epoch_forge/lib_efo/src/worldgen.rs

357 lines
11 KiB
Rust

//! Deterministic, configuration-driven world generation.
use std::{fs, path::Path};
use rand::{Rng, SeedableRng, rngs::StdRng, seq::IndexedRandom};
use serde::{Deserialize, Serialize};
use uuid::Uuid;
use crate::{
entity::Entity,
epoch::EpochInfo,
repository_format::FormatVersion,
stats::{EntityType, Position},
};
/// Schema understood by this build for world-generation configuration.
pub const CURRENT_CONFIG_VERSION: FormatVersion = FormatVersion { major: 1, minor: 0 };
/// Embedded, offline-safe default configuration.
pub const DEFAULT_CONFIG_JSON: &str = include_str!("../assets/worldgen/default.json");
/// Amount of state to generate.
#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
pub enum GenerationLevel {
/// One positioned event.
Event,
/// One town with residents and a local event.
Settlement,
/// A medium subset of the configured world.
Region,
/// A complete configured world.
World,
}
/// Inclusive entity-count range.
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CountRange {
/// Smallest generated count.
pub min: usize,
/// Largest generated count.
pub max: usize,
}
/// Output canvas and coordinate bounds.
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CanvasConfig {
/// Width in pixels/world units.
pub width: u32,
/// Height in pixels/world units.
pub height: u32,
}
/// Configured ranges for every persisted entity collection.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct EntityCounts {
/// Character count.
pub characters: CountRange,
/// Town count.
pub towns: CountRange,
/// Event count.
pub events: CountRange,
/// Calamity count.
pub calamities: CountRange,
/// Organisation count.
pub organisations: CountRange,
/// Blocker count.
pub blockers: CountRange,
}
/// Name pools used by deterministic generation.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct NamePools {
/// Character names.
pub characters: Vec<String>,
/// Town names.
pub towns: Vec<String>,
/// Event names.
pub events: Vec<String>,
/// Calamity names.
pub calamities: Vec<String>,
/// Organisation names.
pub organisations: Vec<String>,
/// Blocker names.
pub blockers: Vec<String>,
}
/// Complete versioned input for the generator.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct WorldGenConfig {
/// Configuration schema, independent from repository format.
pub schema_version: FormatVersion,
/// Spatial bounds.
pub canvas: CanvasConfig,
/// Full-world collection ranges.
pub counts: EntityCounts,
/// User-editable naming pools.
pub names: NamePools,
}
/// Configuration and generation failures.
#[derive(Debug, thiserror::Error)]
pub enum WorldGenError {
/// Reading an external configuration failed.
#[error("cannot read worldgen config `{path}`: {source}")]
Io {
/// Affected file.
path: std::path::PathBuf,
/// Filesystem failure.
#[source]
source: std::io::Error,
},
/// JSON did not match the schema.
#[error("invalid worldgen config `{path}`: {source}")]
Json {
/// Embedded label or external file.
path: std::path::PathBuf,
/// Decode failure.
#[source]
source: serde_json::Error,
},
/// Semantic validation rejected otherwise valid JSON.
#[error("invalid worldgen configuration: {0}")]
Invalid(String),
}
impl WorldGenConfig {
/// Load and validate the embedded defaults.
pub fn embedded() -> Result<Self, WorldGenError> {
Self::decode(
DEFAULT_CONFIG_JSON.as_bytes(),
Path::new("<embedded worldgen config>"),
)
}
/// Load and validate an external override.
pub fn load(path: &Path) -> Result<Self, WorldGenError> {
let bytes = fs::read(path).map_err(|source| WorldGenError::Io {
path: path.to_owned(),
source,
})?;
Self::decode(&bytes, path)
}
/// Decode and validate bytes while retaining their diagnostic source.
fn decode(bytes: &[u8], path: &Path) -> Result<Self, WorldGenError> {
let config: Self = serde_json::from_slice(bytes).map_err(|source| WorldGenError::Json {
path: path.to_owned(),
source,
})?;
config.validate()?;
Ok(config)
}
/// Validate limits before allocation or generation.
pub fn validate(&self) -> Result<(), WorldGenError> {
if self.schema_version != CURRENT_CONFIG_VERSION {
return Err(WorldGenError::Invalid(format!(
"schema {} is unsupported; expected {}",
self.schema_version, CURRENT_CONFIG_VERSION
)));
}
if self.canvas.width == 0
|| self.canvas.height == 0
|| self.canvas.width > 100_000
|| self.canvas.height > 100_000
{
return Err(WorldGenError::Invalid(
"canvas dimensions must each be between 1 and 100000".into(),
));
}
let entries = [
("characters", self.counts.characters, &self.names.characters),
("towns", self.counts.towns, &self.names.towns),
("events", self.counts.events, &self.names.events),
("calamities", self.counts.calamities, &self.names.calamities),
(
"organisations",
self.counts.organisations,
&self.names.organisations,
),
("blockers", self.counts.blockers, &self.names.blockers),
];
for (label, range, names) in entries {
if range.min > range.max || range.max > 10_000 {
return Err(WorldGenError::Invalid(format!(
"{label} count must be ordered and no greater than 10000"
)));
}
if range.max > 0 && names.is_empty() {
return Err(WorldGenError::Invalid(format!(
"{label} names cannot be empty when entities may be generated"
)));
}
}
Ok(())
}
}
/// Generate a deterministic complete snapshot from a validated configuration.
pub fn generate(config: &WorldGenConfig, seed: u64, level: GenerationLevel) -> EpochInfo {
let mut rng = StdRng::seed_from_u64(seed);
let mut world = EpochInfo {
rng_seed: seed,
..EpochInfo::default()
};
let counts = selected_counts(config, level, &mut rng);
world.characters = entities(
&config.names.characters,
counts[0],
EntityType::Character,
config,
&mut rng,
);
world.towns = entities(
&config.names.towns,
counts[1],
EntityType::Town,
config,
&mut rng,
);
world.events = entities(
&config.names.events,
counts[2],
EntityType::Event,
config,
&mut rng,
);
world.calamities = entities(
&config.names.calamities,
counts[3],
EntityType::Calamity,
config,
&mut rng,
);
world.organizations = entities(
&config.names.organisations,
counts[4],
EntityType::Organization,
config,
&mut rng,
);
world.blockers = entities(
&config.names.blockers,
counts[5],
EntityType::Blocker,
config,
&mut rng,
);
world
}
/// Resolve configured ranges into concrete counts for one generation level.
fn selected_counts(
config: &WorldGenConfig,
level: GenerationLevel,
rng: &mut StdRng,
) -> [usize; 6] {
match level {
GenerationLevel::Event => [0, 0, 1, 0, 0, 0],
GenerationLevel::Settlement => [rng.random_range(3..=6), 1, 1, 0, 0, 0],
GenerationLevel::Region => [
pick(config.counts.characters, rng).div_ceil(2),
pick(config.counts.towns, rng).max(1).div_ceil(2),
pick(config.counts.events, rng).max(1).div_ceil(2),
pick(config.counts.calamities, rng).div_ceil(2),
pick(config.counts.organisations, rng).div_ceil(2),
pick(config.counts.blockers, rng).div_ceil(2),
],
GenerationLevel::World => [
pick(config.counts.characters, rng),
pick(config.counts.towns, rng),
pick(config.counts.events, rng),
pick(config.counts.calamities, rng),
pick(config.counts.organisations, rng),
pick(config.counts.blockers, rng),
],
}
}
/// Pick an inclusive count reproducibly.
fn pick(range: CountRange, rng: &mut StdRng) -> usize {
rng.random_range(range.min..=range.max)
}
/// Build one positioned entity collection from a name pool.
fn entities(
names: &[String],
count: usize,
kind: EntityType,
config: &WorldGenConfig,
rng: &mut StdRng,
) -> Vec<Entity> {
(0..count)
.map(|index| {
let base = names
.choose(rng)
.cloned()
.unwrap_or_else(|| "Unnamed".to_owned());
let mut entity = Entity::default();
entity.name = format!("{base} {}", index + 1);
entity.id = Uuid::from_u128(rng.random());
entity.entity_type = kind;
entity.modify_position(Position::from((
rng.random_range(0..config.canvas.width) as isize,
rng.random_range(0..config.canvas.height) as isize,
)));
entity
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn embedded_config_is_valid() {
WorldGenConfig::embedded().expect("valid embedded config");
}
#[test]
fn the_same_seed_replays_exactly() {
let config = WorldGenConfig::embedded().expect("config");
let first = generate(&config, 42, GenerationLevel::World);
let second = generate(&config, 42, GenerationLevel::World);
assert_eq!(
serde_json::to_value(first).expect("first"),
serde_json::to_value(second).expect("second")
);
}
#[test]
fn levels_are_cumulative_in_scope() {
let config = WorldGenConfig::embedded().expect("config");
let event = generate(&config, 7, GenerationLevel::Event);
assert_eq!(event.events.len(), 1);
assert!(event.towns.is_empty());
let settlement = generate(&config, 7, GenerationLevel::Settlement);
assert_eq!(settlement.towns.len(), 1);
assert!(!settlement.characters.is_empty());
}
#[test]
fn invalid_ranges_and_empty_pools_are_rejected() {
let mut config = WorldGenConfig::embedded().expect("config");
config.counts.towns = CountRange { min: 3, max: 2 };
assert!(config.validate().is_err());
config.counts.towns = CountRange { min: 1, max: 2 };
config.names.towns.clear();
assert!(config.validate().is_err());
}
}