epoch_forge/lib_efo/src/entity/implementations.rs

668 lines
23 KiB
Rust

//! Implementation of all needed traits for the Entity struct
use std::ops::Add;
mod from_impl;
use std::cmp::{max, min};
use cli_table::format::{Border, HorizontalLine, Separator, VerticalLine};
use cli_table::{Style, WithTitle};
use colored::*;
use log::debug;
use rand::distr::Distribution;
use rand::seq::{IndexedRandom, IteratorRandom};
use uuid::Uuid; // [3] - colored-rs examples
use crate::entity::{EffectApplication, EffectBounds, Entity, EntityDuration, EntityIdentifier};
use crate::epoch::EpochInfo;
use crate::epoch::epoch_traits::Diffable;
use crate::error::EpochError;
use crate::stats::{
self, EntityType, FactionId, GenericStat, ListStats, MetaStats, OverallStats, Position,
PositionGrid, StatPair, Symbols,
};
use crate::utils::RngLevel;
use crate::{Displayable, items_table};
// ---------- Implementation ----------
impl Displayable for Entity {
// Detailed multi-line view (used e.g. in logs)
fn print_full(&self, epoch_info: &EpochInfo) {
println!("{}", self.to_pretty_tree(epoch_info),);
if let Ok(c) = self.stats_to_table() {
println!("{c}");
}
}
/// One-liner used for auto-generation of `Vec<T>` displays
// TODO: URGENT: Change this display
fn oneline_display(&self) -> String {
let capital = self
.metadata
.capital
.as_ref()
.map(|c| format!("{} ", c.to_symbol()).green())
.unwrap_or_default();
let governor = self
.metadata
.governor
.as_ref()
.map(|g| format!("Governor:  {}", g.to_symbol()).blue())
.unwrap_or_default();
let prestige = if *self.metadata.prestige > 0 {
format!(" {:2}{}", self.metadata.prestige, "".yellow())
} else {
String::new()
};
// ---- build the two lines ----
let line1 = format!(
"├──┬─ {} {:23} {} ──────> {} {}",
self.id.to_string().split_at(7).0.blue(),
self.name.green(),
self.entity_type.to_symbol(),
self.metadata.position.to_symbol(),
self.duration.to_symbol().yellow(),
);
let (junction, line3) = if !capital.is_empty() | !governor.is_empty() {
("├", format!("│ └─ {}{}\n", capital, governor,))
} else {
("└", "".to_string())
};
let line2 = format!(
"│ {}─ Faction: {} │ Effect: {} {}, Stats: {}{}",
junction,
self.metadata.faction.to_symbol(),
self.effect_nature.to_symbol(),
self.effect_bounds.to_symbol(),
self.stats.to_symbol(),
prestige,
);
format!("{}\n{}\n{}│", line1, line2, line3)
}
}
impl Entity {
// Display the entity's statistics in a pretty table.
///
/// The table contains both the permanent and temporary statistics of the
/// entity. The table is formatted with a custom border and separator
/// using the `cli_table` crate.
///
/// # Returns
/// A `Result` containing the table display on success, or an `EpochError` if the
/// conversion to a table string fails.
pub fn full_stats_to_table(&self) -> Result<cli_table::TableDisplay, EpochError> {
let items = if let Some(t) = &self.temp_stats {
vec![&self.stats, t]
} else {
vec![&self.stats]
};
self.stat_to_table(items)
}
/// Display the entity's statistics in a pretty table (same format as
/// `full_stats_to_table`).
///
/// This method is provided for backward compatibility and forwards all
/// work to `full_stats_to_table`.
///
/// # Returns
/// A `Result` containing the table display on success, or an `EpochError` if the
/// conversion to a table string fails.
pub fn stats_to_table(&self) -> Result<cli_table::TableDisplay, EpochError> {
let items = if let Some(t) = &self.temp_stats {
vec![t]
} else {
vec![&self.stats]
};
self.stat_to_table(items)
}
/// Display the entity's statistics in a pretty table (same format as
/// `full_stats_to_table`).
///
/// This method is provided for backward compatibility and forwards all
/// work to `full_stats_to_table`.
///
/// # Returns
/// A `Result` containing the table display on success, or an `EpochError` if the
/// conversion to a table string fails.
///
fn stat_to_table(
&self,
items: Vec<&OverallStats>,
) -> Result<cli_table::TableDisplay, EpochError> {
items_table!(items, self.name.clone(), self.id)
}
/// Pretty-print the entity as a coloured tree.
///
/// The output is a `String` that visualises the entity's metadata, type,
/// duration, effect bounds, and any links. Colours are applied using
/// `colored::Colorize`.
///
/// # Returns
/// A `String` containing the formatted tree.
// TODO: Deref ids
pub fn to_pretty_tree(&self, epoch_info: &EpochInfo) -> String {
// Helper that prefixes a line with the correct amount of vertical bars.
fn indent(level: usize, line: &str) -> String {
let bars = "│ ".repeat(level);
format!(" {}{}", bars, line)
}
let mut out = String::new();
out.push_str(&format!(
"[{} {} 󰻾[{}]]\n",
self.entity_type.to_symbol().blue().bold(),
self.name.cyan().bold(),
self.id.to_string().blue().bold()
));
// ── Metadata section
out.push_str(&indent(0, &format!("├─ {}\n", "metadata".green())));
if let Some(capital) = self.metadata.capital {
out.push_str(&indent(
1,
&format!(
"├─ {}: {}\n",
"capital".bright_green(),
uuid_to_symbol(*capital, epoch_info, &EntityType::Town)
),
));
}
if let Some(faction) = self.metadata.faction {
out.push_str(&indent(
1,
&format!(
"├─ {} : {}{}\n",
"faction".bright_green(),
"".yellow(),
faction.to_string().yellow(),
),
));
}
if let Some(governor) = self.metadata.governor {
out.push_str(&indent(
1,
&format!(
"├─ {}: {}\n",
"governor".bright_green(),
uuid_to_symbol(*governor, epoch_info, &EntityType::Character)
),
));
}
if *self.metadata.prestige > 0 {
out.push_str(&indent(
1,
&format!(
"├─ {}: {}{}\n",
"prestige".bright_green(),
self.metadata.prestige.to_string().yellow(),
"".yellow()
),
));
}
out.push_str(&indent(
1,
&format!(
"└─ {}: {}\n",
"position".bright_green(),
self.metadata.position.to_symbol()
),
));
// ── Optional links
if !self.metadata.links.is_empty() {
out.push_str(&indent(0, &format!("├─ {}\n", "links".green())));
for (i, link) in self.metadata.links.iter().enumerate() {
let last = i == self.metadata.links.len() - 1;
let symbol = if last { "└─" } else { "├─" };
out.push_str(&indent(
1,
&format!(
"{} {}\n",
symbol,
uuid_to_symbol(**link, epoch_info, &EntityType::Town).yellow()
),
));
}
}
// ── Other top-level fields
out.push_str(&indent(
0,
&format!(
"├─ {}: {}\n",
"duration".green(),
self.duration.to_symbol().yellow()
),
));
out.push_str(&indent(
0,
&format!("├─ {}: {:?}\n", "effect_nature".green(), self.effect_nature),
));
out.push_str(&indent(
0,
&format!(
"└─ {}: {}",
"effect_bounds".green(),
self.effect_bounds.to_symbol()
),
));
out
}
/// Create an entity using a specific RNG level.
///
/// The entity is initialised with random statistics, a random position,
/// and a random prestige value derived from the supplied `RngLevel`.
///
/// # Arguments
/// * `e_type` - The type of entity to create.
/// * `rng` - The RNG level to use when generating random values.
///
/// # Returns
/// * `Ok(Self)` - The newly created entity.
/// * `Err(EpochError)` - Propagated from any randomisation failure.
///
pub fn create_rng(e_type: &EntityType, rng: &RngLevel) -> Result<Self, EpochError> {
let mut r = rand::rng();
Ok(Self {
id: Uuid::new_v4(),
stats: OverallStats::create_rng(rng, &mut r)?,
temp_stats: None,
metadata: MetaStats {
prestige: GenericStat(rng.to_rng()?.sample(&mut r) as isize),
position: Position::create_rng(&mut r)?,
..Default::default()
},
entity_type: e_type.clone(),
..Default::default()
})
}
/// Change one of the entity's statistics.
///
/// The stat identified by `pair` is replaced with the new value specified in
/// the `StatPair`. This is a direct overwrite and does not apply any delta.
///
/// # Arguments
/// * `pair` - The stat pair containing the key and new value.
///
pub fn change_stat_strict(&mut self, pair: StatPair) {
overwrite_stat(&mut self.stats, pair);
}
/// Mutate a statistic in a “fuzzy” way.
///
/// This method behaves like `change_stat_strict` for ordinary stats, but
/// for *meta-stats* it applies a random modification instead of an
/// outright overwrite.
///
/// # Parameters
/// * `pair` - a `StatPair` that contains the target statistic and the
/// value that should be used for the fuzzy change.
pub fn change_stat_fuzzy(&mut self, pair: StatPair, delta: bool) {
let stats_demo = [
ListStats::Population,
ListStats::Growthrate,
ListStats::Crime,
ListStats::Happiness,
];
let stats_eco = [
ListStats::Food,
ListStats::Industry,
ListStats::Science,
ListStats::Trade,
];
let stats_soc = [
ListStats::Culture,
ListStats::Education,
ListStats::Tourism,
ListStats::Influence,
];
let stats_mil = [
ListStats::Army,
ListStats::Strength,
ListStats::Fortification,
ListStats::Threat,
];
let stats_inf = [
ListStats::Bureaucracy,
ListStats::Transportation,
ListStats::Sprawl,
ListStats::Health,
];
match pair.stat {
ListStats::Demographics => self.change_random_stats_by(&stats_demo, pair.value, delta),
ListStats::Economy => self.change_random_stats_by(&stats_eco, pair.value, delta),
ListStats::Social => self.change_random_stats_by(&stats_soc, pair.value, delta),
ListStats::Military => self.change_random_stats_by(&stats_mil, pair.value, delta),
ListStats::Infrastructure => self.change_random_stats_by(&stats_inf, pair.value, delta),
_ => self.change_stat_strict(pair),
}
}
/// Mutates a statistic in a “fuzzy” manner.
///
/// For ordinary statistics this behaves like `change_stat_strict` and
/// simply assigns the supplied value. For *meta-stats* the function
/// chooses a random subset of the associated sub-statistics and
/// distributes the requested change evenly among them. The selection
/// is performed using a thread-local RNG.
fn change_random_stats_by(
&mut self,
stats_demo: &[ListStats],
amount: GenericStat,
delta: bool,
) {
let mut r = rand::rng();
let nb = (1..stats_demo.len() + 1).choose(&mut r).unwrap_or(1);
let stats = stats_demo.choose_multiple(&mut r, nb);
let (a, b) = (*amount / 2, *amount);
let (a, b) = (min(a, b), max(a, b));
let mut value = || GenericStat((a..b).choose(&mut r).unwrap_or(1));
stats.for_each(|stat| {
if delta {
self.delta_stat(StatPair {
stat: *stat,
value: value(),
});
} else {
self.change_stat_strict(StatPair {
stat: *stat,
value: value(),
})
}
});
}
/// Change the entity's duration.
///
/// This simply replaces the current `EntityDuration` with the one supplied.
/// No validation or transformation is performed; it is a direct overwrite.
///
/// # Arguments
/// * `duration` - The new `EntityDuration` to assign to the entity.
///
pub fn change_duration(&mut self, duration: EntityDuration) {
self.duration = duration
}
/// Change the entity's description.
///
/// Replaces the current description string with the new one supplied.
/// This method performs a direct overwrite; the previous description is dropped.
///
/// # Arguments
/// * `descritption` - The new description string for the entity.
///
pub fn change_description(&mut self, descritption: String) {
self.description = descritption
}
/// Apply a delta to all of the entity's statistics.
///
/// The delta specified by `pair` is added to each of the statistics in
/// `self.stats`. Positive values increase the stat, negative values
/// decrease it.
///
/// # Arguments
/// * `pair` - The stat pair representing the change to apply.
pub fn delta_stat(&mut self, pair: StatPair) {
add_to_stat(&mut self.stats, pair);
}
/// Replace the entity's duration.
///
/// The method simply overwrites the current `duration` field with the
/// supplied value. It is primarily intended for use when an entity
/// is instantiated from external data that already contains a duration value.
pub fn modify_duration(&mut self, duration: EntityDuration) {
self.duration = duration
}
/// Set the way the entity's effects are applied.
///
/// The field `effect_nature` determines how the entity's abilities or
/// status effects interact with the world.
/// This method overwrites the existing value with the supplied `EffectApplication`.
pub fn modify_effect_application(&mut self, effect: EffectApplication) {
self.effect_nature = effect
}
/// Update the bounds that govern the entity's effects.
///
/// `effect_bounds` controls the maximum/minimum strength, duration or
/// other limits that can be applied to the entity's effects. This
/// method simply replaces the current bounds with the supplied
/// `EffectBounds`.
pub fn modify_effect_bounds(&mut self, effect: EffectBounds) {
self.effect_bounds = effect
}
/// Sets the entity's position using a world-space `Position`.
///
/// This method updates the internal metadata to the specified
/// world coordinates.
pub fn modify_position(&mut self, pos: Position) {
self.metadata.position = pos;
}
/// Sets the entity's faction identifier.
///
/// This method updates the internal metadata to reflect the provided
/// `faction`. A `None` value indicates that the entity is not
/// affiliated with any faction.
pub fn modify_faction(&mut self, faction: Option<FactionId>) {
self.metadata.faction = faction;
}
/// Sets the entity's reach description.
///
/// The `reach` string typically contains information such as the
/// distance or area the entity can affect. This method replaces
/// the current reach value stored in the entity's metadata.
pub fn modify_reach(&mut self, reach: stats::Reach) {
self.metadata.reach = reach;
}
/// Sets the entity's position using a grid-space `PositionGrid`.
///
/// The supplied grid coordinates are converted to world space
/// before being stored.
pub fn modify_position_grid(&mut self, pos: PositionGrid) {
self.metadata.position = pos.to_position();
}
/// Changes the entity's description text.
pub fn modify_description(&mut self, descritption: String) {
self.description = descritption;
}
/// Sets the entity's prestige stat to an absolute value.
///
/// The prestige value is stored directly in the entity's metadata
/// and overwrites any previous value.
pub fn modify_prestige(&mut self, prestige: GenericStat) {
self.metadata.prestige = prestige;
}
/// Adjusts the entity's prestige stat by adding a delta.
pub fn modify_prestige_by_delta(&mut self, prestige: GenericStat) {
self.metadata.prestige = self.metadata.prestige.add(prestige);
}
/// Add a governor to the entity if the id exists
pub fn change_governor(&mut self, governor: stats::CharacterId) {
debug!("Swapping the governor with {}", governor.to_symbol());
self.metadata.governor = Some(governor);
}
/// Remove the entity's governor and return it
pub fn remove_governor(&mut self) -> Option<stats::CharacterId> {
self.metadata.governor.take()
}
/// Add a governor to the entity if the id exists
pub fn change_capital(&mut self, capital: stats::TownId) {
debug!("Swapping the capital with {}", capital.to_symbol());
self.metadata.capital = Some(capital);
}
/// Remove the entity's governor and return it
pub fn remove_capital(&mut self) -> Option<stats::TownId> {
self.metadata.capital.take()
}
/// Returns a **read-only reference** to the entity's current position.
pub fn position(&self) -> &Position {
&self.metadata.position
}
/// Returns whether the entity match an optionnal identifier
pub fn match_identifier(&self, entity_identifier: &Option<EntityIdentifier>) -> bool {
match entity_identifier {
Some(EntityIdentifier::Name(name)) => self.name.starts_with(name),
Some(EntityIdentifier::Id(id)) => self.id.hyphenated().to_string().starts_with(id),
None => false,
}
}
}
/// Short utility to make a symbol for an entity from it's Uuid
fn uuid_to_symbol(id: Uuid, epoch_info: &EpochInfo, e_type: &EntityType) -> String {
epoch_info
.find_entity_strict(id, Some(e_type.clone()))
.map(|e| e.to_symbol())
.unwrap_or(format!(
"{}{} is missing {}",
"".red(),
id.to_symbol().red(),
e_type.clone().to_shortest().blue()
))
}
// impl Entity {
// /// Create a new Event
// fn new_event(name: String, description: String){}
// }
/// Replace a statistic in `stats` with the value from `pair`.
///
/// This function performs a direct overwrite: the existing value is
/// discarded and the new value from `pair` is written in its place.
fn overwrite_stat(stats: &mut OverallStats, pair: StatPair) {
let affected_stat = stats.get_field_mut(&pair.stat);
*affected_stat = pair.value;
}
/// Add a delta to a statistic in `stats`.
///
/// The delta in `pair.value` is added to the current statistic value
/// using `saturating_add`, so that the result never overflows the
/// underlying integer type.
fn add_to_stat(stats: &mut OverallStats, pair: StatPair) {
let affected_stat = stats.get_field_mut(&pair.stat);
let current_value = *affected_stat;
*affected_stat = GenericStat(current_value.saturating_add(*pair.value));
}
/// Compare a field on `self` with the same field on `other`.
/// If they are equal → `None`, otherwise → the value from `other`.
macro_rules! diff_fields {
// Two arguments: the two objects you want to compare
($self:ident, $other:ident, $( $field:ident ),* $(,)?) => {
$(
let $field = if $self.$field == $other.$field {
None
} else {
$other.$field.clone()
};
)*
};
}
impl Diffable for Entity {
fn delta(&self, other: &Self) -> Self {
let name = if self.name == other.name {
self.name.clone()
} else {
format!("{}->{}", self.name, other.name)
};
Self {
name,
stats: self.stats.clone() - other.stats.clone(),
temp_stats: self.temp_stats.delta(&other.temp_stats),
metadata: self.metadata.delta(&other.metadata),
entity_type: other.entity_type.clone(),
duration: other.duration.clone(),
effect_nature: other.effect_nature.clone(),
effect_bounds: other.effect_bounds.clone(),
id: Uuid::new_v4(),
description: other.description.clone(),
}
}
}
impl Diffable for Option<OverallStats> {
fn delta(&self, other: &Self) -> Self {
match (self, other) {
(None, None) => None,
(None, Some(a)) => Some(a.clone()),
(Some(a), None) => Some(a.clone()),
(Some(a), Some(b)) => Some(a.clone() - b.clone()),
}
}
}
impl Diffable for MetaStats {
fn delta(&self, other: &Self) -> Self {
diff_fields!(self, other, capital, governor);
Self {
position: self.position.clone() - other.position.clone(),
capital,
governor,
faction: {
match (self.faction.as_ref(), other.faction.as_ref()) {
(None, None) => None,
(None, Some(b)) => Some(*b),
(Some(a), None) => Some(*a),
(Some(_), Some(b)) => Some(*b),
}
},
links: self
.links
.clone()
.into_iter()
.filter(|t1| other.links.iter().any(|t2| t1 == t2))
.collect(),
prestige: self.prestige - other.prestige,
reach: stats::Reach::None,
}
}
}
impl Symbols for Entity {
fn to_symbol(&self) -> String {
format!(
"{} {} {}",
self.entity_type.to_symbol().blue(),
self.id.to_symbol().blue(),
self.name
)
}
}
impl Symbols for Uuid {
fn to_symbol(&self) -> String {
format!("󰻾[{}]", self.to_string().split_at(7).0)
}
fn to_shortest(&self) -> String {
self.to_string().split_at(7).0.to_string()
}
}