Skip to main content

voxel_framework/generator/
terrain.rs

1//! Procedural heightmap terrain generator for [`DefaultTerrainVoxel`].
2//!
3//! `TerrainGenerator` uses fractal Brownian motion (FBM) noise to build a
4//! classic layered terrain: grass on top, dirt below, stone underneath, and
5//! sand at low elevations near the water line.
6//!
7//! # Integration
8//!
9//! ```no_run
10//! use std::sync::Arc;
11//! use bevy::prelude::*;
12//! use voxel_framework::{
13//!     VoxelPlugin,
14//!     generator::{GeneratorPlugin, GeneratorResource},
15//!     generator::terrain::{TerrainConfig, TerrainGenerator},
16//!     voxel::DefaultTerrainVoxel,
17//! };
18//!
19//! App::new()
20//!     .add_plugins(DefaultPlugins)
21//!     .add_plugins(VoxelPlugin::<DefaultTerrainVoxel>::new())
22//!     .add_plugins(GeneratorPlugin::<DefaultTerrainVoxel>::new())
23//!     .insert_resource(GeneratorResource::<DefaultTerrainVoxel> {
24//!         generator: Arc::new(TerrainGenerator::new(TerrainConfig::default())),
25//!     })
26//!     .run();
27//! ```
28
29use bevy::math::IVec3;
30
31use crate::chunk::{CHUNK_SIZE, Chunk};
32use crate::noise::{fbm, hash3};
33use crate::voxel::DefaultTerrainVoxel;
34
35use super::ChunkGenerator;
36
37/// Configuration for [`TerrainGenerator`].
38///
39/// Controls the overall shape and scale of the generated terrain. All fields
40/// have sensible defaults via [`Default`]; call [`TerrainConfig::default`] for
41/// a ready-to-use configuration.
42#[derive(Debug, Clone)]
43pub struct TerrainConfig {
44    /// Seed value passed to the FBM noise function.
45    ///
46    /// Different seeds produce entirely different terrain layouts.
47    /// **Default: `42`.**
48    pub seed: u32,
49    /// Maximum terrain height in world units.
50    ///
51    /// The FBM output (normalized to `[0, 1]`) is multiplied by this value to
52    /// produce the surface Y coordinate. **Default: `48.0`.**
53    pub height_scale: f32,
54    /// Base frequency of the FBM noise.
55    ///
56    /// Lower values produce broader, smoother hills; higher values produce
57    /// jagged, fine-grained terrain. **Default: `0.008`.**
58    pub frequency: f32,
59    /// World Y below which sand replaces the normal grass/dirt surface.
60    ///
61    /// Voxels at or below this threshold and within the surface layers are
62    /// filled with `Sand` instead, simulating a beach or desert floor.
63    /// **Default: `5.0`.**
64    pub sand_level: f32,
65    /// World Y up to which air voxels at or below the surface are filled with
66    /// [`DefaultTerrainVoxel::Water`].
67    ///
68    /// Columns whose surface height is at or below this level get their
69    /// above-surface air replaced with water up to `water_level`. Set to a
70    /// negative value to disable water entirely. **Default: `4.0`.**
71    pub water_level: f32,
72    /// Whether to place procedural trees on grass surfaces.
73    ///
74    /// When `true`, roughly 1 in 20 grass-topped columns receive a tree (trunk
75    /// + leaf crown). **Default: `true`.**
76    pub trees_enabled: bool,
77    /// Whether to vary terrain surface type and height by biome.
78    ///
79    /// When `true`, a low-frequency noise layer assigns one of four biomes
80    /// (Desert, Plains, Forest, Snow) per region. Each biome changes the
81    /// surface voxel, height scale multiplier, and tree density.
82    /// **Default: `true`.**
83    pub biomes_enabled: bool,
84}
85
86impl Default for TerrainConfig {
87    fn default() -> Self {
88        Self {
89            seed: 42,
90            height_scale: 48.0,
91            frequency: 0.008,
92            sand_level: 5.0,
93            water_level: 4.0,
94            trees_enabled: true,
95            biomes_enabled: true,
96        }
97    }
98}
99
100/// Procedural terrain generator that fills chunks using FBM heightmap data.
101///
102/// For each XZ column the generator computes a surface height from
103/// [`fbm`] noise and layers voxel materials as follows:
104///
105/// | World Y relative to surface | Material |
106/// |---|---|
107/// | Above surface | `Air` |
108/// | Top layer (surface - 1) | `Grass` (or `Sand` below `sand_level`) |
109/// | Next 4 layers | `Dirt` (or `Sand` below `sand_level`) |
110/// | Anything deeper | `Stone` |
111///
112/// The generator implements [`ChunkGenerator<DefaultTerrainVoxel>`] and can be
113/// stored in a [`crate::generator::GeneratorResource`].
114pub struct TerrainGenerator {
115    config: TerrainConfig,
116}
117
118impl TerrainGenerator {
119    /// Creates a new generator with the given configuration.
120    pub fn new(config: TerrainConfig) -> Self {
121        Self { config }
122    }
123}
124
125// ─── Biome helpers ────────────────────────────────────────────────────────────
126
127/// Biome type for a terrain column.
128#[derive(Clone, Copy, PartialEq, Eq)]
129enum Biome {
130    /// Flat sandy desert with no trees and lower height variation.
131    Desert,
132    /// Grassy plains with occasional trees and moderate height.
133    Plains,
134    /// Dense forest with many trees and taller, rougher hills.
135    Forest,
136    /// Snowy peaks with no trees and the tallest height scale.
137    Snow,
138}
139
140impl Biome {
141    /// Returns the height scale multiplier for this biome (applied on top of
142    /// [`TerrainConfig::height_scale`]).
143    fn height_multiplier(self) -> f32 {
144        match self {
145            Biome::Desert => 0.5,
146            Biome::Plains => 0.8,
147            Biome::Forest => 1.0,
148            Biome::Snow => 1.4,
149        }
150    }
151
152    /// Returns the surface and sub-surface voxel for this biome.
153    /// `(surface_top, sub_surface)` — top layer and the 4 layers below it.
154    fn surface_voxels(self) -> (DefaultTerrainVoxel, DefaultTerrainVoxel) {
155        match self {
156            Biome::Desert => (DefaultTerrainVoxel::Sand, DefaultTerrainVoxel::Sand),
157            Biome::Plains => (DefaultTerrainVoxel::Grass, DefaultTerrainVoxel::Dirt),
158            Biome::Forest => (DefaultTerrainVoxel::Grass, DefaultTerrainVoxel::Dirt),
159            Biome::Snow => (DefaultTerrainVoxel::Snow, DefaultTerrainVoxel::Gravel),
160        }
161    }
162
163    /// Returns whether trees should grow in this biome and the modulo divisor
164    /// controlling density (lower = denser). `None` means no trees.
165    fn tree_density(self) -> Option<u32> {
166        match self {
167            Biome::Desert => None,
168            Biome::Plains => Some(30), // ~1 in 30 columns
169            Biome::Forest => Some(8),  // ~1 in 8 columns — dense
170            Biome::Snow => None,
171        }
172    }
173}
174
175/// Samples the biome at a world XZ coordinate using a very low-frequency FBM.
176///
177/// The biome noise uses `seed + 1000` so it is independent of the heightmap
178/// noise. Returns one of four [`Biome`] variants.
179fn sample_biome(wx: f32, wz: f32, seed: u32) -> Biome {
180    // Very slow noise (0.001) so biome regions span ~300 world units each.
181    let n = fbm(wx, 0.0, wz, seed.wrapping_add(1000), 2, 0.001, 2.0, 0.5);
182    if n < -0.33 {
183        Biome::Desert
184    } else if n < 0.2 {
185        Biome::Plains
186    } else if n < 0.6 {
187        Biome::Forest
188    } else {
189        Biome::Snow
190    }
191}
192
193/// Places a tree centered at the given local column `(lx, lz)` with the trunk
194/// base at local Y `trunk_base_ly`. Only voxels whose local Y falls within
195/// `[0, CHUNK_SIZE)` are written; out-of-range positions are silently skipped.
196/// Leaves do not overwrite non-air voxels so trunks and solid terrain win.
197fn place_tree(chunk: &mut Chunk<DefaultTerrainVoxel>, lx: usize, lz: usize, trunk_base_ly: usize) {
198    const TRUNK_HEIGHT: usize = 4;
199    const CROWN_RADIUS: i32 = 2;
200    const CROWN_HEIGHT: usize = 4;
201
202    // Trunk: 4 Wood blocks stacked directly above the surface.
203    for h in 0..TRUNK_HEIGHT {
204        let ly = trunk_base_ly + h;
205        if lx < CHUNK_SIZE && lz < CHUNK_SIZE && ly < CHUNK_SIZE {
206            chunk.set(lx, ly, lz, DefaultTerrainVoxel::Wood);
207        }
208    }
209
210    // Crown: Chebyshev-distance sphere of Leaves centered above the trunk top.
211    let crown_center_ly = trunk_base_ly + TRUNK_HEIGHT;
212    for dy in 0..CROWN_HEIGHT {
213        for dx in -CROWN_RADIUS..=CROWN_RADIUS {
214            for dz in -CROWN_RADIUS..=CROWN_RADIUS {
215                let dist = dx.abs().max(dz.abs()).max(dy as i32 - 1);
216                if dist > CROWN_RADIUS {
217                    continue;
218                }
219                let cx = lx as i32 + dx;
220                let cy = crown_center_ly as i32 + dy as i32;
221                let cz = lz as i32 + dz;
222                if cx < 0 || cy < 0 || cz < 0 {
223                    continue;
224                }
225                let (cx, cy, cz) = (cx as usize, cy as usize, cz as usize);
226                if cx < CHUNK_SIZE
227                    && cy < CHUNK_SIZE
228                    && cz < CHUNK_SIZE
229                    && chunk.get(cx, cy, cz) == DefaultTerrainVoxel::Air
230                {
231                    chunk.set(cx, cy, cz, DefaultTerrainVoxel::Leaves);
232                }
233            }
234        }
235    }
236}
237
238impl ChunkGenerator<DefaultTerrainVoxel> for TerrainGenerator {
239    fn generate(&self, coord: IVec3, chunk: &mut Chunk<DefaultTerrainVoxel>) {
240        let cfg = &self.config;
241        let chunk_world_y = coord.y * CHUNK_SIZE as i32;
242
243        // Track per-column surface info for the tree pass.
244        let mut surface_info: Vec<Option<(usize, bool)>> = vec![None; CHUNK_SIZE * CHUNK_SIZE];
245
246        for lx in 0..CHUNK_SIZE {
247            for lz in 0..CHUNK_SIZE {
248                let wx = (coord.x * CHUNK_SIZE as i32 + lx as i32) as f32;
249                let wz = (coord.z * CHUNK_SIZE as i32 + lz as i32) as f32;
250
251                // Biome determines height multiplier and surface materials.
252                let biome = if cfg.biomes_enabled {
253                    sample_biome(wx, wz, cfg.seed)
254                } else {
255                    Biome::Plains
256                };
257                let effective_height = cfg.height_scale * biome.height_multiplier();
258
259                // FBM output is in [-1, 1] — normalize to [0, 1] then scale.
260                let noise = fbm(wx, 0.0, wz, cfg.seed, 4, cfg.frequency, 2.0, 0.5);
261                let surface_y = (noise * 0.5 + 0.5) * effective_height;
262
263                // Override surface voxels based on biome (sand_level still applies).
264                let (top_voxel, sub_voxel) = if surface_y <= cfg.sand_level {
265                    (DefaultTerrainVoxel::Sand, DefaultTerrainVoxel::Sand)
266                } else {
267                    biome.surface_voxels()
268                };
269
270                let can_have_trees = cfg.trees_enabled
271                    && top_voxel == DefaultTerrainVoxel::Grass
272                    && biome.tree_density().is_some();
273
274                for ly in 0..CHUNK_SIZE {
275                    let wy = (chunk_world_y + ly as i32) as f32;
276
277                    let voxel = if wy >= surface_y {
278                        // Above terrain surface — fill with water if below water level.
279                        if wy < cfg.water_level {
280                            DefaultTerrainVoxel::Water
281                        } else {
282                            DefaultTerrainVoxel::Air
283                        }
284                    } else if wy >= surface_y - 1.0 {
285                        top_voxel
286                    } else if wy >= surface_y - 5.0 {
287                        sub_voxel
288                    } else {
289                        DefaultTerrainVoxel::Stone
290                    };
291
292                    chunk.set(lx, ly, lz, voxel);
293                }
294
295                // Record surface for tree pass.
296                if can_have_trees {
297                    let surface_world_ly = surface_y.ceil() as i32 - chunk_world_y;
298                    if surface_world_ly >= 0 && surface_world_ly < CHUNK_SIZE as i32 {
299                        surface_info[lz * CHUNK_SIZE + lx] =
300                            Some((surface_world_ly as usize, true));
301                    }
302                }
303            }
304        }
305
306        // Tree placement pass.
307        if cfg.trees_enabled {
308            for lx in 0..CHUNK_SIZE {
309                for lz in 0..CHUNK_SIZE {
310                    if let Some((trunk_base_ly, _)) = surface_info[lz * CHUNK_SIZE + lx] {
311                        let wx_i = coord.x * CHUNK_SIZE as i32 + lx as i32;
312                        let wz_i = coord.z * CHUNK_SIZE as i32 + lz as i32;
313                        let wx = wx_i as f32;
314                        let wz = wz_i as f32;
315                        let biome = if cfg.biomes_enabled {
316                            sample_biome(wx, wz, cfg.seed)
317                        } else {
318                            Biome::Plains
319                        };
320                        if let Some(density) = biome.tree_density() {
321                            let h =
322                                ((hash3(wx_i, 0, wz_i, cfg.seed) * 0.5 + 0.5) * 1_000_000.0) as u32;
323                            if h % density == 0 {
324                                place_tree(chunk, lx, lz, trunk_base_ly);
325                            }
326                        }
327                    }
328                }
329            }
330        }
331    }
332}
333
334// ─── Tests ────────────────────────────────────────────────────────────────────
335
336#[cfg(test)]
337mod tests {
338    use super::*;
339    use crate::voxel::VoxelType;
340
341    fn make_gen() -> TerrainGenerator {
342        TerrainGenerator::new(TerrainConfig::default())
343    }
344
345    #[test]
346    fn test_terrain_surface_chunk_has_grass() {
347        let tgen = make_gen();
348        // Chunk at y=1 should contain surface-level voxels (height_scale=48,
349        // so surface is in [0, 48] ⊆ chunks y=0..y=3).
350        let mut chunk = Chunk::new();
351        tgen.generate(IVec3::new(0, 1, 0), &mut chunk);
352        // There should be at least some non-air voxels.
353        let solid_count = (0..CHUNK_SIZE)
354            .flat_map(|x| {
355                (0..CHUNK_SIZE).flat_map(move |y| (0..CHUNK_SIZE).map(move |z| (x, y, z)))
356            })
357            .filter(|&(x, y, z)| chunk.get(x, y, z).is_solid())
358            .count();
359        assert!(solid_count > 0, "surface chunk must have solid voxels");
360    }
361
362    #[test]
363    fn test_terrain_deep_chunk_is_all_stone() {
364        let tgen = make_gen();
365        // Chunk at y=-10 is far below any surface (height_scale=48, min surface=0).
366        let mut chunk = Chunk::new();
367        tgen.generate(IVec3::new(0, -10, 0), &mut chunk);
368        for x in 0..CHUNK_SIZE {
369            for y in 0..CHUNK_SIZE {
370                for z in 0..CHUNK_SIZE {
371                    assert_eq!(
372                        chunk.get(x, y, z),
373                        DefaultTerrainVoxel::Stone,
374                        "deep chunk voxel ({x},{y},{z}) should be Stone"
375                    );
376                }
377            }
378        }
379    }
380
381    #[test]
382    fn test_terrain_high_chunk_is_all_air() {
383        let tgen = make_gen();
384        // Chunk at y=10 is above max terrain height (height_scale=48, max=48 < 160).
385        let mut chunk = Chunk::new();
386        tgen.generate(IVec3::new(0, 10, 0), &mut chunk);
387        for x in 0..CHUNK_SIZE {
388            for y in 0..CHUNK_SIZE {
389                for z in 0..CHUNK_SIZE {
390                    assert_eq!(
391                        chunk.get(x, y, z),
392                        DefaultTerrainVoxel::Air,
393                        "high chunk voxel ({x},{y},{z}) should be Air"
394                    );
395                }
396            }
397        }
398    }
399
400    #[test]
401    fn test_terrain_deterministic() {
402        let tgen = make_gen();
403        let mut a = Chunk::new();
404        let mut b = Chunk::new();
405        tgen.generate(IVec3::new(3, 1, -2), &mut a);
406        tgen.generate(IVec3::new(3, 1, -2), &mut b);
407        for x in 0..CHUNK_SIZE {
408            for y in 0..CHUNK_SIZE {
409                for z in 0..CHUNK_SIZE {
410                    assert_eq!(
411                        a.get(x, y, z),
412                        b.get(x, y, z),
413                        "same coord must produce identical voxels"
414                    );
415                }
416            }
417        }
418    }
419}