epoch_forge/lib_efo/src/entity.rs

208 lines
7.2 KiB
Rust

//! # Entity System
//!
//! The `Entity` type represents any object that can participate in the game world.
//! It encapsulates runtime statistics, temporary bonuses, and metadata,
//! along with information about its lifetime and the nature of its effects.
//!
//! The design intentionally groups behaviour into two primary components,
//! `OverallStats` and `MetaStats`. The `entity_type` field is a placeholder
//! for future trait-based dispatch - the enum will eventually be replaced
//! by a type-safe system. For the moment it provides a quick lookup for
//! logic that distinguishes creatures, items, terrain, etc.
//!
use std::str::FromStr;
use derive_more::{Add, Display, Sub};
use serde::{Deserialize, Serialize};
use uuid::Uuid;
use crate::{
error::EpochError,
stats::{self, EntityType, MetaStats, OverallStats, Symbols, TypedLink},
};
pub mod edit;
pub mod implementations;
/// An entity that can be present in the game world.
///
/// Entities are mutable only through the entity system's public API.
/// Their fields are private to prevent accidental state corruption.
#[derive(Serialize, Deserialize, Debug, Clone, Default)]
pub struct Entity {
/// The name of the entity
pub name: String,
/// A short description of the entity
pub description: String,
/// The global identifier for the entity
pub id: Uuid,
/// Runtime statistics that determine the entity's behaviour.
///
/// These values are updated by the game loop and reflect the
/// entity's current state (e.g., health, speed, attack).
stats: OverallStats,
/// Temporary statistics that include bonuses from events,
/// leaders, or other temporary modifiers.
///
/// `temp_stats` is recalculated each turn and does not persist
/// beyond the entity's lifetime.
#[serde(skip)]
temp_stats: Option<OverallStats>,
/// Non-statistical metadata such as name, rarity, and faction.
///
/// This information is not directly part of the entity's combat
/// calculations but is useful for UI and logic.
metadata: MetaStats,
/// The categorical type of the entity.
///
/// Currently an enum that distinguishes creatures, items,
/// terrain, etc. It will be phased out in favor of a trait-based
/// system for greater type safety.
pub entity_type: EntityType,
/// The lifetime of the entity within the game world.
///
/// The game loop checks this value during each tick to decide
/// whether to keep or remove the entity.
duration: EntityDuration,
/// Describes the effect applied by the entity.
///
/// This determines when the effect is applied and whether it
/// persists after the entity is removed.
effect_nature: EffectApplication,
/// Limits that clamp any stat changes caused by the entity's effect.
effect_bounds: EffectBounds,
}
impl Entity {
/// Iterate over all the links and do the appropriate action
pub fn remove_all_links(
&self,
epoch_info: &mut crate::epoch::EpochInfo,
) -> Result<(), EpochError> {
for TypedLink {
other_id,
role,
other_type,
} in &self.metadata.links
{
let entity: &mut Entity =
epoch_info.find_entity_strict_as_mut(*other_id, Some(*other_type))?;
let id = match role {
stats::Role::Govern => entity.remove_governor().map(|i| *i),
stats::Role::Capital => entity.remove_capital().map(|i| *i),
stats::Role::Undefined => None,
};
// TODO: Add the other way cleaning, not useful for now but if ever links can be two way,
// it needs to be done
log::info!(
"Removed entity {}{} [{}] from {}{}{} -> {id:?}",
other_id.to_symbol(),
other_type.to_symbol(),
role.to_symbol(),
entity.name,
entity.id.to_symbol(),
entity.entity_type.to_symbol()
);
}
Ok(())
}
}
/// Limits for the maximum and minimum value that an effect may
/// modify a statistic. The bounds are applied after the effect has
/// been calculated to keep stats within a sane range.
///
/// `min` and `max` are inclusive.
#[derive(Debug, Serialize, Deserialize, Clone, Default, Add, Sub)]
#[allow(missing_docs)]
pub struct EffectBounds {
pub min: usize,
pub max: usize,
}
/// How the entity's effect is applied over time.
#[derive(Debug, Serialize, Deserialize, Clone, Default)]
pub enum EffectApplication {
/// Repeatedly applied every turn while the entity is present.
Recurring,
/// Modifies the attached entity's stats only while present.
WhenPresent,
/// Permanently modifies stats
#[default]
PermanentEffectToApply,
/// Indicates that a permanent effect has already been applied.
PermanentEffectApplied,
}
impl FromStr for EffectApplication {
type Err = EpochError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.to_ascii_lowercase().as_str() {
_ if s.starts_with("re") => Ok(EffectApplication::Recurring),
_ if s.starts_with("wh") => Ok(EffectApplication::WhenPresent),
_ if s.contains("present") => Ok(EffectApplication::WhenPresent),
_ if s.contains("toap") => Ok(EffectApplication::WhenPresent),
_ if s.starts_with("appl") => Ok(EffectApplication::WhenPresent),
"done" | "ok" => Ok(EffectApplication::PermanentEffectApplied),
"todo" => Ok(EffectApplication::PermanentEffectToApply),
_ => Err(EpochError::ParsingArgument {
argument_parsed: s.to_string(),
while_parsing: "EffectApplication",
}),
}
}
}
/// Represents how long an entity remains active in the world.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Default)]
pub enum EntityDuration {
/// The entity persists until it is explicitly destroyed.
Permanent,
/// The entity remains for a fixed number of turns.
/// The counter is decremented each tick and the entity becomes
/// `Done` once it reaches zero.
Duration(usize),
/// The entity's lifecycle has finished and it should no longer
/// be updated. This variant is typically used for one-off
/// events or buffs that expire after their final turn.
#[default]
Done,
}
/// An identifier that can be supplied on the command line.
///
/// The enum is deliberately small so it can be used as a Clap argument type.
/// It accepts **either**
/// * a plain name (e.g. `"bob"`), or
/// * a UUID that is prefixed with an `@` (e.g. `"@3f4c6b7e-d4d1-4b3f-a7a4-0d5c6b8e1f9b"`).
///
/// The two variants are kept separate so that downstream code can decide
/// whether it should treat the value as a human-readable name or a
/// machine-identifiable UUID.
#[derive(Debug, Clone, PartialEq, Eq, Display)]
pub enum EntityIdentifier {
/// A human-readable name.
Name(String),
/// A UUID that was supplied with a leading `@`. The `@` is stripped
/// when the enum is constructed - only the raw UUID string is stored.
Id(String),
}
#[allow(clippy::unwrap_used)]
#[cfg(test)]
mod test;