Skip to main content

voxel_framework/world/
config.rs

1//! World configuration loaded from `world.toml` at startup.
2//!
3//! # Overview
4//!
5//! [`WorldConfig`] is a Bevy [`Resource`] that centralises every
6//! data-driven parameter the engine needs at startup: the world seed,
7//! streaming distances, asteroid generation settings, scene lighting, and
8//! skybox mode.
9//!
10//! # Where it is read from
11//!
12//! [`WorldConfigPlugin`] runs a [`Startup`] system that calls
13//! [`WorldConfig::from_file`] with the path `"world.toml"`, resolved relative
14//! to the **process working directory**. For games launched via `cargo run`,
15//! this is the workspace root. For distributed builds it is the directory
16//! containing the executable.
17//!
18//! # Fallback behavior
19//!
20//! If `world.toml` is absent, unreadable, or contains invalid TOML,
21//! [`WorldConfig::default`] is used and a diagnostic message is printed to
22//! stderr. No panic occurs. The fallback values are documented on each field
23//! of [`WorldConfig`].
24//!
25//! # When it is applied
26//!
27//! After loading (or falling back), the plugin inserts [`WorldConfig`] as a
28//! Bevy [`Resource`] and copies `load_distance` / `unload_distance` into the
29//! existing [`ChunkManager`] resource so the streaming system uses the
30//! configured distances immediately.
31
32use bevy::prelude::*;
33
34use crate::generator::asteroid::{AsteroidConfig, AsteroidGenerator};
35use crate::skybox::{SkyboxConfig, SkyboxMode, StarfieldConfig};
36use crate::world::ChunkManager;
37#[cfg(feature = "crafting")]
38use crate::world::manifest::WorldManifest;
39
40// ─── Config structs ───────────────────────────────────────────────────────────
41
42/// Asteroid-generation parameters as read from the `[asteroids]` TOML section.
43///
44/// This is a serialization-only mirror of
45/// [`crate::generator::asteroid::AsteroidConfig`], kept separate to avoid
46/// coupling TOML deserialization to the runtime generator type (which uses
47/// `u32` seeds and `usize` counts internally). Call
48/// [`WorldConfig::build_asteroid_generator`] to convert this into an
49/// [`crate::generator::asteroid::AsteroidGenerator`].
50///
51/// | Field | Default | Description |
52/// |---|---|---|
53/// | `seed` | `42` | `u64` seed truncated to `u32` for the PRNG |
54/// | `count` | `20` | Number of asteroids to place |
55/// | `min_radius` | `15.0` | Minimum asteroid radius in world units |
56/// | `max_radius` | `40.0` | Maximum asteroid radius in world units |
57#[derive(Debug, Clone, serde::Deserialize)]
58pub struct AsteroidConfigToml {
59    /// Seed for deterministic asteroid placement. Truncated to `u32` at runtime.
60    pub seed: u64,
61    /// Number of asteroids to generate. Default: `20`.
62    pub count: u32,
63    /// Minimum asteroid radius in world units. Default: `15.0`.
64    pub min_radius: f32,
65    /// Maximum asteroid radius in world units. Default: `40.0`.
66    pub max_radius: f32,
67}
68
69impl Default for AsteroidConfigToml {
70    fn default() -> Self {
71        Self {
72            seed: 42,
73            count: 20,
74            min_radius: 15.0,
75            max_radius: 40.0,
76        }
77    }
78}
79
80/// Skybox parameters as read from the `[skybox]` TOML section.
81///
82/// Converted into a [`crate::skybox::SkyboxConfig`] at startup by
83/// [`WorldConfig::build_skybox_config`].
84///
85/// | Field | Default | Description |
86/// |---|---|---|
87/// | `mode` | `"starfield"` | `"starfield"` or `"color"` |
88/// | `star_count` | `800` | Number of point-light stars (starfield mode only) |
89/// | `star_radius` | `900.0` | Distance of stars from the origin in world units |
90/// | `background_color` | `None` | RGBA clear color as `[r, g, b, a]` (color mode only) |
91#[derive(Debug, Clone, serde::Deserialize)]
92pub struct SkyboxConfigToml {
93    /// Skybox rendering mode: `"starfield"` or `"color"`. Default: `"starfield"`.
94    pub mode: String,
95    /// Number of stars rendered in starfield mode. Default: `800`.
96    pub star_count: u32,
97    /// Radius at which stars are placed from the world origin. Default: `900.0`.
98    pub star_radius: f32,
99    /// Clear color in `[r, g, b, a]` format, used only in `"color"` mode.
100    /// Defaults to opaque black `[0.0, 0.0, 0.0, 1.0]` when `None`.
101    pub background_color: Option<[f32; 4]>,
102}
103
104impl Default for SkyboxConfigToml {
105    fn default() -> Self {
106        Self {
107            mode: "starfield".to_string(),
108            star_count: 800,
109            star_radius: 900.0,
110            background_color: None,
111        }
112    }
113}
114
115/// Scene lighting parameters as read from the `[lighting]` TOML section.
116///
117/// | Field | Default | Description |
118/// |---|---|---|
119/// | `sun_illuminance` | `15000.0` | Directional sun light illuminance in lux |
120/// | `ambient_brightness` | `0.1` | Global ambient light intensity (0 = dark, 1 = full) |
121#[derive(Debug, Clone, serde::Deserialize)]
122pub struct LightingConfig {
123    /// Illuminance of the directional sun light in lux. Default: `15000.0`.
124    pub sun_illuminance: f32,
125    /// Brightness of the scene's ambient light, in the range `[0.0, 1.0]`. Default: `0.1`.
126    pub ambient_brightness: f32,
127}
128
129impl Default for LightingConfig {
130    fn default() -> Self {
131        Self {
132            sun_illuminance: 15000.0,
133            ambient_brightness: 0.1,
134        }
135    }
136}
137
138fn default_world_name() -> String {
139    "world".to_string()
140}
141fn default_example() -> String {
142    "basic_world".to_string()
143}
144fn default_seed() -> u64 {
145    42
146}
147fn default_load_distance() -> f32 {
148    150.0
149}
150fn default_unload_distance() -> f32 {
151    200.0
152}
153
154/// Top-level world configuration loaded from `world.toml`.
155///
156/// Inserted as a Bevy [`Resource`] by [`WorldConfigPlugin`] during the
157/// [`Startup`] schedule. If `world.toml` is absent or malformed,
158/// [`WorldConfig::default`] is used and an error is printed to stderr — no
159/// panic occurs. See the [module docs](self) for the full fallback and
160/// application flow.
161///
162/// After loading, call the builder helpers to construct runtime types:
163/// - [`build_asteroid_generator`](WorldConfig::build_asteroid_generator) →
164///   [`crate::generator::asteroid::AsteroidGenerator`]
165/// - [`build_skybox_config`](WorldConfig::build_skybox_config) →
166///   [`crate::skybox::SkyboxConfig`]
167///
168/// # Field defaults (when `world.toml` is absent)
169///
170/// | Field | Default |
171/// |---|---|
172/// | `world_name` | `"world"` |
173/// | `seed` | `42` |
174/// | `spawn_position` | `[0.0, 0.0, 0.0]` |
175/// | `load_distance` | `150.0` |
176/// | `unload_distance` | `200.0` |
177/// | `asteroids` | see [`AsteroidConfigToml::default`] |
178/// | `lighting` | see [`LightingConfig::default`] |
179/// | `skybox` | see [`SkyboxConfigToml::default`] |
180///
181/// # Example
182///
183/// ```rust,no_run
184/// use voxel_framework::world::WorldConfig;
185///
186/// let config = WorldConfig::from_file("world.toml").unwrap_or_default();
187/// println!("world = {}", config.world_name);
188/// println!("seed = {}", config.seed);
189/// ```
190#[derive(Resource, Debug, Clone, serde::Deserialize)]
191pub struct WorldConfig {
192    /// Which example game to run when launched via `examples/voxel.rs`.
193    ///
194    /// Recognized values: `"basic_world"`, `"minetest"`.  Default: `"basic_world"`.
195    #[serde(default = "default_example")]
196    pub example: String,
197    /// Name of this world, used as the folder under `worlds/` for chunk and
198    /// player data storage.  Default: `"world"`.
199    ///
200    /// Set in the world TOML as `world_name = "survival"`.  The framework stores
201    /// all data for this world under `./worlds/{world_name}/`.
202    #[serde(default = "default_world_name")]
203    pub world_name: String,
204    /// Global world seed used for all deterministic generation. Default: `42`.
205    #[serde(default = "default_seed")]
206    pub seed: u64,
207    /// Player/viewer spawn position in world space as `[x, y, z]`. Default: `[0.0, 0.0, 0.0]`.
208    #[serde(default)]
209    pub spawn_position: [f32; 3],
210    /// Radius in world units within which chunks are loaded. Default: `150.0`.
211    ///
212    /// Copied into [`ChunkManager::load_distance`] by [`WorldConfigPlugin`].
213    #[serde(default = "default_load_distance")]
214    pub load_distance: f32,
215    /// Radius in world units beyond which chunks are unloaded. Default: `200.0`.
216    ///
217    /// Must be greater than [`load_distance`](WorldConfig::load_distance) to
218    /// maintain the hysteresis band. Copied into
219    /// [`ChunkManager::unload_distance`] by [`WorldConfigPlugin`].
220    #[serde(default = "default_unload_distance")]
221    pub unload_distance: f32,
222    /// Asteroid generation parameters from the `[asteroids]` section.
223    #[serde(default)]
224    pub asteroids: AsteroidConfigToml,
225    /// Scene lighting parameters from the `[lighting]` section.
226    #[serde(default)]
227    pub lighting: LightingConfig,
228    /// Skybox configuration from the `[skybox]` section. Defaults to a
229    /// starfield when the section is absent.
230    #[serde(default)]
231    pub skybox: SkyboxConfigToml,
232}
233
234impl Default for WorldConfig {
235    fn default() -> Self {
236        Self {
237            example: "basic_world".to_string(),
238            world_name: "world".to_string(),
239            seed: 42,
240            spawn_position: [0.0, 0.0, 0.0],
241            load_distance: 150.0,
242            unload_distance: 200.0,
243            asteroids: AsteroidConfigToml::default(),
244            lighting: LightingConfig::default(),
245            skybox: SkyboxConfigToml::default(),
246        }
247    }
248}
249
250impl WorldConfig {
251    /// Constructs an [`AsteroidGenerator`] from the `[asteroids]` configuration.
252    ///
253    /// Bridges the TOML-friendly [`AsteroidConfigToml`] (which uses `u64` for
254    /// the seed and `u32` for the count) to the runtime
255    /// [`crate::generator::asteroid::AsteroidConfig`] type (which uses `u32`
256    /// and `usize` respectively). The seed is truncated — values above
257    /// `u32::MAX` wrap silently.
258    ///
259    /// Fields not present in [`AsteroidConfigToml`] (e.g. noise octaves) are
260    /// filled from [`crate::generator::asteroid::AsteroidConfig::default`].
261    ///
262    /// Call this once during startup, typically inside the system that sets up
263    /// the world generator:
264    ///
265    /// ```rust,no_run
266    /// use bevy::prelude::*;
267    /// use voxel_framework::world::WorldConfig;
268    ///
269    /// fn setup(config: Res<WorldConfig>) {
270    ///     let generator = config.build_asteroid_generator();
271    ///     // hand `generator` to your chunk generation system
272    /// }
273    /// ```
274    pub fn build_asteroid_generator(&self) -> AsteroidGenerator {
275        AsteroidGenerator::new(AsteroidConfig {
276            seed: self.asteroids.seed as u32,
277            asteroid_count: self.asteroids.count as usize,
278            min_radius: self.asteroids.min_radius,
279            max_radius: self.asteroids.max_radius,
280            ..AsteroidConfig::default()
281        })
282    }
283
284    /// Converts [`SkyboxConfigToml`] into a [`SkyboxConfig`] runtime resource.
285    ///
286    /// - `"starfield"` → [`SkyboxMode::Starfield`] using `star_count` and `star_radius`.
287    /// - `"color"` → [`SkyboxMode::Color`] using `background_color` (falls back to black).
288    /// - Any other value falls back to the default starfield.
289    pub fn build_skybox_config(&self) -> SkyboxConfig {
290        let mode = match self.skybox.mode.as_str() {
291            "color" => {
292                let [r, g, b, a] = self.skybox.background_color.unwrap_or([0.0, 0.0, 0.0, 1.0]);
293                SkyboxMode::Color(Color::srgba(r, g, b, a))
294            }
295            _ => SkyboxMode::Starfield(StarfieldConfig {
296                count: self.skybox.star_count,
297                radius: self.skybox.star_radius,
298                ..StarfieldConfig::default()
299            }),
300        };
301        SkyboxConfig { mode }
302    }
303
304    /// Returns the base data directory for this world: `./worlds/{world_name}`.
305    ///
306    /// All world-specific files (chunks, player data) are stored under this path.
307    pub fn world_data_dir(&self) -> String {
308        format!("./worlds/{}", self.world_name)
309    }
310
311    /// Loads a [`WorldConfig`] from a TOML file at `path`.
312    ///
313    /// # Errors
314    ///
315    /// Returns an error in either of these two situations:
316    ///
317    /// - **I/O failure** — the file does not exist, is not readable, or the
318    ///   process lacks permission to open it.
319    /// - **Parse failure** — the file content is not valid TOML, or a required
320    ///   top-level field (`seed`, `spawn_position`, `load_distance`,
321    ///   `unload_distance`, `asteroids`, `lighting`) is missing.
322    ///
323    /// The typical usage pattern is to fall back to [`Default`] on any error:
324    ///
325    /// ```rust,no_run
326    /// use voxel_framework::world::WorldConfig;
327    ///
328    /// let config = WorldConfig::from_file("world.toml").unwrap_or_default();
329    /// ```
330    pub fn from_file(path: &str) -> Result<Self, Box<dyn std::error::Error>> {
331        let content = std::fs::read_to_string(path)?;
332        Self::from_toml_str(&content)
333    }
334
335    /// Parses a [`WorldConfig`] from a TOML string.
336    ///
337    /// Returns an error if the TOML is invalid or missing required fields.
338    pub fn from_toml_str(s: &str) -> Result<Self, Box<dyn std::error::Error>> {
339        let config: Self = toml::from_str(s)?;
340        Ok(config)
341    }
342
343    /// Loads [`WorldConfig`] from a world directory's `world.json` manifest.
344    ///
345    /// Reads `worlds/{world_name}/world.json` and extracts the fields that are
346    /// stored there (`seed`, `spawn_position`, `load_distance`,
347    /// `unload_distance`). All other fields keep their [`Default`] values.
348    ///
349    /// Returns defaults (with `world_name` set) if the file is missing or
350    /// cannot be parsed — no panic occurs.
351    ///
352    /// # Example
353    ///
354    /// ```rust,no_run
355    /// use voxel_framework::world::WorldConfig;
356    ///
357    /// // First run: world.json does not exist yet → defaults.
358    /// // Subsequent runs: world.json was written by WorldManifestPlugin → loaded.
359    /// let config = WorldConfig::from_world_dir("survival");
360    /// println!("seed = {}", config.seed);
361    /// ```
362    #[cfg(feature = "crafting")]
363    pub fn from_world_dir(world_name: &str) -> Self {
364        let world_dir = std::path::Path::new("worlds").join(world_name);
365        match WorldManifest::read(&world_dir) {
366            Ok(manifest) => Self {
367                world_name: manifest.world_name,
368                seed: manifest.seed,
369                spawn_position: manifest.spawn_position,
370                load_distance: manifest.load_distance,
371                unload_distance: manifest.unload_distance,
372                ..Self::default()
373            },
374            Err(e) => {
375                eprintln!(
376                    "voxel-framework: could not read worlds/{}/world.json ({e}), using defaults",
377                    world_name
378                );
379                Self {
380                    world_name: world_name.to_string(),
381                    ..Self::default()
382                }
383            }
384        }
385    }
386}
387
388// ─── Plugin ───────────────────────────────────────────────────────────────────
389
390/// Startup system that loads `WorldConfig` and applies it to [`ChunkManager`].
391///
392/// If the game already inserted a `WorldConfig` resource (e.g. via
393/// `app.insert_resource(my_config)`), this system respects it and only
394/// syncs the distances to `ChunkManager` without overwriting.
395fn load_world_config(
396    mut commands: Commands,
397    mut chunk_manager: ResMut<ChunkManager>,
398    existing: Option<Res<WorldConfig>>,
399) {
400    if let Some(config) = existing {
401        // Game provided its own config — apply distances and skip file loading.
402        chunk_manager.load_distance = config.load_distance;
403        chunk_manager.unload_distance = config.unload_distance;
404        return;
405    }
406
407    let config = WorldConfig::from_file("world.toml")
408        .inspect_err(|e| {
409            eprintln!(
410                "voxel-framework: world.toml not found or invalid ({e}), using default WorldConfig"
411            );
412        })
413        .unwrap_or_default();
414
415    chunk_manager.load_distance = config.load_distance;
416    chunk_manager.unload_distance = config.unload_distance;
417
418    commands.insert_resource(config);
419}
420
421/// Plugin that loads [`WorldConfig`] from `world.toml` on startup.
422///
423/// Registers a [`Startup`] system (`load_world_config`) that:
424///
425/// 1. Calls [`WorldConfig::from_file`]`("world.toml")`.
426/// 2. Falls back to [`WorldConfig::default`] and logs to stderr if the file is
427///    absent or malformed.
428/// 3. Inserts the resolved [`WorldConfig`] as a Bevy [`Resource`].
429/// 4. Copies `load_distance` and `unload_distance` into the existing
430///    [`ChunkManager`] resource so the streaming system honours them from the
431///    very first [`Update`] tick.
432///
433/// Must be added **after** [`super::WorldPlugin`] (which inserts
434/// [`ChunkManager`]):
435///
436/// ```rust,no_run
437/// use bevy::prelude::*;
438/// use voxel_framework::world::{WorldPlugin, WorldConfigPlugin};
439///
440/// App::new()
441///     .add_plugins((WorldPlugin, WorldConfigPlugin))
442///     .run();
443/// ```
444pub struct WorldConfigPlugin;
445
446impl Plugin for WorldConfigPlugin {
447    fn build(&self, app: &mut App) {
448        app.add_systems(Startup, load_world_config);
449    }
450}
451
452// ─── Tests ────────────────────────────────────────────────────────────────────
453
454#[cfg(test)]
455mod tests {
456    use super::*;
457
458    #[test]
459    fn test_default_config_values() {
460        let config = WorldConfig::default();
461        assert_eq!(config.seed, 42);
462        assert_eq!(config.spawn_position, [0.0, 0.0, 0.0]);
463        assert_eq!(config.load_distance, 150.0);
464        assert_eq!(config.unload_distance, 200.0);
465        assert_eq!(config.asteroids.seed, 42);
466        assert_eq!(config.asteroids.count, 20);
467        assert_eq!(config.asteroids.min_radius, 15.0);
468        assert_eq!(config.asteroids.max_radius, 40.0);
469        assert_eq!(config.lighting.sun_illuminance, 15000.0);
470        assert_eq!(config.lighting.ambient_brightness, 0.1);
471    }
472
473    #[test]
474    fn test_from_str_parses_correctly() {
475        let toml = r#"
476seed = 99
477spawn_position = [1.0, 2.0, 3.0]
478load_distance = 120.0
479unload_distance = 180.0
480
481[asteroids]
482seed = 7
483count = 5
484min_radius = 10.0
485max_radius = 50.0
486
487[lighting]
488sun_illuminance = 20000.0
489ambient_brightness = 0.2
490
491[skybox]
492mode = "starfield"
493star_count = 800
494star_radius = 900.0
495"#;
496
497        let config = WorldConfig::from_toml_str(toml).expect("TOML should parse without error");
498
499        assert_eq!(config.seed, 99);
500        assert_eq!(config.spawn_position, [1.0, 2.0, 3.0]);
501        assert_eq!(config.load_distance, 120.0);
502        assert_eq!(config.unload_distance, 180.0);
503        assert_eq!(config.asteroids.seed, 7);
504        assert_eq!(config.asteroids.count, 5);
505        assert_eq!(config.asteroids.min_radius, 10.0);
506        assert_eq!(config.asteroids.max_radius, 50.0);
507        assert_eq!(config.lighting.sun_illuminance, 20000.0);
508        assert_eq!(config.lighting.ambient_brightness, 0.2);
509    }
510}