836 lines
31 KiB
Rust
836 lines
31 KiB
Rust
//! Module that holds all statistics for an entity and the helper methods that operate on them.
|
||
//!
|
||
//! The statistics are grouped into thematic sections (Demographics, Economy, Social, Military,
|
||
//! Infrastructure). Each field is a `GenericStat`, an internal wrapper around a numeric value
|
||
//! that provides convenience methods such as `max()`, `clamp()`, and arithmetic ops.
|
||
//!
|
||
//! The documentation for each field follows the same three-part template:
|
||
//! * **Purpose** - What the stat represents.
|
||
//! * **Effect** - Gameplay consequence of the stat.
|
||
//! * **Source** - Formula or function that generates the stat value.
|
||
|
||
#![deny(clippy::missing_docs_in_private_items)]
|
||
|
||
use crate::{entity::EntityIdentifier, error::EpochError, thin_newtype, utils::RngLevel};
|
||
use cli_table::{CellStruct, Color, Style, Table};
|
||
use colored::Colorize;
|
||
use derive_more::{Add, Display, Mul, Sub};
|
||
use rand::{Rng, distr::Distribution, rngs::ThreadRng};
|
||
use serde::{Deserialize, Serialize};
|
||
use uuid::Uuid;
|
||
mod implementations;
|
||
|
||
/// Aggregated statistics for a single entity.
|
||
///
|
||
/// The struct is intentionally flat to keep access fast; the fields are logically grouped
|
||
/// by comment blocks that describe each thematic section.
|
||
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
|
||
// Derive more
|
||
#[derive(Table, Add, Sub)]
|
||
pub struct OverallStats {
|
||
// ──────────────────────── Demographics ────────────────────────
|
||
/// Total economic health of the entity.
|
||
///
|
||
/// **Purpose** - A single value summarizing all economic indicators.
|
||
/// **Effect** - Drives tax revenue, spending power, and overall economic influence.
|
||
/// **Source** - Sum of `industry`, `science`, `trade`, and other economic contributors.
|
||
#[table(title = "DEM", customize_fn = "color_cell_categories")]
|
||
pub demographics: GenericStat,
|
||
/// Population count.
|
||
///
|
||
/// **Purpose** - The number of citizens living in the entity.
|
||
/// **Effect** - Determines resource consumption, tax base, and potential unrest.
|
||
/// **Source** - Updated by the growth/decay formulas each turn.
|
||
#[table(title = "POP", customize_fn = "color_cell")]
|
||
pub population: GenericStat,
|
||
|
||
/// Per-turn change in population.
|
||
///
|
||
/// **Purpose** - The growth rate of the population.
|
||
/// **Effect** - Predicts future needs and signals potential social unrest.
|
||
/// **Source** - Derived from `population`, `happiness`, and `stability`.
|
||
#[table(title = "GRW", customize_fn = "color_cell")]
|
||
pub growth_rate: GenericStat,
|
||
|
||
/// Crime level (0-1 scale).
|
||
///
|
||
/// **Purpose** - How frequently crimes occur.
|
||
/// **Effect** - Can trigger riots and reduce stability.
|
||
/// **Source** - Result of the crime function (influenced by class disparity and law enforcement).
|
||
#[table(title = "CRM", customize_fn = "color_cell")]
|
||
pub crime: GenericStat,
|
||
|
||
/// Base happiness of the population (0-1 scale).
|
||
///
|
||
/// **Purpose** - A measure of citizen contentment.
|
||
/// **Effect** - Influences productivity, tax compliance, and unrest.
|
||
/// **Source** - Output of the happiness function (affected by class, war, infrastructure).
|
||
#[table(title = "HPY", customize_fn = "color_cell")]
|
||
pub happiness: GenericStat,
|
||
|
||
// ──────────────────────── Economy ────────────────────────
|
||
/// Aggregate economic health of the entity.
|
||
///
|
||
/// **Purpose** - A single value summarizing all economic metrics.
|
||
/// **Effect** - Drives revenue, spending, and empire-wide economic influence.
|
||
/// **Source** - Sum of `food`, `industry`, `science`, `trade`, etc.
|
||
#[table(title = "ECO", customize_fn = "color_cell_categories")]
|
||
pub economy: GenericStat,
|
||
|
||
/// Food produced by the entity.
|
||
///
|
||
/// **Purpose** - Amount of consumable resources available.
|
||
/// **Effect** - Keeps the population alive and productive.
|
||
/// **Source** - `food = farm_yield + tech_level`.
|
||
#[table(title = "FOD", customize_fn = "color_cell")]
|
||
pub food: GenericStat,
|
||
|
||
/// Strength of the industry.
|
||
///
|
||
/// **Purpose** - Industrial production capacity.
|
||
/// **Effect** - Drives tax revenue and unit production.
|
||
/// **Source** - `industry = factory_output + tech_level`.
|
||
#[table(title = "IND", customize_fn = "color_cell")]
|
||
pub industry: GenericStat,
|
||
|
||
/// Scientific output.
|
||
///
|
||
/// **Purpose** - Rate of research progress.
|
||
/// **Effect** - Determines how quickly new technologies are unlocked.
|
||
/// **Source** - `science = research_center_output + tech_level`.
|
||
#[table(title = "SCI", customize_fn = "color_cell")]
|
||
pub science: GenericStat,
|
||
|
||
/// Trade volume / exports.
|
||
///
|
||
/// **Purpose** - Measure of export activity.
|
||
/// **Effect** - Influences influence and wealth.
|
||
/// **Source** - `trade = trade_network_output`.
|
||
#[table(title = "TRD", customize_fn = "color_cell")]
|
||
pub trade: GenericStat,
|
||
// // ──────────────────────── Social ────────────────────────
|
||
// /// Overall social prestige.
|
||
// ///
|
||
// /// **Purpose** - Reflects the cultural standing of the entity.
|
||
// /// **Effect** - Affects diplomacy and citizen morale.
|
||
// /// **Source** - Sum of `culture`, `education`, `tourism`, etc.
|
||
// #[table(title = "SOC", color = "Color::Blue", bold, customize_fn = "color_cell")]
|
||
// pub social: GenericStat,
|
||
|
||
// /// Cultural output from arts, theatres, museums, etc.
|
||
// ///
|
||
// /// **Purpose** - Measure of cultural production.
|
||
// /// **Effect** - Drives tourism, prestige, and happiness.
|
||
// /// **Source** - `culture = Σ(cultural_building_output)`.
|
||
// #[table(title = "CLU", customize_fn = "color_cell")]
|
||
// pub culture: GenericStat,
|
||
|
||
// /// Level of education/literacy.
|
||
// ///
|
||
// /// **Purpose** - Measure of the citizenry's knowledge.
|
||
// /// **Effect** - Improves productivity, science output, and reduces unrest.
|
||
// /// **Source** - `education = Σ(education_building_output)`.
|
||
// #[table(title = "EDU", customize_fn = "color_cell")]
|
||
// pub education: GenericStat,
|
||
|
||
// /// Tourism revenue.
|
||
// ///
|
||
// /// **Purpose** - Income generated by visitors.
|
||
// /// **Effect** - Provides an additional income stream.
|
||
// /// **Source** - `tourism = number_of_tourists x price_per_tourist`.
|
||
// #[table(title = "TOR", customize_fn = "color_cell")]
|
||
// pub tourism: GenericStat,
|
||
|
||
// /// Cultural influence over the region.
|
||
// ///
|
||
// /// **Purpose** - Measure of soft power.
|
||
// /// **Effect** - Grants diplomatic bonuses and increases sway in the empire.
|
||
// /// **Source** - `influence = culture x population`.
|
||
// #[table(title = "INF", customize_fn = "color_cell")]
|
||
// pub influence: GenericStat,
|
||
|
||
// ──────────────────────── Military ────────────────────────
|
||
/// Overall military power.
|
||
///
|
||
/// **Purpose** - Composite measure of combat capability.
|
||
/// **Effect** - Determines defensive and offensive strength.
|
||
/// **Source** - Sum of `army`, `strength`, `fortification`, etc.
|
||
#[table(title = "MIL", customize_fn = "color_cell_categories")]
|
||
pub military: GenericStat,
|
||
|
||
/// Number of battle-ready units.
|
||
///
|
||
/// **Purpose** - Size of the active army.
|
||
/// **Effect** - Directly dictates defense and attack potential.
|
||
/// **Source** - Sum of all trained and equipped units.
|
||
#[table(title = "ARM", customize_fn = "color_cell")]
|
||
pub army: GenericStat,
|
||
|
||
/// Composite strength of the army.
|
||
///
|
||
/// **Purpose** - Tech, training, and equipment bonuses aggregated.
|
||
/// **Effect** - Determines combat effectiveness and required force to defeat an enemy.
|
||
/// **Source** - `strength = Σ(unit_strength) x tech_bonus x training_bonus`.
|
||
#[table(title = "STR", customize_fn = "color_cell")]
|
||
pub strength: GenericStat,
|
||
|
||
/// Defensive bonus from fortifications.
|
||
///
|
||
/// **Purpose** - Wall and tower defenses.
|
||
/// **Effect** - Adds a multiplier to overall defense.
|
||
/// **Source** - `fortification = Σ(fortification_building_bonus)`.
|
||
#[table(title = "FRT", customize_fn = "color_cell")]
|
||
pub fortification: GenericStat,
|
||
|
||
/// Threat level facing the entity.
|
||
///
|
||
/// **Purpose** - Likelihood of being attacked.
|
||
/// **Effect** - Triggers early warning alerts and strategic decisions.
|
||
/// **Source** - `threat = (enemy_proximity + enemy_strength) / defense`.
|
||
#[table(title = "THR", customize_fn = "color_cell")]
|
||
pub threat: GenericStat,
|
||
|
||
// ──────────────────────── Infrastructure ────────────────────────
|
||
/// Total infrastructure power.
|
||
///
|
||
/// **Purpose** - Overall built-environment capacity.
|
||
/// **Effect** - Supports population size and efficiency.
|
||
/// **Source** - Sum of all infrastructure components.
|
||
#[table(title = "IFR", customize_fn = "color_cell_categories")]
|
||
pub infrastructure: GenericStat,
|
||
|
||
/// Bureaucratic power.
|
||
///
|
||
/// **Purpose** - Efficiency of the city's administrative machinery.
|
||
/// **Effect** - Improves resource management and policy implementation.
|
||
/// **Source** - `bureaucracy = Σ(bureaucracy_building_output)`.
|
||
#[table(title = "BUR", customize_fn = "color_cell")]
|
||
pub bureaucracy: GenericStat,
|
||
|
||
/// Transportation level.
|
||
///
|
||
/// **Purpose** - Availability and quality of transport infrastructure.
|
||
/// **Effect** - Impacts logistics, mobility, and trade.
|
||
/// **Source** - `transportation = Σ(transport_building_output)`.
|
||
#[table(title = "TRP", customize_fn = "color_cell")]
|
||
pub transportation: GenericStat,
|
||
|
||
/// Sprawl / urban density.
|
||
///
|
||
/// **Purpose** - Measure of city sprawl and clutter.
|
||
/// **Effect** - Affects health, happiness, and infrastructure efficiency.
|
||
/// **Source** - `sprawl = Σ(sprawl_factor)`.
|
||
#[table(title = "SPR", customize_fn = "color_cell")]
|
||
pub sprawl: GenericStat,
|
||
|
||
/// Health infrastructure quality.
|
||
///
|
||
/// **Purpose** - Public health capacity.
|
||
/// **Effect** - Affects population health and can generate unrest.
|
||
/// **Source** - `health = output_of_health_function` (influenced by sanitation, disease spread, etc.).
|
||
#[table(title = "HLT", customize_fn = "color_cell")]
|
||
pub health: GenericStat,
|
||
}
|
||
|
||
/// Color the base cells
|
||
fn color_cell(cell: CellStruct, value: &GenericStat) -> CellStruct {
|
||
match (**value).cmp(&0) {
|
||
std::cmp::Ordering::Less => cell.foreground_color(Some(Color::Red)),
|
||
std::cmp::Ordering::Equal => cell,
|
||
std::cmp::Ordering::Greater => cell, //.foreground_color(Some(Color::Green)),
|
||
}
|
||
}
|
||
|
||
/// Color the cell categories
|
||
fn color_cell_categories(cell: CellStruct, value: &GenericStat) -> CellStruct {
|
||
match (**value).cmp(&0) {
|
||
std::cmp::Ordering::Less => cell.foreground_color(Some(Color::Red)).bold(true),
|
||
std::cmp::Ordering::Equal => cell.foreground_color(Some(Color::Blue)).bold(true),
|
||
std::cmp::Ordering::Greater => cell.foreground_color(Some(Color::Green)).bold(true),
|
||
}
|
||
}
|
||
|
||
impl OverallStats {
|
||
/// Clamp user-editable values to the supported simulation domain.
|
||
///
|
||
/// Population is an unbounded non-negative count. Growth and event/blocker
|
||
/// modifiers may be negative; other normalised values use `0..=120`.
|
||
pub fn clamp_for(&mut self, kind: EntityType) {
|
||
let modifier = matches!(kind, EntityType::Event | EntityType::Blocker);
|
||
self.population = GenericStat(if modifier {
|
||
(*self.population).max(-120)
|
||
} else {
|
||
(*self.population).max(0)
|
||
});
|
||
self.growth_rate = GenericStat((*self.growth_rate).clamp(-120, 120));
|
||
let minimum = if modifier { -120 } else { 0 };
|
||
for value in [
|
||
&mut self.crime,
|
||
&mut self.happiness,
|
||
&mut self.food,
|
||
&mut self.industry,
|
||
&mut self.science,
|
||
&mut self.trade,
|
||
&mut self.army,
|
||
&mut self.strength,
|
||
&mut self.fortification,
|
||
&mut self.threat,
|
||
&mut self.bureaucracy,
|
||
&mut self.transportation,
|
||
&mut self.sprawl,
|
||
&mut self.health,
|
||
] {
|
||
*value = GenericStat((**value).clamp(minimum, 120));
|
||
}
|
||
self.update();
|
||
}
|
||
|
||
/// Whether all editable values already satisfy the persisted domain.
|
||
pub fn is_bounded_for(&self, kind: EntityType) -> bool {
|
||
let mut copy = self.clone();
|
||
copy.clamp_for(kind);
|
||
let fields = [
|
||
ListStats::Demographics,
|
||
ListStats::Population,
|
||
ListStats::Growthrate,
|
||
ListStats::Crime,
|
||
ListStats::Happiness,
|
||
ListStats::Economy,
|
||
ListStats::Food,
|
||
ListStats::Industry,
|
||
ListStats::Science,
|
||
ListStats::Trade,
|
||
ListStats::Military,
|
||
ListStats::Army,
|
||
ListStats::Strength,
|
||
ListStats::Fortification,
|
||
ListStats::Threat,
|
||
ListStats::Infrastructure,
|
||
ListStats::Bureaucracy,
|
||
ListStats::Transportation,
|
||
ListStats::Sprawl,
|
||
ListStats::Health,
|
||
];
|
||
fields
|
||
.iter()
|
||
.all(|field| self.get_field(field) == copy.get_field(field))
|
||
}
|
||
|
||
/// Create Stats with a given rng distribution
|
||
pub(crate) fn create_rng(
|
||
rng: &RngLevel,
|
||
mut rng_t: &mut ThreadRng,
|
||
) -> Result<OverallStats, EpochError> {
|
||
let r = rng.to_rng()?;
|
||
let mut overall_stats = Self {
|
||
demographics: 0.into(),
|
||
population: (r.sample(&mut rng_t) as isize).into(),
|
||
growth_rate: (r.sample(&mut rng_t) as isize).into(),
|
||
crime: (r.sample(&mut rng_t) as isize).into(),
|
||
happiness: (r.sample(&mut rng_t) as isize).into(),
|
||
economy: 0.into(),
|
||
food: (r.sample(&mut rng_t) as isize).into(),
|
||
industry: (r.sample(&mut rng_t) as isize).into(),
|
||
science: (r.sample(&mut rng_t) as isize).into(),
|
||
trade: (r.sample(&mut rng_t) as isize).into(),
|
||
military: 0.into(),
|
||
army: (r.sample(&mut rng_t) as isize).into(),
|
||
strength: (r.sample(&mut rng_t) as isize).into(),
|
||
fortification: (r.sample(&mut rng_t) as isize).into(),
|
||
threat: (r.sample(&mut rng_t) as isize).into(),
|
||
infrastructure: 0.into(),
|
||
bureaucracy: (r.sample(&mut rng_t) as isize).into(),
|
||
transportation: (r.sample(&mut rng_t) as isize).into(),
|
||
sprawl: (r.sample(&mut rng_t) as isize).into(),
|
||
health: (r.sample(&mut rng_t) as isize).into(),
|
||
};
|
||
overall_stats.update();
|
||
Ok(overall_stats)
|
||
}
|
||
|
||
/// Updates the inner meta values
|
||
// TODO: Force the use of this ?
|
||
pub fn update(&mut self) {
|
||
self.demographics =
|
||
(*(self.population + self.growth_rate + self.happiness - self.crime) / 4).into();
|
||
self.economy = (*(self.food + self.industry + self.trade + self.science) / 4).into();
|
||
self.military =
|
||
(*(self.army + self.strength + self.fortification + self.threat) / 4).into();
|
||
self.infrastructure =
|
||
(*(self.bureaucracy + self.transportation + self.sprawl + self.health) / 4).into();
|
||
}
|
||
|
||
/// Updates with events
|
||
/// Updates with leader
|
||
/// etc.
|
||
// TODO: Fill this
|
||
#[allow(dead_code)]
|
||
fn apply_exteriors(&mut self) {}
|
||
|
||
#[cfg(test)]
|
||
pub(crate) fn linear(base: isize) -> OverallStats {
|
||
use crate::stats;
|
||
|
||
Self {
|
||
demographics: stats::GenericStat(1 + base),
|
||
population: stats::GenericStat(2 + base),
|
||
growth_rate: stats::GenericStat(3 + base),
|
||
crime: stats::GenericStat(4 + base),
|
||
happiness: stats::GenericStat(5 + base),
|
||
economy: stats::GenericStat(6 + base),
|
||
food: stats::GenericStat(7 + base),
|
||
industry: stats::GenericStat(8 + base),
|
||
science: stats::GenericStat(9 + base),
|
||
trade: stats::GenericStat(10 + base),
|
||
military: stats::GenericStat(11 + base),
|
||
army: stats::GenericStat(12 + base),
|
||
strength: stats::GenericStat(13 + base),
|
||
fortification: stats::GenericStat(14 + base),
|
||
threat: stats::GenericStat(15 + base),
|
||
infrastructure: stats::GenericStat(16 + base),
|
||
bureaucracy: stats::GenericStat(17 + base),
|
||
transportation: stats::GenericStat(18 + base),
|
||
sprawl: stats::GenericStat(19 + base),
|
||
health: stats::GenericStat(20 + base),
|
||
}
|
||
}
|
||
}
|
||
|
||
/// Strategic context and meta-data for an entity.
|
||
///
|
||
/// All fields are intentionally simple - the logic that interprets them
|
||
/// lives in separate modules (e.g. `map`, `network`, `governance`).
|
||
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
|
||
pub struct MetaStats {
|
||
// ──── Location & Spatial Data (hidden) ───────────────────────────────
|
||
/// Cartesian coordinates of the entity on the world map.
|
||
///
|
||
/// **Purpose** - Position of the entity in the simulation grid.
|
||
/// **Effect** - Used for distance calculations, visibility, and
|
||
/// map-based event logic.
|
||
/// **Source** - Supplied by the map generator.
|
||
pub position: Position,
|
||
|
||
/// Identifier for the capital
|
||
pub capital: Option<TownId>,
|
||
|
||
// /// List of nearby resource nodes (mines, forests, farms, etc.).
|
||
// ///
|
||
// /// **Purpose** - Resource map around the entity.
|
||
// /// **Effect** - Drives the entity's specialization and determines
|
||
// /// the default output mix.
|
||
// /// **Source** - `resources = filter(resource_list, distance ≤ detection_radius)`.
|
||
// pub resources: Vec<String>,
|
||
|
||
// /// The entity's chosen specialization tag
|
||
// /// (e.g., “Agricultural Hub”, “Industrial Center”).
|
||
// ///
|
||
// /// **Purpose** - Identity that dictates default production multipliers.
|
||
// /// **Effect** - Alters output curves and trade attractiveness.
|
||
// /// **Source** - `specialization = tag_assigned_by_player_or_ai`.
|
||
// pub specialization: String,
|
||
|
||
// ──── Strategic Positioning (hidden + public) ─────────────────────
|
||
/// Current governor or leader assigned to the entity.
|
||
///
|
||
/// **Purpose** - Leadership identity.
|
||
/// **Effect** - Adds personal bonuses and may modify policies
|
||
/// or diplomatic stance.
|
||
/// **Source** - `governor = selected_leader_uuid`.
|
||
pub governor: Option<CharacterId>,
|
||
|
||
// /// The entity's classification (capital, trade hub, frontier post, etc.).
|
||
// ///
|
||
// /// **Purpose** - Functional role within the empire.
|
||
// /// **Effect** - Alters base production, tax rates, and
|
||
// /// certain event probabilities.
|
||
// /// **Source** - `role = tag_assigned_by_player_or_ai`.
|
||
// pub role: String,
|
||
/// The faction or empire to which the entity currently belongs.
|
||
///
|
||
/// **Purpose** - Political affiliation.
|
||
/// **Effect** - Determines diplomatic relations, war status,
|
||
/// and access to empire-wide bonuses.
|
||
/// **Source** - `faction = current_faction_uuid`.
|
||
pub faction: Option<FactionId>,
|
||
|
||
/// UIDs of all entities the entity is linked to (roads, trade routes,
|
||
/// alliances, war declarations, etc.).
|
||
pub links: Vec<TypedLink>,
|
||
|
||
/// Prestige / reputation of the entity in the eyes of the empire
|
||
/// and foreign powers.
|
||
///
|
||
/// **Purpose** - Social standing metric.
|
||
/// **Effect** - Affects diplomatic influence, trade bonuses,
|
||
/// and event outcomes.
|
||
/// **Source** - `prestige = calculate_prestige(...)`.
|
||
pub prestige: GenericStat,
|
||
|
||
/// The reach of the entity, wether local or worldly
|
||
///
|
||
/// **Purpose** - Event validation
|
||
pub reach: Reach,
|
||
}
|
||
|
||
/// A generic stat pair with (ListStats, GenericStat), used mainly for clap
|
||
/// Accepts two forms
|
||
/// 1. "cri 10" (two separate tokens)
|
||
/// 2. "cri:10" (one token with a separator)
|
||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||
pub struct StatPair {
|
||
/// The stat selected
|
||
pub stat: ListStats,
|
||
/// The value of the modifier
|
||
pub value: GenericStat,
|
||
}
|
||
|
||
/// A two-dimensional point on the world map.
|
||
///
|
||
/// The struct is a thin wrapper around a pair of `isize` values
|
||
/// representing the X and Y coordinates.
|
||
#[derive(Debug, Default, Serialize, Deserialize, Clone, PartialEq, Eq, Add, Sub, Mul)]
|
||
pub struct Position(isize, isize);
|
||
|
||
/// A grid-aligned position used for chunk look-ups.
|
||
///
|
||
/// A `PositionGrid` stores the coordinates of a chunk in the world
|
||
/// grid. Each component is the index of the chunk in the X and Y
|
||
/// direction.
|
||
#[derive(Debug, Default, Serialize, Deserialize, Clone, Add, Sub, Mul)]
|
||
pub struct PositionGrid(isize, isize);
|
||
|
||
/// The size of the whole world in pixels.
|
||
///
|
||
/// These constants are internal to the module; they are not part
|
||
/// of the public API.
|
||
// TODO(9): Change to be at least initialized with the world ?
|
||
const GRID_SIZE: (i32, i32) = (1920, 1080);
|
||
/// The size of one world chunk in pixels.
|
||
const CHUNK_SIZE: isize = 200;
|
||
|
||
impl Position {
|
||
/// Calculates the Euclidean distance between two points.
|
||
///
|
||
/// The distance is computed in the 2-D Euclidean space.
|
||
pub fn distance(&self, other: &Self) -> isize {
|
||
((self.0 - other.0).pow(2) + (self.1 - other.1).pow(2)).isqrt()
|
||
}
|
||
|
||
/// Converts this point to its corresponding grid position.
|
||
///
|
||
/// The conversion divides the world coordinates by the
|
||
/// `CHUNK_SIZE` to obtain the chunk indices.
|
||
pub fn to_grid_distance(&self) -> PositionGrid {
|
||
PositionGrid(self.0 / CHUNK_SIZE, self.1 / CHUNK_SIZE)
|
||
}
|
||
|
||
/// Returns the inner tuple representation of the position.
|
||
///
|
||
/// This is a convenience method to obtain the raw `(isize, isize)`
|
||
/// coordinates without wrapping them in the struct.
|
||
pub fn to_inner(&self) -> (isize, isize) {
|
||
(self.0, self.1)
|
||
}
|
||
|
||
/// Generates a random position within the world bounds.
|
||
///
|
||
/// The position is chosen uniformly at random using the supplied
|
||
/// random number generator.
|
||
pub fn create_rng(r: &mut ThreadRng) -> Result<Self, EpochError> {
|
||
let x = r.random_range(0..GRID_SIZE.0);
|
||
let y = r.random_range(0..GRID_SIZE.1);
|
||
Ok(Self(x as isize, y as isize))
|
||
}
|
||
}
|
||
|
||
impl PositionGrid {
|
||
/// Calculates the Euclidean distance between two grid positions.
|
||
///
|
||
/// The distance is computed by converting both grid positions to
|
||
/// world coordinates and then using `Position::distance`.
|
||
pub fn distance(&self, other: &PositionGrid) -> isize {
|
||
self.to_position().distance(&other.to_position())
|
||
}
|
||
|
||
/// Converts the grid coordinates to world coordinates.
|
||
///
|
||
/// Each component is multiplied by `CHUNK_SIZE` to obtain the
|
||
/// corresponding world position.
|
||
pub fn to_position(&self) -> Position {
|
||
Position(CHUNK_SIZE * self.0, CHUNK_SIZE * self.1)
|
||
}
|
||
}
|
||
/// A summary of the stats, only for display purposes
|
||
#[allow(clippy::missing_docs_in_private_items)]
|
||
#[derive(Table)]
|
||
pub struct SummaryStats {
|
||
#[table(title = "Demo")]
|
||
demographics: GenericStat,
|
||
#[table(title = "Eco")]
|
||
economy: GenericStat,
|
||
// #[table(title = "Social")]
|
||
// social: GenericStat,
|
||
#[table(title = "Milit")]
|
||
military: GenericStat,
|
||
#[table(title = "Infra")]
|
||
infrastructure: GenericStat,
|
||
}
|
||
|
||
impl From<OverallStats> for SummaryStats {
|
||
fn from(value: OverallStats) -> Self {
|
||
Self {
|
||
demographics: value.demographics,
|
||
economy: value.economy,
|
||
military: value.military,
|
||
infrastructure: value.infrastructure,
|
||
}
|
||
}
|
||
}
|
||
|
||
/// Bridge between the CLI and the statistics logic.
|
||
///
|
||
/// Helps convert clap arguments to OverallStats
|
||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||
#[allow(missing_docs)]
|
||
pub enum ListStats {
|
||
Demographics,
|
||
Population,
|
||
Growthrate,
|
||
Crime,
|
||
Happiness,
|
||
Economy,
|
||
Food,
|
||
Industry,
|
||
Science,
|
||
Trade,
|
||
Social,
|
||
Culture,
|
||
Education,
|
||
Tourism,
|
||
Influence,
|
||
Military,
|
||
Army,
|
||
Strength,
|
||
Fortification,
|
||
Threat,
|
||
Infrastructure,
|
||
Bureaucracy,
|
||
Transportation,
|
||
Sprawl,
|
||
Health,
|
||
}
|
||
|
||
/// The list of all types of entities
|
||
#[allow(missing_docs)]
|
||
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
|
||
pub enum EntityType {
|
||
Character,
|
||
Player,
|
||
Town,
|
||
/// A calamity.
|
||
Calamity,
|
||
Organization,
|
||
Blocker,
|
||
#[default]
|
||
Event,
|
||
}
|
||
|
||
/// Trait to implement some symbol representations
|
||
pub trait Symbols {
|
||
/// Have a small Symbol to resume it
|
||
fn to_symbol(&self) -> String;
|
||
/// Have the shortest display possible
|
||
fn to_shortest(&self) -> String {
|
||
self.to_symbol()
|
||
}
|
||
}
|
||
|
||
// impl<T: Symbols> Display for T {
|
||
// fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||
// write!(f, "{}", self.to_symbol())
|
||
// }
|
||
// }
|
||
|
||
// A stat that is shown to the player *and* can be modified manually.
|
||
thin_newtype!(GenericStat, isize, derives: [Add, Sub]);
|
||
thin_newtype!(TownId, Uuid);
|
||
thin_newtype!(CharacterId, Uuid);
|
||
thin_newtype!(FactionId, usize, derives: [Add, Sub]);
|
||
|
||
#[derive(Copy, Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Display, Default)]
|
||
/// A typed link between two entities.
|
||
///
|
||
/// A link is a lightweight association that ties an entity's **identifier**
|
||
/// (`id`) to a *semantic role* (`role`). The role is expressed by the
|
||
/// [`Role`] enum and defines what the link actually means in the
|
||
/// domain model.
|
||
#[display("{}{}({}{})",role, role.to_symbol(),other_id.to_symbol(), other_type.to_symbol())]
|
||
pub struct TypedLink {
|
||
/// The UUID of the entity that is linked.
|
||
///
|
||
/// The link is *unidirectional*; the `TypedLink` itself does not
|
||
/// keep a back-reference to the source entity.
|
||
pub other_id: Uuid,
|
||
/// The semantic role that this link plays.
|
||
///
|
||
/// For example, a link with `Role::Capital` indicates that the entity
|
||
/// identified by `id` is the capital of the entity that owns the link.
|
||
pub role: Role,
|
||
/// The Type of the entity linked
|
||
///
|
||
/// Even if it can mostly be inferred, some edge cases can be squashed
|
||
/// early in exchange of some data storred
|
||
pub other_type: EntityType,
|
||
}
|
||
|
||
impl TypedLink {
|
||
/// Simple initializer for the TypedLink type
|
||
pub fn new(other_id: Uuid, role: Role, other_type: EntityType) -> Self {
|
||
Self {
|
||
other_id,
|
||
role,
|
||
other_type,
|
||
}
|
||
}
|
||
}
|
||
|
||
#[derive(Copy, Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Display, Default)]
|
||
/// Semantic role of a link.
|
||
///
|
||
/// The role encodes *what the link represents* in the model. The
|
||
/// variants are intentionally limited to the most common use-cases,
|
||
/// but the enum can be extended if the domain evolves.
|
||
pub enum Role {
|
||
/// The linked entity has governing authority over the link owner
|
||
Govern,
|
||
/// The linked entity is the capital of the link owner
|
||
Capital,
|
||
#[default]
|
||
/// No role has been assigned.
|
||
Undefined,
|
||
}
|
||
|
||
// --- TRAITS ---------------------------------------------------------------
|
||
/// A stat is a *game value* that can be converted to two different
|
||
/// normalised ranges - a 100-point range for “gaming” logic and a
|
||
/// 10-point range for “roll & UI” logic. The trait also exposes the
|
||
/// underlying raw value and its visibility.
|
||
///
|
||
// TODO(7): Change this with Deref+From
|
||
pub trait GameStat {
|
||
/// Convert the raw integer to a 50-point scale.
|
||
fn to_100(&self) -> isize {
|
||
(self.get_value().clamp(0, 120) - 10).min(100)
|
||
}
|
||
|
||
/// Convert the raw integer to a 10-point scale.
|
||
fn to_10(&self) -> isize {
|
||
self.to_100() / 10
|
||
}
|
||
|
||
/// As a colored delta (when the stat is used as a delta)
|
||
fn to_delta(&self) -> String {
|
||
let get_value = self.get_value();
|
||
if get_value < 0 {
|
||
format!("{}", get_value.to_string().red())
|
||
} else {
|
||
format!("{}", get_value.to_string().green())
|
||
}
|
||
}
|
||
|
||
/// Return the raw integer value, always bound to 0-70
|
||
fn get_value(&self) -> isize;
|
||
|
||
/// Return the raw integer value, always bound to 0-70
|
||
fn change_value(&mut self, value: isize);
|
||
|
||
/// Create a Gamestat from it's underlying value
|
||
fn from_value(value: isize) -> Self
|
||
where
|
||
Self: Sized;
|
||
}
|
||
|
||
/// Trait for objects that can expose a stat via a string key.
|
||
/// The trait returns a *boxed* trait object so callers do not need to know
|
||
/// the concrete type that was stored.
|
||
pub trait Accessible {
|
||
/// Return the requested stat as a `Box<dyn GameStat>`.
|
||
/// `None` if the key does not exist.
|
||
fn get_val(&self, key: &str) -> Option<Box<dyn GameStat>>;
|
||
}
|
||
|
||
/// Represents a position that can be identified in three different ways.
|
||
///
|
||
/// The string format is deliberately simple and is designed to be easy to write
|
||
/// by hand while still being unambiguous to a machine.
|
||
///
|
||
/// | Variant | Syntax in a string |
|
||
/// |---------|--------------------|
|
||
/// | `Exact` | `X,Y` |
|
||
/// | `Grid` | `~X,Y` or `gX,Y` |
|
||
/// | `Id` | `@{uuid}` |
|
||
#[derive(Debug, Clone)]
|
||
pub enum PositionIdentifier {
|
||
/// Exact position specified as `X,Y`.
|
||
Exact(Position),
|
||
|
||
/// Grid-aligned position specified as `~X,Y` or `gX,Y`.
|
||
Grid(PositionGrid),
|
||
|
||
/// Reference to an epoch by UUID, written as `@{uuid}`.
|
||
Id(EntityIdentifier),
|
||
}
|
||
|
||
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
|
||
/// The reach of the entity
|
||
pub enum Reach {
|
||
/// The entity can affect **any** target - no positional or faction
|
||
/// restrictions. Use this when the effect is truly global.
|
||
Global,
|
||
/// The entity has a *limited* area of effect. The `usize` usually
|
||
/// represents the radius around the entity's position that the effect covers.
|
||
Local(usize),
|
||
/// The entity can only affect members of a particular faction.
|
||
Faction(FactionId),
|
||
// /// The entity only affect a specific entity
|
||
// Entity(EntityIdentifier),
|
||
/// No reach - the entity should not be applied globally.
|
||
#[default]
|
||
None,
|
||
}
|
||
|
||
/// A description of how a value should be updated.
|
||
///
|
||
/// The enum is intentionally tiny – only the three actions that
|
||
/// matter in our state‑diff engine. Each variant is documented
|
||
/// with a short, practical example so you know exactly when
|
||
/// you’d pick it.
|
||
///
|
||
/// The enum is `Copy`, so you can freely pass it around without
|
||
/// ownership worries. The `From<&str>` implementation below
|
||
/// lets you read the operation name from configuration files or
|
||
/// CLI flags:
|
||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||
pub enum Modification {
|
||
/// The modification will be a *delta*, i.e. an increment.
|
||
///
|
||
/// For numeric values this is equivalent to adding the new
|
||
/// value to the existing one. For collections it usually
|
||
/// means “append”.
|
||
Delta,
|
||
|
||
/// The modification will *replace* the existing value.
|
||
///
|
||
/// This is a hard overwrite: the old value is dropped
|
||
/// entirely and the new one is written in its place.
|
||
Replace,
|
||
|
||
/// The modification will *reset* the underlying value.
|
||
///
|
||
/// For plain types this is typically a default/zero value.
|
||
/// For `Option<T>` it sets the field to `None`. It can
|
||
/// also be interpreted as “delete the field entirely”.
|
||
Delete,
|
||
}
|