From b0d84f235a5aa015edbb8fa15c9f3d517fef7df3 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Fri, 28 Nov 2025 00:43:33 +0100 Subject: [PATCH 01/22] Adds more error handling --- bin_efo/src/commands/epoch.rs | 8 ++++++++ bin_efo/src/commands/epoch/cli_epoch.rs | 7 +++++++ lib_efo/src/epoch_struct.rs | 21 +++++++-------------- lib_efo/src/error.rs | 8 ++++++-- 4 files changed, 28 insertions(+), 16 deletions(-) diff --git a/bin_efo/src/commands/epoch.rs b/bin_efo/src/commands/epoch.rs index 587f283..677c6c8 100644 --- a/bin_efo/src/commands/epoch.rs +++ b/bin_efo/src/commands/epoch.rs @@ -24,6 +24,7 @@ pub fn handle_cmd(cmd: cli_epoch::EpochCmd) -> Result<(), AppError> { cli_epoch::EpochCmd::Reset(args) => handle_reset(args, &mut main_epoch), cli_epoch::EpochCmd::Diff(args) => handle_diff(args), cli_epoch::EpochCmd::Tag(args) => handle_taging(args, &mut main_epoch), + cli_epoch::EpochCmd::Fsck(args) => handle_fsck(args, &mut main_epoch), } } @@ -111,3 +112,10 @@ fn handle_taging(args: cli_epoch::Tag, main_epoch: &mut EpochConfig) -> Result<( ))) } } + +/// Basic sanity check +fn handle_fsck(args: cli_epoch::Fsck, main_epoch: &mut EpochConfig) -> Result<(), AppError> { + let _ = main_epoch; + let _ = args; + unimplemented!() +} diff --git a/bin_efo/src/commands/epoch/cli_epoch.rs b/bin_efo/src/commands/epoch/cli_epoch.rs index 25b53a4..c27e836 100644 --- a/bin_efo/src/commands/epoch/cli_epoch.rs +++ b/bin_efo/src/commands/epoch/cli_epoch.rs @@ -21,6 +21,9 @@ pub enum EpochCmd { // Tag and next could be implemented as subcommands of epoch // even if they barely belong here Tag(Tag), + + /// Basic filesystem level maintenance + Fsck(Fsck), } /// `efo epoch log` @@ -69,3 +72,7 @@ pub struct Tag { /// The tag to tag the current epoch with pub tag: String, } + +/// `efo epoch fsck` +#[derive(Debug, Args)] +pub struct Fsck {} diff --git a/lib_efo/src/epoch_struct.rs b/lib_efo/src/epoch_struct.rs index 131dd3a..b53e425 100644 --- a/lib_efo/src/epoch_struct.rs +++ b/lib_efo/src/epoch_struct.rs @@ -81,7 +81,8 @@ impl EpochConfig { // TODO: write a trait for this let config: EpochConfig = serde_json::from_str(&io_err_with_help!( read_to_string(path), - format!("Reading config from path {:?}", path) + "Reading config from path {:?}", + path )?) .map_err(|e| EpochError::Serde { source: e, @@ -99,19 +100,11 @@ impl EpochConfig { /// Initialize the epoch more in depth fn initialize(mut self) -> Result { let path = EpochConfig::default().save_subfolder(); - let path = io_err_with_help!( - Path::new(&path).read_dir(), - format!("Reading initial folder {path}") - )?; + let path = io_err_with_help!(Path::new(&path).read_dir(), "Reading initial folder {path}")?; // let mut valid_folders = HashMap::new(); for elt in path { let elt = io_err_with_help!(elt, "Opening file in main config folder")?; - if io_err_with_help!( - elt.file_type(), - format!("Determining file type of {:?}", elt) - )? - .is_dir() - { + if io_err_with_help!(elt.file_type(), "Determining file type of {:?}", elt)?.is_dir() { let id = elt.file_name().to_string_lossy().parse::(); println!("{:?}", id); self.list_existing_epochs.insert(id.unwrap(), None); @@ -127,8 +120,7 @@ impl EpochConfig { // Create a mock epoch let path = EpochInfo::with_id(epoch_id).save_path(); - let read_to_string = - io_err_with_help!(read_to_string(&path), format!("Reading {:?}", path)); + let read_to_string = io_err_with_help!(read_to_string(&path), "Reading {:?}", path); // Try to load let maybe_epoch: EpochInfo = @@ -177,7 +169,8 @@ impl EpochConfig { } io_err_with_help!( remove_dir_all(EpochInfo::with_id(&id).save_folder()), - format!("Removing the epoch {}", id) + "Removing the epoch {}", + id )?; Ok(()) } diff --git a/lib_efo/src/error.rs b/lib_efo/src/error.rs index 99914d7..be6fc47 100644 --- a/lib_efo/src/error.rs +++ b/lib_efo/src/error.rs @@ -163,6 +163,10 @@ pub enum EpochError { /// Any other error that didn't fit into the above categories #[error("An unknown error occurred: {0}")] Unknown(String), + + /// User error, meant to be very explicit over what happened and what to do + #[error("An user facing error")] + UserError(#[help] String), } // macro_rules! err_with { @@ -175,10 +179,10 @@ pub enum EpochError { macro_rules! io_err_with_help { // $expr: the expression that produces the Result // $help: string literal with the help message - ($expr:expr, $help:expr) => {{ + ($expr:expr, $($help:expr),*) => {{ $expr.map_err(|e| EpochError::Io { source: e, - help: Some($help.to_owned()), + help: Some(format!($($help),*)), }) }}; } -- 2.45.1 From a13560a53f85e701b5f9944141fb962208641adc Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Fri, 28 Nov 2025 16:40:31 +0100 Subject: [PATCH 02/22] Most doc added --- Cargo.lock | 28 +++++ bin_efo/src/commands.rs | 3 +- bin_efo/src/commands/epoch.rs | 111 ++++++++++++++--- bin_efo/src/commands/epoch/cli_epoch.rs | 57 +++++++-- bin_efo/src/commands/error.rs | 7 -- bin_efo/src/commands/init.rs | 40 ++++-- bin_efo/src/error.rs | 2 + bin_efo/src/main.rs | 32 ++++- lib_efo/Cargo.toml | 1 + lib_efo/src/epoch_struct.rs | 63 +++++++++- lib_efo/src/error.rs | 156 ++++++++++++++++-------- lib_efo/src/lib.rs | 2 + lib_efo/src/utils.rs | 2 + 13 files changed, 404 insertions(+), 100 deletions(-) delete mode 100644 bin_efo/src/commands/error.rs diff --git a/Cargo.lock b/Cargo.lock index 56e1f13..b2e6278 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -161,6 +161,27 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b05b61dc5112cbb17e4b6cd61790d9845d13888356391624cbe7e41efeac1e75" +[[package]] +name = "derive_more" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "093242cf7570c207c83073cf82f79706fe7b8317e98620a47d5be7c3d8497678" +dependencies = [ + "derive_more-impl", +] + +[[package]] +name = "derive_more-impl" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bda628edc44c4bb645fbe0f758797143e4e07926f7ebf4e9bdfbd3d2ce621df3" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "unicode-xid", +] + [[package]] name = "errno" version = "0.3.14" @@ -206,6 +227,7 @@ name = "lib_efo" version = "0.1.0" dependencies = [ "clap", + "derive_more", "miette", "serde", "serde_json", @@ -478,6 +500,12 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254" +[[package]] +name = "unicode-xid" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" + [[package]] name = "utf8parse" version = "0.2.2" diff --git a/bin_efo/src/commands.rs b/bin_efo/src/commands.rs index 507983a..a9861be 100644 --- a/bin_efo/src/commands.rs +++ b/bin_efo/src/commands.rs @@ -6,6 +6,7 @@ //! `efo::main.rs` can simply `use commands::*;` and dispatch based on the //! clap‑parsed enum. +#![warn(missing_docs, clippy::missing_docs_in_private_items)] + pub mod epoch; -pub mod error; pub mod init; diff --git a/bin_efo/src/commands/epoch.rs b/bin_efo/src/commands/epoch.rs index 677c6c8..96e191f 100644 --- a/bin_efo/src/commands/epoch.rs +++ b/bin_efo/src/commands/epoch.rs @@ -2,15 +2,16 @@ //! //! Handles all epoch‑related logic – logging, switching, computing the //! next epoch, and resetting future events. +#![warn(missing_docs, clippy::missing_docs_in_private_items)] +use crate::error::AppError; use lib_efo::{ epoch_struct::{ConfigWritable, EpochConfig}, error::EpochError, }; -use crate::error::AppError; - pub mod cli_epoch; + /// **Public entry point used by `efo::main`** – dispatches to the real /// handler that lives in `crate::world::EpochManager`. pub fn handle_cmd(cmd: cli_epoch::EpochCmd) -> Result<(), AppError> { @@ -20,7 +21,7 @@ pub fn handle_cmd(cmd: cli_epoch::EpochCmd) -> Result<(), AppError> { match cmd { cli_epoch::EpochCmd::Log(args) => handle_log(args), cli_epoch::EpochCmd::Switch(args) => handle_switch(args, &mut main_epoch), - cli_epoch::EpochCmd::Next(args) => handle_next(args), + cli_epoch::EpochCmd::Next(args) => handle_next(args, &mut main_epoch), cli_epoch::EpochCmd::Reset(args) => handle_reset(args, &mut main_epoch), cli_epoch::EpochCmd::Diff(args) => handle_diff(args), cli_epoch::EpochCmd::Tag(args) => handle_taging(args, &mut main_epoch), @@ -28,37 +29,89 @@ pub fn handle_cmd(cmd: cli_epoch::EpochCmd) -> Result<(), AppError> { } } +/// Show the diff between two epochs fn handle_diff(args: cli_epoch::Diff) -> Result<(), AppError> { let _ = args; unimplemented!("Blocker: There is actually no way to diff the world yet") } +/// Show a log of all different epochs fn handle_log(_args: cli_epoch::Log) -> Result<(), AppError> { println!("Epoch log (most recent first):"); unimplemented!("Just needs for the epoch to implement lvels of displays trait: DisplayLevels"); } -/// Switch the current epoch for another +/// Switches the current epoch to the one specified by the user. +/// +/// This updates the in‑memory configuration, reloads the target epoch, +/// updates the epoch identifier, and persists the changes. +/// +/// # Arguments +/// * `args` – `cli_epoch::Switch` containing the target epoch identifier. +/// * `main_epoch` – mutable reference to the current `EpochConfig`. fn handle_switch(args: cli_epoch::Switch, main_epoch: &mut EpochConfig) -> Result<(), AppError> { let target = main_epoch.get(&args.target)?; main_epoch.try_load(&target)?; main_epoch.epoch_id = target; println!("Switched to epoch {:?}", target); - main_epoch.save( - "Saving modified epoch config".into(), - lib_efo::epoch_struct::SaveMode::Erase, + main_epoch.save_with_context( + "Saving modified epoch config", + &lib_efo::epoch_struct::SaveMode::Erase, )?; Ok(()) } -fn handle_next(args: cli_epoch::Next) -> Result<(), AppError> { - let _ = args; - println!("⚡ Next",); - unimplemented!("Missing logic to process a next event"); +/// Handle the `next` sub‑command. +/// +/// Advances the epoch to the next scheduled event. If the current +/// configuration contains any epochs with an identifier larger than +/// the current one, an error is returned – otherwise the next epoch +/// is computed. +/// +/// # Arguments +/// * `main_epoch` – mutable reference to the current `EpochConfig` +/// (the `cli_epoch::Next` argument is unused). +/// +/// # Returns +/// * `Ok(())` if the next epoch was successfully computed. +/// * `Err(AppError::Epoch(EpochError::FutureEpochExist))` if there are +/// no future epochs to advance to. +fn handle_next(_args: cli_epoch::Next, main_epoch: &mut EpochConfig) -> Result<(), AppError> { + let current_id = main_epoch.epoch_id; + + // Check that there are no future epochs + if main_epoch + .list_existing_epochs + .keys() + .any(|id| id > ¤t_id) + { + Err(AppError::Epoch(EpochError::FutureEpochExist)) + } else { + let new_epoch = main_epoch.compute_next()?; + // This epoch is not used or checked in this command, just directly inserted and saved + + // TODO: Finish + main_epoch + .insert_and_save(new_epoch, &lib_efo::epoch_struct::SaveMode::DoNotErase) + .unwrap(); + // TODO: Does main save or do we save, I feel like we should save + Ok(()) + } } -/// Reset all future events by deleting them +/// Handle the `reset` sub‑command. +/// +/// Deletes all epochs whose identifier is greater than the current one, +/// effectively rolling back to the present epoch. +/// +/// # Arguments +/// * `main_epoch` – mutable reference to the current `EpochConfig` +/// (the `cli_epoch::Reset` argument is unused). +/// +/// # Returns +/// * `Ok(())` if all future epochs were successfully removed. +/// * `Err(AppError)` if any deletion fails. fn handle_reset(args: cli_epoch::Reset, main_epoch: &mut EpochConfig) -> Result<(), AppError> { let _ = args; let current_id = main_epoch.epoch_id; @@ -74,7 +127,21 @@ fn handle_reset(args: cli_epoch::Reset, main_epoch: &mut EpochConfig) -> Result< Ok(()) } -/// Adds a tag to the current epoch +/// Handle the `tag` sub‑command. +/// +/// Adds a tag to the current epoch. The tag must not already exist +/// elsewhere in the configuration; otherwise an error is returned. +/// +/// # Arguments +/// * `args` – `cli_epoch::Tag` containing the tag to add. +/// * `main_epoch` – mutable reference to the current `EpochConfig`. +/// +/// # Returns +/// * `Ok(())` if the tag was successfully added. +/// * `Err(AppError::Epoch(EpochError::TagAlreadyExists))` if the tag +/// already exists in another epoch. +/// * `Err(AppError::Epoch(EpochError::Unknown))` if the epoch cannot +/// be found or saved. fn handle_taging(args: cli_epoch::Tag, main_epoch: &mut EpochConfig) -> Result<(), AppError> { // Load into memory the current epoch main_epoch.try_load(&main_epoch.epoch_id.clone())?; @@ -88,22 +155,23 @@ fn handle_taging(args: cli_epoch::Tag, main_epoch: &mut EpochConfig) -> Result<( } // Modify the epoch to add the tag inside + #[allow(clippy::unwrap_used)] if let Some(current_epoch_info) = main_epoch .list_existing_epochs .get_mut(&main_epoch.epoch_id) .unwrap() { current_epoch_info.tags.push(args.tag.clone()); - current_epoch_info.save( - "Saving modified epoch".to_owned(), - lib_efo::epoch_struct::SaveMode::Erase, + current_epoch_info.save_with_context( + "Saving modified epoch", + &lib_efo::epoch_struct::SaveMode::Erase, )?; main_epoch .tags .insert(args.tag.clone(), main_epoch.epoch_id); - main_epoch.save( - "Saving modified main config".into(), - lib_efo::epoch_struct::SaveMode::Erase, + main_epoch.save_with_context( + "Saving modified main config", + &lib_efo::epoch_struct::SaveMode::Erase, )?; Ok(()) } else { @@ -113,7 +181,10 @@ fn handle_taging(args: cli_epoch::Tag, main_epoch: &mut EpochConfig) -> Result<( } } -/// Basic sanity check +/// Performs a basic sanity check. +/// +/// Currently unimplemented – the function will panic at runtime. +/// fn handle_fsck(args: cli_epoch::Fsck, main_epoch: &mut EpochConfig) -> Result<(), AppError> { let _ = main_epoch; let _ = args; diff --git a/bin_efo/src/commands/epoch/cli_epoch.rs b/bin_efo/src/commands/epoch/cli_epoch.rs index c27e836..1035258 100644 --- a/bin_efo/src/commands/epoch/cli_epoch.rs +++ b/bin_efo/src/commands/epoch/cli_epoch.rs @@ -1,7 +1,27 @@ +//! # `epoch` CLI module +//! +//! This module defines the command‑line interface for the `efo epoch` +//! sub‑command. +//! +//! ## Overview of commands +//! +//! * **`log`** – list epochs in a git‑log style. +//! * **`switch`** – switch to a specific epoch (by id, name or tag). +//! * **`next`** – compute the next epoch from the current one. +//! * **`reset`** – delete all future events after the current epoch. +//! * **`diff`** – show differences between two epochs. +//! * **`tag`** – add a tag to the current epoch. +//! * **`fsck`** – perform basic filesystem level maintenance. + +#![warn(missing_docs, clippy::missing_docs_in_private_items)] + use clap::{Args, Subcommand}; use lib_efo::epoch_struct::EpochIdentifier; -/// The outer clap entry that the binary will dispatch to +/// Top‑level sub‑command for the `efo epoch` command. +/// +/// Each variant represents a distinct epoch operation that can be +/// invoked from the command line. #[derive(Subcommand, Debug)] pub enum EpochCmd { /// List all epochs – a git‑log style view @@ -18,15 +38,19 @@ pub enum EpochCmd { /// Show the differences between two epochs Diff(Diff), - // Tag and next could be implemented as subcommands of epoch - // even if they barely belong here + + /// Add a tag to the current epoch Tag(Tag), /// Basic filesystem level maintenance Fsck(Fsck), } -/// `efo epoch log` +/// Displays a git‑log style list of epochs. +/// +/// # Arguments +/// * `limit` – (Optional) Limit the number of entries shown. +/// Default: `50`. #[derive(Args, Debug)] pub struct Log { /// (Optional) Limit the number of entries shown. @@ -34,7 +58,12 @@ pub struct Log { pub limit: usize, } -/// `efo epoch switch ` +/// Switches to the specified epoch. The target can be an integer, +/// a name, or a tag. +/// +/// # Arguments +/// * `target` – The epoch to switch to. +/// * `force` – If set, drops all pending work and forces the switch. #[derive(Args, Debug)] pub struct Switch { /// The epoch to switch to – can be an integer, a name, or a tag. @@ -46,15 +75,20 @@ pub struct Switch { pub force: bool, } -/// `efo epoch next` +/// Computes the next epoch from the current one. #[derive(Args, Debug)] pub struct Next; -/// `efo epoch reset` +/// Deletes all future events after the current epoch. #[derive(Args, Debug)] pub struct Reset; -/// `efo epoch diff ` +/// Shows the differences between two epochs. +/// +/// # Arguments +/// * `start` – The starting point to compute the differences. +/// * `end` – The end point to compute the differences; defaults to the +/// current epoch if omitted. #[derive(Args, Debug)] pub struct Diff { #[arg(required = true)] @@ -65,7 +99,10 @@ pub struct Diff { pub end: Option, } -/// `efo epoch tag "tag"` +/// Adds a tag to the current epoch. +/// +/// # Arguments +/// * `tag` – The tag to tag the current epoch with. #[derive(Args, Debug)] pub struct Tag { #[arg(required = true)] @@ -73,6 +110,6 @@ pub struct Tag { pub tag: String, } -/// `efo epoch fsck` +/// Performs basic filesystem level maintenance. #[derive(Debug, Args)] pub struct Fsck {} diff --git a/bin_efo/src/commands/error.rs b/bin_efo/src/commands/error.rs deleted file mode 100644 index d4ba9bd..0000000 --- a/bin_efo/src/commands/error.rs +++ /dev/null @@ -1,7 +0,0 @@ -//! Error types that can arise while manipulating epochs. -//! -//! These errors are returned by the `epoch` sub‑command handlers and -//! the underlying `EpochManager`. They are lightweight, strongly‑typed -//! and can be converted into a top‑level error with `thiserror`. - -// use thiserror::Error; diff --git a/bin_efo/src/commands/init.rs b/bin_efo/src/commands/init.rs index 8e5527f..9cfa55d 100644 --- a/bin_efo/src/commands/init.rs +++ b/bin_efo/src/commands/init.rs @@ -1,3 +1,16 @@ +//! # `init` module +//! +//! Provides the implementation of the `init` sub‑command for the +//! command‑line interface. The sub‑command creates an empty +//! repository, writes the default configuration (`.epoch`), +//! and sets up the first epoch (epoch 0). +//! +//! The main public API consists of: +//! +//! * `InitCmd` – a struct containing the command‑line arguments. + +#![warn(missing_docs, clippy::missing_docs_in_private_items)] + use clap::Args; use lib_efo::epoch_struct::{ConfigWritable, EpochInfo}; use lib_efo::{epoch_struct::EpochConfig, error::EpochError}; @@ -6,13 +19,21 @@ use std::fs::read_dir; use crate::error::AppError; #[derive(Args, Debug)] + +/// Arguments for the `init` subcommand. +/// +/// The `--force` flag forces initialisation even when the target +/// directory already contains files. pub struct InitCmd { /// Force initialisation even if the directory isn't empty #[arg(long)] force: bool, } -/// Init an empty repository +/// Initialise an empty repository. +/// +/// Creates the default `EpochConfig`, verifies that the target directory +/// is empty, and writes the initial configuration and epoch data. pub fn init(args: &InitCmd) -> Result<(), AppError> { let epoch_config = EpochConfig::default(); let root = epoch_config.save_folder(); @@ -26,9 +47,9 @@ pub fn init(args: &InitCmd) -> Result<(), AppError> { } init_epoch(args)?; epoch_config - .save( - "Creatig initial config".into(), - lib_efo::epoch_struct::SaveMode::DoNotErase, + .save_with_context( + "Creatig initial config", + &lib_efo::epoch_struct::SaveMode::DoNotErase, ) .map_err(|_| EpochError::AlreadyInitialized { advice: Some( @@ -39,13 +60,16 @@ pub fn init(args: &InitCmd) -> Result<(), AppError> { Ok(()) } -/// Tries to init the epoch 0 +/// Helper that creates the initial epoch (epoch 0). +/// +/// This function is not part of the public API; it is kept internal +/// to `init`. It creates an empty `EpochInfo`, crea fn init_epoch(_args: &InitCmd) -> Result<(), AppError> { let empty = EpochInfo::default(); _ = empty.create_subfolders(); - empty.save( - "Creating empty epoch file 0".into(), - lib_efo::epoch_struct::SaveMode::DoNotErase, + empty.save_with_context( + "Creating empty epoch file 0", + &lib_efo::epoch_struct::SaveMode::DoNotErase, )?; Ok(()) } diff --git a/bin_efo/src/error.rs b/bin_efo/src/error.rs index 9820956..0199a3c 100644 --- a/bin_efo/src/error.rs +++ b/bin_efo/src/error.rs @@ -3,6 +3,8 @@ //! `AppError` aggregates all error kinds that may surface during a command //! execution: parsing, I/O, epoch logic, storage, and a catch‑all. +#![warn(missing_docs, clippy::missing_docs_in_private_items)] + use lib_efo::error::{EpochError, StorageError}; use miette::Diagnostic; use thiserror::Error; diff --git a/bin_efo/src/main.rs b/bin_efo/src/main.rs index d5e4391..4654c76 100644 --- a/bin_efo/src/main.rs +++ b/bin_efo/src/main.rs @@ -19,6 +19,8 @@ //! ```sh //! efo epoch switch 5 //! ``` + +#![warn(missing_docs, clippy::missing_docs_in_private_items)] use clap::{Parser, Subcommand}; use crate::commands::init::InitCmd; @@ -26,18 +28,28 @@ use crate::{commands::epoch::cli_epoch::EpochCmd, error::AppError}; mod commands; mod error; -/// Root parser – the “efo” program +/// The root command‑line parser for the `efo` binary. +/// +/// It uses `clap` to parse the top‑level sub‑commands (`init`, `epoch`, …) +/// and stores them in the `command` field. #[derive(Parser, Debug)] #[command(name = "efo")] #[command(about = "Epoch Forge – manage organisations over time")] struct Cli { #[command(subcommand)] + /// The top level command to be executed command: TopLevelCmd, } +/// Enumeration of the top‑level sub‑commands that `efo` accepts. +/// +/// Each variant corresponds to a single sub‑command and holds its own +/// argument structure. #[derive(Subcommand, Debug)] enum TopLevelCmd { + /// Initialise a new epoch folder. Init(InitCmd), + /// Advance or query the current epoch. #[command(subcommand)] Epoch(EpochCmd), // Event(commands::event::EventCmd), @@ -47,6 +59,11 @@ enum TopLevelCmd { // Link(commands::link::LinkCmd), } +/// Program entry point. +/// +/// Parses the command‑line arguments and dispatches to the selected +/// sub‑command. Errors returned by the sub‑command handlers are printed +/// to stdout and returned as a `miette::Result<()>`. fn main() -> miette::Result<()> { let cli = Cli::parse(); @@ -66,6 +83,19 @@ fn main() -> miette::Result<()> { Ok(()) } +/// Dispatches the parsed command to the appropriate handler. +/// +/// # Arguments +/// * `cli` – The parsed command‑line options. +/// +/// # Returns +/// * `Ok(())` on success. +/// * `Err(AppError)` if the chosen sub‑command handler fails. +/// +/// The function matches on the `TopLevelCmd` variant and calls the +/// corresponding handler in the `commands` module. Any error is +/// propagated to the caller, which in `main` will be printed to +/// stdout and returned as a `miette::Result<()>`. fn exec_dispatch(cli: Cli) -> Result<(), AppError> { match cli.command { TopLevelCmd::Init(cmd) => { diff --git a/lib_efo/Cargo.toml b/lib_efo/Cargo.toml index 9398e9c..734b55e 100644 --- a/lib_efo/Cargo.toml +++ b/lib_efo/Cargo.toml @@ -9,3 +9,4 @@ serde = {workspace = true} thiserror = {workspace = true} clap = {workspace = true} miette = {workspace = true} +derive_more = { version = "2.0.1", features = ["display"] } diff --git a/lib_efo/src/epoch_struct.rs b/lib_efo/src/epoch_struct.rs index b53e425..8432369 100644 --- a/lib_efo/src/epoch_struct.rs +++ b/lib_efo/src/epoch_struct.rs @@ -18,6 +18,7 @@ //! or resetting can be done by reading/writing a handful of JSON/YAML //! files, just like a git repository tracks its commits and //! `HEAD` pointer. +#![warn(missing_docs, clippy::missing_docs_in_private_items)] use clap::error::ErrorKind; use serde::{Deserialize, Serialize}; @@ -32,8 +33,12 @@ use std::{ use crate::{epoch_struct, error::EpochError, io_err_with_help}; +// TODO: Try to load from a config and have it inserted as a backup +/// The subfolder naming convention static SUBFOLDER_NAMING: &str = "epoch"; +/// The main name of the epoch static MAIN_NAME: &str = ".epoch"; +/// The subname of the epochinfo static SUB_NAME: &str = ".epochinfo"; /// The file written to *.epochconfig* that tells the CLI which @@ -155,6 +160,7 @@ impl EpochConfig { } } + /// Return the name of the subfolder used to save this structure fn save_subfolder(&self) -> String { format!("{}/", SUBFOLDER_NAMING) } @@ -174,6 +180,41 @@ impl EpochConfig { )?; Ok(()) } + + /// Compute the next epoch, by defering the work to the Epochinfo -> World + /// Return the id of the next (and now present) epoch + pub fn compute_next(&mut self) -> Result { + // unimplemented!() + // TODO: Implement this + print!("DEBUG LINE: COMPUTING NEXT EPOCH"); + // New fake epoch + Ok(EpochInfo::with_id(&self.epoch_id.next())) + } + + /// Insert the given epoch and save it + pub fn insert_and_save( + &mut self, + new_epoch: EpochInfo, + save_mode: &SaveMode, + ) -> Result<(), EpochError> { + if self.list_existing_epochs.contains_key(&new_epoch.epoch_id) { + return Err(EpochError::EpochAlreadyExists(new_epoch.epoch_id)); + } + + // TODO: Finish + new_epoch + .save_with_context("Saving new epoch without subfolders", save_mode) + .unwrap(); + new_epoch.create_subfolders().unwrap(); + new_epoch.create_subfolders().unwrap(); + new_epoch.create_subfolders().unwrap(); + new_epoch + .save_with_context("Saving new epoch", save_mode) + .unwrap(); + + // Add the epoch to the list of epochs + Ok(()) + } } /// Trait representing a serialisable / writable config @@ -194,19 +235,22 @@ pub trait ConfigWritable: Serialize { } /// Save the config into it's nominal path - fn save( + /// + /// This command will NOT create all subdirectories + fn save_with_context( &self, // Very unsure about this versus a macro - action_description: String, - do_not_erase: SaveMode, + action_description: &str, + do_not_erase: &SaveMode, // advice: Option, ) -> Result<(), EpochError> { - let mut f = match do_not_erase { + let mut f = match *do_not_erase { SaveMode::Erase => File::create(self.save_path()), SaveMode::DoNotErase => File::create_new(self.save_path()), } .map_err(|e| EpochError::ConfigCreation(self.save_path(), e))?; - write!(f, "{}", self.as_json(action_description)?).map_err(EpochError::ConfigWrite)?; + write!(f, "{}", self.as_json(action_description.to_owned())?) + .map_err(EpochError::ConfigWrite)?; Ok(()) } } @@ -254,6 +298,8 @@ impl Default for EpochInfo { } } +/// Which save mode to use +#[allow(missing_docs)] pub enum SaveMode { DoNotErase, Erase, @@ -261,6 +307,8 @@ pub enum SaveMode { impl EpochInfo { /// Create all subfolders as needed + /// + /// This command can be safely used even if the folder already exists pub fn create_subfolders(&self) -> Result<(), EpochError> { io_err_with_help!(create_dir_all(self.save_folder()), "Creating subfolders") } @@ -301,6 +349,11 @@ impl EpochId { pub fn new(id: u64) -> Self { Self { id } } + + /// Return the next epochId + pub fn next(&self) -> Self { + Self { id: self.id + 1 } + } } impl std::ops::Deref for EpochId { diff --git a/lib_efo/src/error.rs b/lib_efo/src/error.rs index be6fc47..7f8ed38 100644 --- a/lib_efo/src/error.rs +++ b/lib_efo/src/error.rs @@ -1,9 +1,15 @@ //! Error types that arise when interacting with the storage layer. //! -//! These are the only errors emitted by the `Storage` abstraction. -//! They are lightweight, strongly‑typed and can be converted to the -//! top‑level `AppError` via `thiserror`. +//! These are the only errors emitted by the `Storage` abstraction. They are +//! lightweight, strongly‑typed, and can be converted to the top‑level +//! `AppError` via `thiserror`. +//! +//! The public items below are all lightweight error types that can be +//! produced by the storage layer or the epoch handling subsystem. +#![warn(missing_docs, clippy::missing_docs_in_private_items)] + +use derive_more::Display; use std::{num::ParseIntError, path::PathBuf}; use thiserror::Error; @@ -12,6 +18,10 @@ use crate::epoch_struct::EpochId; use miette::Diagnostic; /// Errors that can be returned by the storage layer. +/// +/// The variants are intentionally small – each one carries all the +/// information required to surface a helpful message to the user. +// TODO: Remove or rethink these errors #[derive(Debug, Error, Diagnostic)] pub enum StorageError { /// Problems with serialisation / deserialisation. @@ -32,157 +42,207 @@ pub enum StorageError { } /// All errors that can occur while working with epochs. -/// The enum is deliberately *small* – each variant is self‑contained -/// and carries the information you need to surface a friendly message +/// +/// The enum is deliberately _small_ – each variant is self‑contained and +/// carries the information you need to surface a friendly message /// to the user (and to the test‑suite). +// TODO: Split effectively user errors to avoid the usage of advice and such #[derive(Error, Debug, Diagnostic)] pub enum EpochError { - /// Problems with the `.epochconfig` file + /// Problems with the `.epochconfig` file. #[error("Failed to read epoch configuration")] + #[diagnostic(code(EpochError::ConfigRead))] ConfigRead(#[source] std::io::Error), + /// Failed to write the epoch configuration. #[error("Failed to write epoch configuration")] + #[diagnostic(code(EpochError::ConfigWrite))] ConfigWrite(#[source] std::io::Error), + /// Failed to create the epoch configuration. #[error("Failed to create the epoch configuration")] #[help("Make sure the path is writable")] + #[diagnostic(code(EpochError::ConfigCreation))] ConfigCreation(String, #[source] std::io::Error), + /// This directory is already an epoch folder and thus cannot be initialized. #[error("This directory is already an epoch folder and thus cannot be initialized")] #[diagnostic(code(EpochError::AlreadyInitialized))] AlreadyInitialized { #[help] + /// User given advice advice: Option, }, + /// This directory isn't empty and thus cannot be initialized. #[error("This directory isn't empty and thus cannot be initialized")] #[diagnostic(code(EpochError::FolderNotEmpty))] #[diagnostic(help("Empty the folder or remove its content first"))] - // #[diagnostic(label((1,1)))] FolderNotEmpty { #[source_code] + /// Name of the file causing problem name: Option, - + /// Trick used to have a cute line showing the following error message #[label("This file is present and forbid the command to execute properly")] show_label: Option<(usize, usize)>, }, - /// Problems while serialising / deserialising an `EpochInfo` + /// Problems while serialising / deserialising an `EpochInfo`. #[error("Failed to parse `.epochinfo` in epoch {0} ({1}): {2}")] + #[diagnostic(code(EpochError::EpochInfoParse))] EpochInfoParse(EpochId, PathBuf, #[source] serde_json::Error), + /// Failed to write `.epochinfo` in epoch {id} ({path}). #[error("Failed to write `.epochinfo` in epoch {id} ({path})")] #[diagnostic(code(EpochError::EpochInfoWrite))] EpochInfoWrite { + /// The id of the epoch id: EpochId, + /// The path of the epoch path: PathBuf, - + /// An optionnal help message #[help] help: Option, - + /// The source error #[source] src: Option, }, - /// The user supplied an epoch id or tag that does not exist - #[error("No epoch found for id/tag `{}`", .0)] + /// The user supplied an epoch id or tag that does not exist. + #[error("No epoch found for id/tag `{0}`")] + #[diagnostic(code(EpochError::EpochNotFound))] EpochNotFound(String), - /// The user attempted to resolve an epoch that is *ambiguous* – e.g. two - /// tags with the same name or a tag that points to a non‑existent id - #[error("Tag `{}` resolves to either multiple epochs or invalid epoch", .0)] + /// The user attempted to resolve an epoch that is ambiguous. + #[error("Tag `{0}` resolves to either multiple epochs or invalid epoch")] + #[diagnostic(code(EpochError::AmbiguousTag))] AmbiguousTag(String), - /// The epoch folder for the target id is missing - #[error("Missing directory for epoch {} at `{}`", .0, .1.display())] + /// The epoch folder for the target id is missing. + #[error("Missing directory for epoch {0} at `{1}`")] + #[diagnostic(code(EpochError::EpochFolderMissing))] EpochFolderMissing(EpochId, PathBuf), - /// There are *future* events left in the current epoch, so you cannot compute `next` - #[error("Cannot compute `next` because there are pending future events")] - FutureEventsExist, + /// A future epoch exists, forbidding you to compute `next` and overriding them. + #[diagnostic(help("Use epoch reset if you want to erase all future epochs first"))] + #[error("Cannot compute `next` because future epoch exists")] + #[diagnostic(code(EpochError::FutureEpochExist))] + FutureEpochExist, - /// Attempt to switch to an epoch that has already been *advanced* past - /// the current world state (e.g. you are at epoch 5 but try to switch - /// to epoch 7 while epoch 6 is still in the past) - #[error("Cannot switch to epoch `{}` – the world has already advanced beyond it", .0)] + /// A specific epoch exists, forbidding the further execution of the command. + #[diagnostic(help("Use epoch reset or manually delete the epoch {0}"))] + #[error("The epoch {0} exists forbidding the execution of the command")] + #[diagnostic(code(EpochError::EpochAlreadyExists))] + EpochAlreadyExists(EpochId), + + /// Attempt to switch to an epoch that has already been advanced past. + #[error("Cannot switch to epoch `{0}` – the world has already advanced beyond it")] + #[diagnostic(code(EpochError::SwitchPastEpoch))] SwitchPastEpoch(EpochId), - /// The supplied epoch id is out of bounds (negative, zero or too large) - #[error("Invalid epoch id `{}` – must be a positive, non‑overflowing integer", .0)] + /// The supplied epoch id is out of bounds (negative, zero or too large). + #[error("Invalid epoch id `{0}` – must be a positive, non‑overflowing integer")] + #[diagnostic(code(EpochError::InvalidEpochId))] InvalidEpochId(EpochId), - /// A tag that the user tried to assign already exists - #[error("Tag `{}` already exists for epoch {}", .1, .0)] + /// A tag that the user tried to assign already exists. + #[error("Tag `{1}` already exists for epoch {0}")] + #[diagnostic(code(EpochError::InvalidEpochId))] TagAlreadyExists(EpochId, String), - // /// An attempt to delete or reset events failed because the world - // /// was in an inconsistent state (e.g. `reset` called before any `switch`) - // #[error("Reset failed: no epoch has been switched to yet")] - // ResetBeforeSwitch, - /// The parent epoch referenced in an `EpochInfo` cannot be found + /// The parent epoch referenced in an `EpochInfo` cannot be found. #[error("Parent epoch {} referenced by epoch {} does not exist", .0, .1)] + #[diagnostic(code(EpochError::ParentEpochMissing))] ParentEpochMissing(EpochId, EpochId), - /// Generic I/O errors that bubble up from other sub‑tasks + /// Generic I/O errors that bubble up from other sub‑tasks. #[error("I/O error")] #[diagnostic(code(EpochError::GenericIO))] Io { + /// The source error #[source] source: std::io::Error, - + /// An optionnal help message #[help] help: Option, + /// Where the error originated from + error_line: u32, }, - /// Serialization / deserialization errors that are not caught above + /// Serialization / deserialization errors that are not caught above. #[error("Serialization error from {file_name}")] #[diagnostic(code(EpochError::SerdeError))] Serde { + /// The source error #[source] source: serde_json::Error, - + /// The file that was being written file_name: String, - + /// An optionnal help message #[help] help: Option, }, - /// The epoch tree is in an incorrect state + /// The epoch tree is in an incorrect state. #[error("Invalid epoch tree at {0}")] + #[diagnostic(code(EpochError::TreeInvalid))] TreeInvalid(EpochId, String), - /// The main folder is not an epoch folder + /// The main folder is not an epoch folder. #[error("The given directory ({0:?}) is not an epoch folder")] + #[diagnostic(code(EpochError::MainFolderInvalid))] MainFolderInvalid(String), - /// Couldn't parse an EpochId + /// Couldn't parse an `EpochId`. #[error("The id ({0}) couldn't be converted to a valid EpochId")] - #[diagnostic(code(EpochError::ConversionIdImpossible))] + #[diagnostic(code(EpochError::ParsingEpochId))] ParsingEpochId(#[from] ParseIntError), - /// Any other error that didn't fit into the above categories + /// Any other error that didn't fit into the above categories. #[error("An unknown error occurred: {0}")] + #[diagnostic(code(EpochError::Unknown))] Unknown(String), - /// User error, meant to be very explicit over what happened and what to do + /// User error, meant to be very explicit over what happened and what to do. #[error("An user facing error")] - UserError(#[help] String), + #[diagnostic(code(EpochError::UserError))] + UserError(#[help] UserErrors), } +/// A small enum of explicit user‑facing error messages. +/// +/// The variants are deliberately simple; each one is rendered with a +/// clear message via `derive_more::Display`. +#[derive(Debug, Display, Diagnostic, Error)] +pub enum UserErrors { + /// The classic mistake + #[display("The user did a very bad thing")] + #[diagnostic(code(UserErrors::DSItF))] + DSItF, +} // macro_rules! err_with { // ($expr:expr, $err_ty:ty {$($field:ident : $value:expr),* $(,)?}) => {{ // $expr.map_err(|e| { $err_ty { $($field: $value),* } }) // }}; // } +/// Helper macro to convert a `std::io::Error` into an `EpochError::Io` +/// with an attached help message. +/// +/// ```rust +/// # use lib_efo::error::io_err_with_help; +/// let result: Result<(), std::io::Error> = std::fs::read_to_string("does_not_exist").map(|_| ()); +/// let err = io_err_with_help!(result, "Make sure the file exists"); +/// ``` +/// +/// The macro captures the current line number for debugging purposes. #[macro_export] macro_rules! io_err_with_help { - // $expr: the expression that produces the Result - // $help: string literal with the help message ($expr:expr, $($help:expr),*) => {{ $expr.map_err(|e| EpochError::Io { source: e, help: Some(format!($($help),*)), + error_line: line!(), }) }}; } diff --git a/lib_efo/src/lib.rs b/lib_efo/src/lib.rs index 8a5d8e0..069ce41 100644 --- a/lib_efo/src/lib.rs +++ b/lib_efo/src/lib.rs @@ -17,6 +17,8 @@ //! be persisted easily. The `World` struct also offers a convenient //! `World::load()` / `World::save()` API that uses the default JSON file +#![warn(missing_docs, clippy::missing_docs_in_private_items)] + pub mod epoch_struct; #[macro_use] pub mod error; diff --git a/lib_efo/src/utils.rs b/lib_efo/src/utils.rs index c7963dd..d5c2794 100644 --- a/lib_efo/src/utils.rs +++ b/lib_efo/src/utils.rs @@ -4,6 +4,8 @@ //! //! +#![warn(missing_docs, clippy::missing_docs_in_private_items)] + use std::path::Path; use crate::error::EpochError; -- 2.45.1 From a87fe4a848e7d8000082299cbc2889aef8425271 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Fri, 28 Nov 2025 17:16:41 +0100 Subject: [PATCH 03/22] Adds most of next and delete logic --- bin_efo/src/commands/epoch.rs | 13 ++++++++++--- bin_efo/src/main.rs | 2 -- lib_efo/src/epoch_struct.rs | 30 +++++++++++++++++------------- 3 files changed, 27 insertions(+), 18 deletions(-) diff --git a/bin_efo/src/commands/epoch.rs b/bin_efo/src/commands/epoch.rs index 96e191f..1717cd8 100644 --- a/bin_efo/src/commands/epoch.rs +++ b/bin_efo/src/commands/epoch.rs @@ -26,7 +26,11 @@ pub fn handle_cmd(cmd: cli_epoch::EpochCmd) -> Result<(), AppError> { cli_epoch::EpochCmd::Diff(args) => handle_diff(args), cli_epoch::EpochCmd::Tag(args) => handle_taging(args, &mut main_epoch), cli_epoch::EpochCmd::Fsck(args) => handle_fsck(args, &mut main_epoch), - } + }?; + + // TODO: Remove this debug + println!("The main epoch is {:#?}", main_epoch); + Ok(()) } /// Show the diff between two epochs @@ -115,14 +119,17 @@ fn handle_next(_args: cli_epoch::Next, main_epoch: &mut EpochConfig) -> Result<( fn handle_reset(args: cli_epoch::Reset, main_epoch: &mut EpochConfig) -> Result<(), AppError> { let _ = args; let current_id = main_epoch.epoch_id; + // for id in main_epoch for id in main_epoch .list_existing_epochs .keys() .filter(|&k| k > ¤t_id) + .copied() + // Middle step necessary for borrowing purposes + .collect::>() { - main_epoch.delete_id(*id)? + main_epoch.delete_id(id)? } - println!("All future events deleted – back to epoch {current_id}",); Ok(()) } diff --git a/bin_efo/src/main.rs b/bin_efo/src/main.rs index 4654c76..a7afd47 100644 --- a/bin_efo/src/main.rs +++ b/bin_efo/src/main.rs @@ -75,8 +75,6 @@ fn main() -> miette::Result<()> { // AppError::Storage(storage_error) => todo!(), // AppError::Other(_) => todo!(), // } - println!("The program didn't exit properly and returned the following error:"); - // println!("{}", e); Err(e)?; } diff --git a/lib_efo/src/epoch_struct.rs b/lib_efo/src/epoch_struct.rs index 8432369..fb9d488 100644 --- a/lib_efo/src/epoch_struct.rs +++ b/lib_efo/src/epoch_struct.rs @@ -121,7 +121,10 @@ impl EpochConfig { /// Try to load into memory the given epoch id pub fn try_load(&mut self, epoch_id: &EpochId) -> Result<(), EpochError> { // Preload the epoch - let value = self.list_existing_epochs.get_mut(epoch_id).unwrap(); + let value = self + .list_existing_epochs + .get_mut(epoch_id) + .ok_or(EpochError::EpochNotFound(format!("{epoch_id}")))?; // Create a mock epoch let path = EpochInfo::with_id(epoch_id).save_path(); @@ -166,7 +169,8 @@ impl EpochConfig { } /// Tries to delete an entire epoch folder by Id - pub fn delete_id(&self, id: EpochId) -> Result<(), EpochError> { + // TODO: Create a delete_ids taking an iterator for added performance on huge deletions + pub fn delete_id(&mut self, id: EpochId) -> Result<(), EpochError> { if !self.list_existing_epochs.contains_key(&id) { println!( "The given epoch {} doesn't exists and it's deletion was skipped", @@ -178,6 +182,9 @@ impl EpochConfig { "Removing the epoch {}", id )?; + self.list_existing_epochs.remove(&id); + self.tags.retain(|_k, v| *v != id); + self.save_with_context("Saving after delete_id", &SaveMode::Erase)?; Ok(()) } @@ -201,18 +208,15 @@ impl EpochConfig { return Err(EpochError::EpochAlreadyExists(new_epoch.epoch_id)); } - // TODO: Finish - new_epoch - .save_with_context("Saving new epoch without subfolders", save_mode) - .unwrap(); - new_epoch.create_subfolders().unwrap(); - new_epoch.create_subfolders().unwrap(); - new_epoch.create_subfolders().unwrap(); - new_epoch - .save_with_context("Saving new epoch", save_mode) - .unwrap(); + new_epoch.create_subfolders()?; + new_epoch.save_with_context("Saving new epoch", save_mode)?; - // Add the epoch to the list of epochs + // Add the epoch to the list of epochs, not doing so will still have it added + // at the next iteration since the command always parse the files to determine it's state rater that the list + // not doing so would likely create errors if insert is used before another command + self.list_existing_epochs + .insert(new_epoch.epoch_id, Some(new_epoch)); + self.save_with_context("Saving after insert_and_save", &SaveMode::Erase)?; Ok(()) } } -- 2.45.1 From 48a95658935fdf9f4b1d422fc9dc76c735b0d97b Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Fri, 28 Nov 2025 22:36:22 +0100 Subject: [PATCH 04/22] Adds some traits, debug, and logging --- Cargo.lock | 16 +++++ bin_efo/src/commands.rs | 5 ++ bin_efo/src/commands/epoch.rs | 33 ++++++--- bin_efo/src/commands/init.rs | 2 +- bin_efo/src/main.rs | 13 ++-- lib_efo/Cargo.toml | 1 + lib_efo/src/epoch_struct.rs | 129 +++++++++++++++++++++++++++++----- lib_efo/src/epoch_traits.rs | 40 +++++++++++ lib_efo/src/error.rs | 4 +- lib_efo/src/lib.rs | 19 ++--- 10 files changed, 214 insertions(+), 48 deletions(-) create mode 100644 lib_efo/src/epoch_traits.rs diff --git a/Cargo.lock b/Cargo.lock index b2e6278..d50fee9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -192,6 +192,15 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "fancy-table" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cca3bc2bf46d82914b5308d05b12053e79079429ae2b13267238718033ae1eb7" +dependencies = [ + "smallvec", +] + [[package]] name = "gimli" version = "0.32.3" @@ -228,6 +237,7 @@ version = "0.1.0" dependencies = [ "clap", "derive_more", + "fancy-table", "miette", "serde", "serde_json", @@ -398,6 +408,12 @@ dependencies = [ "serde_core", ] +[[package]] +name = "smallvec" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" + [[package]] name = "strsim" version = "0.11.1" diff --git a/bin_efo/src/commands.rs b/bin_efo/src/commands.rs index a9861be..3bbee69 100644 --- a/bin_efo/src/commands.rs +++ b/bin_efo/src/commands.rs @@ -10,3 +10,8 @@ pub mod epoch; pub mod init; +// pub mod diff; +// pub mod utils; +// pub mod event; +// pub mod town; +// pub mod chr; diff --git a/bin_efo/src/commands/epoch.rs b/bin_efo/src/commands/epoch.rs index 1717cd8..34da5a6 100644 --- a/bin_efo/src/commands/epoch.rs +++ b/bin_efo/src/commands/epoch.rs @@ -16,10 +16,10 @@ pub mod cli_epoch; /// handler that lives in `crate::world::EpochManager`. pub fn handle_cmd(cmd: cli_epoch::EpochCmd) -> Result<(), AppError> { let mut main_epoch = EpochConfig::new_from_path(None)?; - // TODO: Remove this debug - println!("The main epoch is {:#?}", main_epoch); + // // TODO[2]: Remove this debug + // println!("The main epoch is {:#?}", main_epoch); match cmd { - cli_epoch::EpochCmd::Log(args) => handle_log(args), + cli_epoch::EpochCmd::Log(args) => handle_log(args, &mut main_epoch), cli_epoch::EpochCmd::Switch(args) => handle_switch(args, &mut main_epoch), cli_epoch::EpochCmd::Next(args) => handle_next(args, &mut main_epoch), cli_epoch::EpochCmd::Reset(args) => handle_reset(args, &mut main_epoch), @@ -28,8 +28,8 @@ pub fn handle_cmd(cmd: cli_epoch::EpochCmd) -> Result<(), AppError> { cli_epoch::EpochCmd::Fsck(args) => handle_fsck(args, &mut main_epoch), }?; - // TODO: Remove this debug - println!("The main epoch is {:#?}", main_epoch); + // // TODO[2]: Remove this debug + // println!("The main epoch is {:#?}", main_epoch); Ok(()) } @@ -40,9 +40,24 @@ fn handle_diff(args: cli_epoch::Diff) -> Result<(), AppError> { } /// Show a log of all different epochs -fn handle_log(_args: cli_epoch::Log) -> Result<(), AppError> { +fn handle_log(args: cli_epoch::Log, main_epoch: &mut EpochConfig) -> Result<(), AppError> { println!("Epoch log (most recent first):"); - unimplemented!("Just needs for the epoch to implement lvels of displays trait: DisplayLevels"); + let limit = args.limit; + let start_id = &main_epoch.epoch_id; + + let list_id = main_epoch + .list_existing_epochs + .iter() + .filter(|(id, _)| id <= &start_id) + .take(limit) + .map(|(id, _)| id) + .copied() + .collect::>(); + + // TODO[8]: Consider other ways to log than one element at a time + main_epoch.log_elements(&list_id)?; + + Ok(()) } /// Switches the current epoch to the one specified by the user. @@ -93,13 +108,11 @@ fn handle_next(_args: cli_epoch::Next, main_epoch: &mut EpochConfig) -> Result<( Err(AppError::Epoch(EpochError::FutureEpochExist)) } else { let new_epoch = main_epoch.compute_next()?; - // This epoch is not used or checked in this command, just directly inserted and saved - // TODO: Finish + // Insert new epoch main_epoch .insert_and_save(new_epoch, &lib_efo::epoch_struct::SaveMode::DoNotErase) .unwrap(); - // TODO: Does main save or do we save, I feel like we should save Ok(()) } } diff --git a/bin_efo/src/commands/init.rs b/bin_efo/src/commands/init.rs index 9cfa55d..d91f635 100644 --- a/bin_efo/src/commands/init.rs +++ b/bin_efo/src/commands/init.rs @@ -34,11 +34,11 @@ pub struct InitCmd { /// /// Creates the default `EpochConfig`, verifies that the target directory /// is empty, and writes the initial configuration and epoch data. +//TODO[5]: Upholster the logic behind force and empty detection pub fn init(args: &InitCmd) -> Result<(), AppError> { let epoch_config = EpochConfig::default(); let root = epoch_config.save_folder(); - //TODO: This can be really deceiving when only .epoch is present if read_dir(root)?.count() != 0 { Err(EpochError::FolderNotEmpty { name: None, diff --git a/bin_efo/src/main.rs b/bin_efo/src/main.rs index a7afd47..21fc81c 100644 --- a/bin_efo/src/main.rs +++ b/bin_efo/src/main.rs @@ -21,7 +21,7 @@ //! ``` #![warn(missing_docs, clippy::missing_docs_in_private_items)] -use clap::{Parser, Subcommand}; +use clap::{ArgAction, Parser, Subcommand}; use crate::commands::init::InitCmd; use crate::{commands::epoch::cli_epoch::EpochCmd, error::AppError}; @@ -36,6 +36,10 @@ mod error; #[command(name = "efo")] #[command(about = "Epoch Forge – manage organisations over time")] struct Cli { + /// The level of verbosity + #[arg(short, long, action = ArgAction::Count, global = true)] + verbose: u8, + #[command(subcommand)] /// The top level command to be executed command: TopLevelCmd, @@ -68,13 +72,6 @@ fn main() -> miette::Result<()> { let cli = Cli::parse(); if let Err(e) = exec_dispatch(cli) { - // match e{ - // AppError::Clap(error) => todo!(), - // AppError::Io(error) => todo!(), - // AppError::Epoch(epoch_error) => todo!(), - // AppError::Storage(storage_error) => todo!(), - // AppError::Other(_) => todo!(), - // } Err(e)?; } diff --git a/lib_efo/Cargo.toml b/lib_efo/Cargo.toml index 734b55e..e856615 100644 --- a/lib_efo/Cargo.toml +++ b/lib_efo/Cargo.toml @@ -10,3 +10,4 @@ thiserror = {workspace = true} clap = {workspace = true} miette = {workspace = true} derive_more = { version = "2.0.1", features = ["display"] } +fancy-table = "0.4.1" diff --git a/lib_efo/src/epoch_struct.rs b/lib_efo/src/epoch_struct.rs index fb9d488..84212f5 100644 --- a/lib_efo/src/epoch_struct.rs +++ b/lib_efo/src/epoch_struct.rs @@ -19,21 +19,21 @@ //! files, just like a git repository tracks its commits and //! `HEAD` pointer. #![warn(missing_docs, clippy::missing_docs_in_private_items)] - use clap::error::ErrorKind; +use derive_more::Display; use serde::{Deserialize, Serialize}; +use std::io::Write; use std::{ collections::HashMap, fmt, fs::{File, create_dir_all, read_to_string, remove_dir_all}, - io::Write, path::Path, str::FromStr, }; -use crate::{epoch_struct, error::EpochError, io_err_with_help}; +use crate::{epoch_struct, epoch_traits::Prettiable, error::EpochError, io_err_with_help}; -// TODO: Try to load from a config and have it inserted as a backup +// TODO[5]: Try to load from a config and have it inserted as a backup /// The subfolder naming convention static SUBFOLDER_NAMING: &str = "epoch"; /// The main name of the epoch @@ -57,7 +57,7 @@ pub struct EpochConfig { /// Optional human‑friendly tags (e.g. `"winter‑B"`, `"post‑war"`). pub tags: HashMap, - // TODO: Can become important + // TODO[6]: Can become important // #[serde(skip)] // /// Absolute path to `epoch//`. // pub path: PathBuf, @@ -83,7 +83,7 @@ impl EpochConfig { let path = Path::new(MAIN_NAME); if path.is_file() { - // TODO: write a trait for this + // TODO[6]: write a trait for this let config: EpochConfig = serde_json::from_str(&io_err_with_help!( read_to_string(path), "Reading config from path {:?}", @@ -111,14 +111,26 @@ impl EpochConfig { let elt = io_err_with_help!(elt, "Opening file in main config folder")?; if io_err_with_help!(elt.file_type(), "Determining file type of {:?}", elt)?.is_dir() { let id = elt.file_name().to_string_lossy().parse::(); - println!("{:?}", id); + // TODO: Logging + // println!("Initialized {:?}", id); self.list_existing_epochs.insert(id.unwrap(), None); } } Ok(self) } - /// Try to load into memory the given epoch id + /// Loads the metadata for an epoch from disk into the in‑memory cache. + /// + /// The epoch identified by `epoch_id` must exist in `list_existing_epochs`. + /// The JSON file on disk is read, deserialized into an `EpochInfo`, and + /// stored in the map. Any existing value for that epoch is overwritten. + /// + /// # Returns + /// * `Ok(())` when the epoch was successfully read and cached. + /// * `Err(EpochError::EpochNotFound(..))` if the epoch is not present in the + /// internal map. + /// * `Err(EpochError::Serde { .. })` if the JSON file could not be parsed. + /// * `Err(EpochError::Io { .. })` if the file could not be read. pub fn try_load(&mut self, epoch_id: &EpochId) -> Result<(), EpochError> { // Preload the epoch let value = self @@ -143,7 +155,20 @@ impl EpochConfig { Ok(()) } - /// Get an identifier or returns None + /// Retrieves the internal epoch ID for a given identifier. + /// + /// The identifier can be either a *tag* string (`EpochIdentifier::Tag`) or an + /// explicit epoch ID (`EpochIdentifier::Id`). + /// * When a tag is supplied the function looks up the corresponding epoch ID in + /// the `tags` map. + /// * When an ID is supplied it verifies that an epoch with that ID exists in + /// `list_existing_epochs` and returns it. + /// + /// # Returns + /// * `Ok(epoch_id)` when the identifier is successfully resolved. + /// * `Err(EpochError::AmbiguousTag(tag))` if a supplied tag does not exist. + /// * `Err(EpochError::EpochFolderMissing(id, path))` if an ID does not have an + /// associated epoch folder. pub fn get(&self, id: &EpochIdentifier) -> Result { match id { EpochIdentifier::Tag(s) => self @@ -169,7 +194,7 @@ impl EpochConfig { } /// Tries to delete an entire epoch folder by Id - // TODO: Create a delete_ids taking an iterator for added performance on huge deletions + // TODO[9]: Create a delete_ids taking an iterator for added performance on huge deletions pub fn delete_id(&mut self, id: EpochId) -> Result<(), EpochError> { if !self.list_existing_epochs.contains_key(&id) { println!( @@ -192,7 +217,7 @@ impl EpochConfig { /// Return the id of the next (and now present) epoch pub fn compute_next(&mut self) -> Result { // unimplemented!() - // TODO: Implement this + // TODO[1]: Implement this print!("DEBUG LINE: COMPUTING NEXT EPOCH"); // New fake epoch Ok(EpochInfo::with_id(&self.epoch_id.next())) @@ -214,11 +239,35 @@ impl EpochConfig { // Add the epoch to the list of epochs, not doing so will still have it added // at the next iteration since the command always parse the files to determine it's state rater that the list // not doing so would likely create errors if insert is used before another command - self.list_existing_epochs - .insert(new_epoch.epoch_id, Some(new_epoch)); + let new_id = new_epoch.epoch_id; + self.list_existing_epochs.insert(new_id, Some(new_epoch)); + self.epoch_id = new_id; self.save_with_context("Saving after insert_and_save", &SaveMode::Erase)?; Ok(()) } + + /// Loads into memory all elements to show them as log + pub fn log_elements(&mut self, list_ids: &[EpochId]) -> Result<(), EpochError> { + let mut items_to_log = Vec::with_capacity(list_ids.len()); + for id in list_ids { + self.try_load(id)?; + } + for id in list_ids { + if let Some(info) = self + .list_existing_epochs + .get(id) + .ok_or(EpochError::EpochNotFound(id.to_string()))? + { + items_to_log.push(info); + } + } + // items_to_log[0].as_log() + for item in items_to_log { + item.show_as_log(); + } + // let table = FancyTable::create();! + Ok(()) + } } /// Trait representing a serialisable / writable config @@ -266,14 +315,12 @@ pub trait ConfigWritable: Serialize { /// reconstruct the state *of that particular epoch* (seed, selected /// events, parent link, etc.). The full world data is kept in /// separate storage (e.g. `world.json`). -#[derive(Debug, Clone, Serialize, Deserialize)] +#[derive(Debug, Clone, Serialize, Deserialize, Display)] +#[display("Epoch {epoch_id:>5} | seed {rng_seed:<10} | tags {tags:?} | summary {summary:?}")] pub struct EpochInfo { /// The ID of this epoch – should match the directory name. pub epoch_id: EpochId, - /// The ID of the parent (previous) epoch, if not a root. - pub parent_id: Option, - /// RNG seed that was used to generate randomised data for /// this epoch. Keeping it in the file guarantees repeatable /// behaviour when replaying the same epoch. @@ -290,11 +337,57 @@ pub struct EpochInfo { pub summary: Option, } +impl Prettiable for EpochInfo { + // fn show_as_table(list: &[Self]) + // where + // Self: std::marker::Sized, + // { + // let table = fancy_table::FancyTable::create(fancy_table::FancyTableOpts { + // charset: fancy_table::charset::Charset::Modern, + // ..Default::default() + // }) + // .add_title_with_align("log", fancy_table::TitleAlign::RightOffset(1)) + // .add_column_named("ID", fancy_table::Layout::Slim) + // .add_column_named("RNG SEED", fancy_table::Layout::Fixed(16)) + // .add_column_named_wrapping_with_align( + // "TAGS", + // fancy_table::Layout::Fixed(25), + // fancy_table::Align::Center, + // ) + // .add_column_named_with_align( + // "SUMMARY", + // fancy_table::Layout::Expandable(150), + // fancy_table::Align::Right, + // ) + // .hseparator(Some(fancy_table::Separator::Double)) + // .padding(3) + // .width(102) + // .build(); + + // // table.render( + // let list: Vec<&[&str]> = list + // .iter() + // .map(|info| { + // [ + // info.epoch_id.to_string().as_str(), + // info.rng_seed.to_string().as_str(), + // info.tags.join(",").as_str(), + // info.summary.unwrap_or("".to_string()).as_str(), + // ] + // }) + // .collect(); + // // ); + // } + + fn as_log(&self) -> String { + format!("{}", self) + } +} + impl Default for EpochInfo { fn default() -> Self { Self { epoch_id: epoch_struct::EpochId::new(0), - parent_id: None, rng_seed: 0, tags: Vec::new(), summary: None, diff --git a/lib_efo/src/epoch_traits.rs b/lib_efo/src/epoch_traits.rs new file mode 100644 index 0000000..ade1775 --- /dev/null +++ b/lib_efo/src/epoch_traits.rs @@ -0,0 +1,40 @@ +//! epoch_traits.rs +//! +//! All traits used by the `lib_efo` library. +//! These traits are marker traits that describe behaviour +//! common to many of the library’s element types. +#![warn(clippy::missing_docs_in_private_items)] + +/// Elements that can be compared with another instance to produce a diff. +pub trait Diffable {} + +/// Elements that can be applied to the current world state. +pub trait Applyable {} + +/// Elements that can advance to a next state over time. +/// +/// Implementors usually provide a `.next()` method that returns the +/// element’s state after a time step (e.g., fading or diminishing). +pub trait Nextable {} + +/// Elements that can be rendered into a pretty, human‑readable form. +pub trait Prettiable { + // TODO: Doc + /// Show many as a table + fn show_as_table(list: &[Self]) + where + Self: std::marker::Sized, + { + list.iter().for_each(|e| { + e.show_as_log(); + }); + } + + /// Print function as a log + fn show_as_log(&self) { + println!("{}", self.as_log()) + } + + /// Convert the struct into a pretty log + fn as_log(&self) -> String; +} diff --git a/lib_efo/src/error.rs b/lib_efo/src/error.rs index 7f8ed38..dd660b4 100644 --- a/lib_efo/src/error.rs +++ b/lib_efo/src/error.rs @@ -21,7 +21,7 @@ use miette::Diagnostic; /// /// The variants are intentionally small – each one carries all the /// information required to surface a helpful message to the user. -// TODO: Remove or rethink these errors +// TODO[2]: Remove or rethink these errors #[derive(Debug, Error, Diagnostic)] pub enum StorageError { /// Problems with serialisation / deserialisation. @@ -46,7 +46,7 @@ pub enum StorageError { /// The enum is deliberately _small_ – each variant is self‑contained and /// carries the information you need to surface a friendly message /// to the user (and to the test‑suite). -// TODO: Split effectively user errors to avoid the usage of advice and such +// TODO[2]: Split effectively user errors to avoid the usage of advice and such #[derive(Error, Debug, Diagnostic)] pub enum EpochError { /// Problems with the `.epochconfig` file. diff --git a/lib_efo/src/lib.rs b/lib_efo/src/lib.rs index 069ce41..ee2acc6 100644 --- a/lib_efo/src/lib.rs +++ b/lib_efo/src/lib.rs @@ -3,15 +3,15 @@ //! The **engine** that drives *Epoch Forge*. It contains a pure, representation of a fantasy world and all the logic needed to manipulate it. //! //! The crate is split into the following domains, each exposed as a public module: -//! - TODO: `world` – holds the global state (`World`) and a lightweight snapshot (`Context`). -//! - TODO: `epoch` – manages the passage of time and epoch switching. -//! - TODO: `event` – CRUD and evaluation of events that affect the world. -//! - TODO: `org` – organisations, guilds, factions and their history. -//! - TODO: `character` – individual characters, traits and lineage. -//! - TODO: `town` – towns, cities, trade hubs and their populations. -//! - TODO: `link` – relations such as wars, alliances, roads, commerce. -//! - TODO: `storage` – generic persistence layer (`Store`) with JSON/YAML back‑ends. -//! - TODO: `util` – small helpers, ID generation, error types, etc. +//! - TODO[1]: `world` – holds the global state (`World`) and a lightweight snapshot (`Context`). +//! - TODO[0]: `epoch` – manages the passage of time and epoch switching. +//! - TODO[1]: `event` – CRUD and evaluation of events that affect the world. +//! - TODO[4]: `org` – organisations, guilds, factions and their history. +//! - TODO[2]: `character` – individual characters, traits and lineage. +//! - TODO[1]: `town` – towns, cities, trade hubs and their populations. +//! - TODO[2]: `link` – relations such as wars, alliances, roads, commerce. +//! - TODO[3]: `storage` – generic persistence layer (`Store`) with JSON/YAML back‑ends. +//! - TODO[4]: `util` – small helpers, ID generation, error types, etc. //! //! All public types implement `serde::Serialize / Deserialize` so that they can //! be persisted easily. The `World` struct also offers a convenient @@ -20,6 +20,7 @@ #![warn(missing_docs, clippy::missing_docs_in_private_items)] pub mod epoch_struct; +pub mod epoch_traits; #[macro_use] pub mod error; pub mod utils; -- 2.45.1 From 3d739e5b554e837139b59c83ba9a430334dfeb1c Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sat, 29 Nov 2025 00:50:30 +0100 Subject: [PATCH 05/22] Refactors EpochConfig --- Cargo.lock | 79 ++++- bin_efo/src/commands/init.rs | 4 +- lib_efo/Cargo.toml | 2 +- lib_efo/src/epoch_struct.rs | 358 ++++------------------- lib_efo/src/epoch_struct/epoch_config.rs | 256 ++++++++++++++++ lib_efo/src/epoch_traits.rs | 2 +- 6 files changed, 385 insertions(+), 316 deletions(-) create mode 100644 lib_efo/src/epoch_struct/epoch_config.rs diff --git a/Cargo.lock b/Cargo.lock index d50fee9..fb51125 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -155,12 +155,56 @@ version = "0.7.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a1d728cc89cf3aee9ff92b05e62b19ee65a02b5702cff7d5a377e32c6ae29d8d" +[[package]] +name = "cli-table" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "14da8d951cef7cc4f13ccc9b744d736963d57863c7e6fc33c070ea274546082c" +dependencies = [ + "cli-table-derive", + "csv", + "termcolor", + "unicode-width 0.2.2", +] + +[[package]] +name = "cli-table-derive" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c1b60bae2c3d45228dfb096046aa51ef6c300de70b658d7a13fcb0c4f832e" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + [[package]] name = "colorchoice" version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b05b61dc5112cbb17e4b6cd61790d9845d13888356391624cbe7e41efeac1e75" +[[package]] +name = "csv" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52cd9d68cf7efc6ddfaaee42e7288d3a99d613d4b50f76ce9827ae0c6e14f938" +dependencies = [ + "csv-core", + "itoa", + "ryu", + "serde_core", +] + +[[package]] +name = "csv-core" +version = "0.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "704a3c26996a80471189265814dbc2c257598b96b8a7feae2d31ace646bb9782" +dependencies = [ + "memchr", +] + [[package]] name = "derive_more" version = "2.0.1" @@ -192,15 +236,6 @@ dependencies = [ "windows-sys 0.61.2", ] -[[package]] -name = "fancy-table" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cca3bc2bf46d82914b5308d05b12053e79079429ae2b13267238718033ae1eb7" -dependencies = [ - "smallvec", -] - [[package]] name = "gimli" version = "0.32.3" @@ -236,8 +271,8 @@ name = "lib_efo" version = "0.1.0" dependencies = [ "clap", + "cli-table", "derive_more", - "fancy-table", "miette", "serde", "serde_json", @@ -408,12 +443,6 @@ dependencies = [ "serde_core", ] -[[package]] -name = "smallvec" -version = "1.15.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" - [[package]] name = "strsim" version = "0.11.1" @@ -452,6 +481,15 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "termcolor" +version = "1.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755" +dependencies = [ + "winapi-util", +] + [[package]] name = "terminal_size" version = "0.4.3" @@ -528,6 +566,15 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" +[[package]] +name = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys 0.61.2", +] + [[package]] name = "windows-link" version = "0.2.1" diff --git a/bin_efo/src/commands/init.rs b/bin_efo/src/commands/init.rs index d91f635..de03a71 100644 --- a/bin_efo/src/commands/init.rs +++ b/bin_efo/src/commands/init.rs @@ -12,8 +12,8 @@ #![warn(missing_docs, clippy::missing_docs_in_private_items)] use clap::Args; -use lib_efo::epoch_struct::{ConfigWritable, EpochInfo}; -use lib_efo::{epoch_struct::EpochConfig, error::EpochError}; +use lib_efo::epoch_struct::{ConfigWritable, EpochConfig, EpochInfo}; +use lib_efo::error::EpochError; use std::fs::read_dir; use crate::error::AppError; diff --git a/lib_efo/Cargo.toml b/lib_efo/Cargo.toml index e856615..35184e2 100644 --- a/lib_efo/Cargo.toml +++ b/lib_efo/Cargo.toml @@ -10,4 +10,4 @@ thiserror = {workspace = true} clap = {workspace = true} miette = {workspace = true} derive_more = { version = "2.0.1", features = ["display"] } -fancy-table = "0.4.1" +cli-table = "0.5.0" diff --git a/lib_efo/src/epoch_struct.rs b/lib_efo/src/epoch_struct.rs index 84212f5..3a9d2e9 100644 --- a/lib_efo/src/epoch_struct.rs +++ b/lib_efo/src/epoch_struct.rs @@ -20,16 +20,17 @@ //! `HEAD` pointer. #![warn(missing_docs, clippy::missing_docs_in_private_items)] use clap::error::ErrorKind; +use cli_table::Table; use derive_more::Display; use serde::{Deserialize, Serialize}; -use std::io::Write; use std::{ - collections::HashMap, - fmt, - fs::{File, create_dir_all, read_to_string, remove_dir_all}, - path::Path, + fs::{File, create_dir_all}, str::FromStr, }; +use std::{ + io::Write, + ops::{Deref, DerefMut}, +}; use crate::{epoch_struct, epoch_traits::Prettiable, error::EpochError, io_err_with_help}; @@ -41,234 +42,8 @@ static MAIN_NAME: &str = ".epoch"; /// The subname of the epochinfo static SUB_NAME: &str = ".epochinfo"; -/// The file written to *.epochconfig* that tells the CLI which -/// epoch folder is the “current” one. -/// -/// Only the minimal information needed for fast switches is stored: -/// * the numeric identifier of the selected epoch, -/// * a list of human‑readable tags, -/// * the absolute path to the epoch’s directory. -/// -/// No world or event data lives here – it is purely a lightweight pointer. -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct EpochConfig { - /// The epoch ID that the binary should consider “current”. - pub epoch_id: EpochId, - - /// Optional human‑friendly tags (e.g. `"winter‑B"`, `"post‑war"`). - pub tags: HashMap, - // TODO[6]: Can become important - // #[serde(skip)] - // /// Absolute path to `epoch//`. - // pub path: PathBuf, - /// A hashmap containing the name of all existing epochs, only loaded in memory if used - #[serde(skip)] - pub list_existing_epochs: HashMap>, -} - -impl Default for EpochConfig { - /// Create an empty config, mainly for initialisation - fn default() -> Self { - EpochConfig { - epoch_id: EpochId::new(0), - tags: HashMap::new(), - list_existing_epochs: HashMap::new(), - } - } -} - -impl EpochConfig { - /// Create a new config from an existig path - pub fn new_from_path(_path: Option<&Path>) -> Result { - let path = Path::new(MAIN_NAME); - - if path.is_file() { - // TODO[6]: write a trait for this - let config: EpochConfig = serde_json::from_str(&io_err_with_help!( - read_to_string(path), - "Reading config from path {:?}", - path - )?) - .map_err(|e| EpochError::Serde { - source: e, - file_name: path.to_string_lossy().to_string(), - help: None, - })?; - Ok(config.initialize()?) - } else { - Err(EpochError::MainFolderInvalid( - EpochConfig::default().save_folder(), - )) - } - } - - /// Initialize the epoch more in depth - fn initialize(mut self) -> Result { - let path = EpochConfig::default().save_subfolder(); - let path = io_err_with_help!(Path::new(&path).read_dir(), "Reading initial folder {path}")?; - // let mut valid_folders = HashMap::new(); - for elt in path { - let elt = io_err_with_help!(elt, "Opening file in main config folder")?; - if io_err_with_help!(elt.file_type(), "Determining file type of {:?}", elt)?.is_dir() { - let id = elt.file_name().to_string_lossy().parse::(); - // TODO: Logging - // println!("Initialized {:?}", id); - self.list_existing_epochs.insert(id.unwrap(), None); - } - } - Ok(self) - } - - /// Loads the metadata for an epoch from disk into the in‑memory cache. - /// - /// The epoch identified by `epoch_id` must exist in `list_existing_epochs`. - /// The JSON file on disk is read, deserialized into an `EpochInfo`, and - /// stored in the map. Any existing value for that epoch is overwritten. - /// - /// # Returns - /// * `Ok(())` when the epoch was successfully read and cached. - /// * `Err(EpochError::EpochNotFound(..))` if the epoch is not present in the - /// internal map. - /// * `Err(EpochError::Serde { .. })` if the JSON file could not be parsed. - /// * `Err(EpochError::Io { .. })` if the file could not be read. - pub fn try_load(&mut self, epoch_id: &EpochId) -> Result<(), EpochError> { - // Preload the epoch - let value = self - .list_existing_epochs - .get_mut(epoch_id) - .ok_or(EpochError::EpochNotFound(format!("{epoch_id}")))?; - - // Create a mock epoch - let path = EpochInfo::with_id(epoch_id).save_path(); - let read_to_string = io_err_with_help!(read_to_string(&path), "Reading {:?}", path); - - // Try to load - let maybe_epoch: EpochInfo = - serde_json::from_str(&read_to_string?).map_err(|e| EpochError::Serde { - source: e, - file_name: path.to_string(), - help: None, - })?; - - // Overwrite the value - *value = Some(maybe_epoch); - Ok(()) - } - - /// Retrieves the internal epoch ID for a given identifier. - /// - /// The identifier can be either a *tag* string (`EpochIdentifier::Tag`) or an - /// explicit epoch ID (`EpochIdentifier::Id`). - /// * When a tag is supplied the function looks up the corresponding epoch ID in - /// the `tags` map. - /// * When an ID is supplied it verifies that an epoch with that ID exists in - /// `list_existing_epochs` and returns it. - /// - /// # Returns - /// * `Ok(epoch_id)` when the identifier is successfully resolved. - /// * `Err(EpochError::AmbiguousTag(tag))` if a supplied tag does not exist. - /// * `Err(EpochError::EpochFolderMissing(id, path))` if an ID does not have an - /// associated epoch folder. - pub fn get(&self, id: &EpochIdentifier) -> Result { - match id { - EpochIdentifier::Tag(s) => self - .tags - .get(s) - .copied() - .ok_or(EpochError::AmbiguousTag(s.to_string())), - EpochIdentifier::Id(epoch_id) => self - .list_existing_epochs - .contains_key(epoch_id) - .then_some(epoch_id) - .ok_or(EpochError::EpochFolderMissing( - *epoch_id, - EpochConfig::default().save_folder().into(), - )) - .copied(), - } - } - - /// Return the name of the subfolder used to save this structure - fn save_subfolder(&self) -> String { - format!("{}/", SUBFOLDER_NAMING) - } - - /// Tries to delete an entire epoch folder by Id - // TODO[9]: Create a delete_ids taking an iterator for added performance on huge deletions - pub fn delete_id(&mut self, id: EpochId) -> Result<(), EpochError> { - if !self.list_existing_epochs.contains_key(&id) { - println!( - "The given epoch {} doesn't exists and it's deletion was skipped", - id - ) - } - io_err_with_help!( - remove_dir_all(EpochInfo::with_id(&id).save_folder()), - "Removing the epoch {}", - id - )?; - self.list_existing_epochs.remove(&id); - self.tags.retain(|_k, v| *v != id); - self.save_with_context("Saving after delete_id", &SaveMode::Erase)?; - Ok(()) - } - - /// Compute the next epoch, by defering the work to the Epochinfo -> World - /// Return the id of the next (and now present) epoch - pub fn compute_next(&mut self) -> Result { - // unimplemented!() - // TODO[1]: Implement this - print!("DEBUG LINE: COMPUTING NEXT EPOCH"); - // New fake epoch - Ok(EpochInfo::with_id(&self.epoch_id.next())) - } - - /// Insert the given epoch and save it - pub fn insert_and_save( - &mut self, - new_epoch: EpochInfo, - save_mode: &SaveMode, - ) -> Result<(), EpochError> { - if self.list_existing_epochs.contains_key(&new_epoch.epoch_id) { - return Err(EpochError::EpochAlreadyExists(new_epoch.epoch_id)); - } - - new_epoch.create_subfolders()?; - new_epoch.save_with_context("Saving new epoch", save_mode)?; - - // Add the epoch to the list of epochs, not doing so will still have it added - // at the next iteration since the command always parse the files to determine it's state rater that the list - // not doing so would likely create errors if insert is used before another command - let new_id = new_epoch.epoch_id; - self.list_existing_epochs.insert(new_id, Some(new_epoch)); - self.epoch_id = new_id; - self.save_with_context("Saving after insert_and_save", &SaveMode::Erase)?; - Ok(()) - } - - /// Loads into memory all elements to show them as log - pub fn log_elements(&mut self, list_ids: &[EpochId]) -> Result<(), EpochError> { - let mut items_to_log = Vec::with_capacity(list_ids.len()); - for id in list_ids { - self.try_load(id)?; - } - for id in list_ids { - if let Some(info) = self - .list_existing_epochs - .get(id) - .ok_or(EpochError::EpochNotFound(id.to_string()))? - { - items_to_log.push(info); - } - } - // items_to_log[0].as_log() - for item in items_to_log { - item.show_as_log(); - } - // let table = FancyTable::create();! - Ok(()) - } -} +pub mod epoch_config; +pub use epoch_config::EpochConfig; /// Trait representing a serialisable / writable config pub trait ConfigWritable: Serialize { @@ -316,14 +91,19 @@ pub trait ConfigWritable: Serialize { /// events, parent link, etc.). The full world data is kept in /// separate storage (e.g. `world.json`). #[derive(Debug, Clone, Serialize, Deserialize, Display)] -#[display("Epoch {epoch_id:>5} | seed {rng_seed:<10} | tags {tags:?} | summary {summary:?}")] +#[display( + "Epoch ({epoch_id:>5}) | seed ({rng_seed:<10}) | tags ({tags:<10}) | summary ({summary:<20})" +)] +#[derive(Table)] pub struct EpochInfo { /// The ID of this epoch – should match the directory name. + #[table(title = "ID")] pub epoch_id: EpochId, /// RNG seed that was used to generate randomised data for /// this epoch. Keeping it in the file guarantees repeatable /// behaviour when replaying the same epoch. + #[table(title = "Seed")] pub rng_seed: u64, // /// List of event IDs that were accepted for this epoch. @@ -331,53 +111,52 @@ pub struct EpochInfo { // /// parent epoch to the current one. // pub selected_events: Vec, /// Optional tags that help identify the epoch (e.g. `"Winter‑B"`). - pub tags: Vec, + #[table(title = "Tags")] + pub tags: TagList, /// Human‑readable description or summary, useful for the `log` command. - pub summary: Option, + #[table(title = "Summary")] + pub summary: String, +} + +/// A lightweight wrapper around a list of tags. +/// +/// The wrapper exists mainly to give the collection a semantic type +/// and to hide the internal representation. +#[derive(Debug, Clone, Serialize, Deserialize, Display)] +#[display("{inner:?}")] +pub struct TagList { + /// The inner vector of tags + inner: Vec, +} + +impl TagList { + /// Create a new empty tag list + fn new() -> Self { + Self { inner: Vec::new() } + } +} + +impl Deref for TagList { + type Target = Vec; + + fn deref(&self) -> &Self::Target { + &self.inner + } +} +impl DerefMut for TagList { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.inner + } } impl Prettiable for EpochInfo { - // fn show_as_table(list: &[Self]) - // where - // Self: std::marker::Sized, - // { - // let table = fancy_table::FancyTable::create(fancy_table::FancyTableOpts { - // charset: fancy_table::charset::Charset::Modern, - // ..Default::default() - // }) - // .add_title_with_align("log", fancy_table::TitleAlign::RightOffset(1)) - // .add_column_named("ID", fancy_table::Layout::Slim) - // .add_column_named("RNG SEED", fancy_table::Layout::Fixed(16)) - // .add_column_named_wrapping_with_align( - // "TAGS", - // fancy_table::Layout::Fixed(25), - // fancy_table::Align::Center, - // ) - // .add_column_named_with_align( - // "SUMMARY", - // fancy_table::Layout::Expandable(150), - // fancy_table::Align::Right, - // ) - // .hseparator(Some(fancy_table::Separator::Double)) - // .padding(3) - // .width(102) - // .build(); - - // // table.render( - // let list: Vec<&[&str]> = list - // .iter() - // .map(|info| { - // [ - // info.epoch_id.to_string().as_str(), - // info.rng_seed.to_string().as_str(), - // info.tags.join(",").as_str(), - // info.summary.unwrap_or("".to_string()).as_str(), - // ] - // }) - // .collect(); - // // ); - // } + fn show_as_table(list: Vec) + where + Self: std::marker::Sized, + { + cli_table::print_stdout(list).unwrap(); + } fn as_log(&self) -> String { format!("{}", self) @@ -389,8 +168,8 @@ impl Default for EpochInfo { Self { epoch_id: epoch_struct::EpochId::new(0), rng_seed: 0, - tags: Vec::new(), - summary: None, + tags: TagList::new(), + summary: String::new(), } } } @@ -420,10 +199,12 @@ impl EpochInfo { } /// Thin type to handle EpochIds -#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +#[derive( + Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Display, +)] +#[display("{id}")] pub struct EpochId { - /// The underlying numeric value. A value of `0` is never used – - /// epoch IDs start at 1. + /// The underlying numeric value. pub id: u64, } @@ -435,12 +216,6 @@ impl FromStr for EpochId { } } -impl std::fmt::Display for EpochId { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{}", self.id) - } -} - impl EpochId { /// Creates a new `EpochId` from a numeric value. pub fn new(id: u64) -> Self { @@ -461,15 +236,6 @@ impl std::ops::Deref for EpochId { } } -impl ConfigWritable for EpochConfig { - fn save_path(&self) -> String { - MAIN_NAME.to_string() - } - - fn save_folder(&self) -> String { - ".".to_string() - } -} impl ConfigWritable for EpochInfo { fn save_path(&self) -> String { format!("{}/{}/{}", SUBFOLDER_NAMING, self.epoch_id, SUB_NAME) diff --git a/lib_efo/src/epoch_struct/epoch_config.rs b/lib_efo/src/epoch_struct/epoch_config.rs new file mode 100644 index 0000000..6996153 --- /dev/null +++ b/lib_efo/src/epoch_struct/epoch_config.rs @@ -0,0 +1,256 @@ +//! Module containing all the EpochConfig functions + +use std::{ + collections::HashMap, + fs::{read_to_string, remove_dir_all}, + path::Path, +}; + +use serde::{Deserialize, Serialize}; + +use crate::{ + epoch_struct::{ + ConfigWritable, EpochId, EpochIdentifier, EpochInfo, MAIN_NAME, SUBFOLDER_NAMING, SaveMode, + }, + epoch_traits::Prettiable, + error::EpochError, + io_err_with_help, +}; + +/// The file written to *.epochconfig* that tells the CLI which +/// epoch folder is the “current” one. +/// +/// Only the minimal information needed for fast switches is stored: +/// * the numeric identifier of the selected epoch, +/// * a list of human‑readable tags, +/// * the absolute path to the epoch’s directory. +/// +/// No world or event data lives here – it is purely a lightweight pointer. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct EpochConfig { + /// The epoch ID that the binary should consider “current”. + pub epoch_id: EpochId, + + /// Optional human‑friendly tags (e.g. `"winter‑B"`, `"post‑war"`). + pub tags: HashMap, + // TODO[6]: Can become important + // #[serde(skip)] + // /// Absolute path to `epoch//`. + // pub path: PathBuf, + /// A hashmap containing the name of all existing epochs, only loaded in memory if used + #[serde(skip)] + pub list_existing_epochs: HashMap>, +} + +impl Default for EpochConfig { + /// Create an empty config, mainly for initialisation + fn default() -> Self { + EpochConfig { + epoch_id: EpochId::new(0), + tags: HashMap::new(), + list_existing_epochs: HashMap::new(), + } + } +} + +impl EpochConfig { + /// Create a new config from an existig path + pub fn new_from_path(_path: Option<&Path>) -> Result { + let path = Path::new(MAIN_NAME); + + if path.is_file() { + // TODO[6]: write a trait for this + let config: EpochConfig = serde_json::from_str(&io_err_with_help!( + read_to_string(path), + "Reading config from path {:?}", + path + )?) + .map_err(|e| EpochError::Serde { + source: e, + file_name: path.to_string_lossy().to_string(), + help: None, + })?; + Ok(config.initialize()?) + } else { + Err(EpochError::MainFolderInvalid( + EpochConfig::default().save_folder(), + )) + } + } + + /// Initialize the epoch more in depth + pub(crate) fn initialize(mut self) -> Result { + let path = EpochConfig::default().save_subfolder(); + let path = io_err_with_help!(Path::new(&path).read_dir(), "Reading initial folder {path}")?; + // let mut valid_folders = HashMap::new(); + for elt in path { + let elt = io_err_with_help!(elt, "Opening file in main config folder")?; + if io_err_with_help!(elt.file_type(), "Determining file type of {:?}", elt)?.is_dir() { + let id = elt.file_name().to_string_lossy().parse::(); + // TODO: Logging + // println!("Initialized {:?}", id); + self.list_existing_epochs.insert(id.unwrap(), None); + } + } + Ok(self) + } + + /// Loads the metadata for an epoch from disk into the in‑memory cache. + /// + /// The epoch identified by `epoch_id` must exist in `list_existing_epochs`. + /// The JSON file on disk is read, deserialized into an `EpochInfo`, and + /// stored in the map. Any existing value for that epoch is overwritten. + /// + /// # Returns + /// * `Ok(())` when the epoch was successfully read and cached. + /// * `Err(EpochError::EpochNotFound(..))` if the epoch is not present in the + /// internal map. + /// * `Err(EpochError::Serde { .. })` if the JSON file could not be parsed. + /// * `Err(EpochError::Io { .. })` if the file could not be read. + pub fn try_load(&mut self, epoch_id: &EpochId) -> Result<(), EpochError> { + // Preload the epoch + let value = self + .list_existing_epochs + .get_mut(epoch_id) + .ok_or(EpochError::EpochNotFound(format!("{epoch_id}")))?; + + // Create a mock epoch + let path = EpochInfo::with_id(epoch_id).save_path(); + let read_to_string = io_err_with_help!(read_to_string(&path), "Reading {:?}", path); + + // Try to load + let maybe_epoch: EpochInfo = + serde_json::from_str(&read_to_string?).map_err(|e| EpochError::Serde { + source: e, + file_name: path.to_string(), + help: None, + })?; + + // Overwrite the value + *value = Some(maybe_epoch); + Ok(()) + } + + /// Retrieves the internal epoch ID for a given identifier. + /// + /// The identifier can be either a *tag* string (`EpochIdentifier::Tag`) or an + /// explicit epoch ID (`EpochIdentifier::Id`). + /// * When a tag is supplied the function looks up the corresponding epoch ID in + /// the `tags` map. + /// * When an ID is supplied it verifies that an epoch with that ID exists in + /// `list_existing_epochs` and returns it. + /// + /// # Returns + /// * `Ok(epoch_id)` when the identifier is successfully resolved. + /// * `Err(EpochError::AmbiguousTag(tag))` if a supplied tag does not exist. + /// * `Err(EpochError::EpochFolderMissing(id, path))` if an ID does not have an + /// associated epoch folder. + pub fn get(&self, id: &EpochIdentifier) -> Result { + match id { + EpochIdentifier::Tag(s) => self + .tags + .get(s) + .copied() + .ok_or(EpochError::AmbiguousTag(s.to_string())), + EpochIdentifier::Id(epoch_id) => self + .list_existing_epochs + .contains_key(epoch_id) + .then_some(epoch_id) + .ok_or(EpochError::EpochFolderMissing( + *epoch_id, + EpochConfig::default().save_folder().into(), + )) + .copied(), + } + } + + /// Return the name of the subfolder used to save this structure + pub(crate) fn save_subfolder(&self) -> String { + format!("{}/", SUBFOLDER_NAMING) + } + + /// Tries to delete an entire epoch folder by Id + // TODO[9]: Create a delete_ids taking an iterator for added performance on huge deletions + pub fn delete_id(&mut self, id: EpochId) -> Result<(), EpochError> { + if !self.list_existing_epochs.contains_key(&id) { + println!( + "The given epoch {} doesn't exists and it's deletion was skipped", + id + ) + } + io_err_with_help!( + remove_dir_all(EpochInfo::with_id(&id).save_folder()), + "Removing the epoch {}", + id + )?; + self.list_existing_epochs.remove(&id); + self.tags.retain(|_k, v| *v != id); + self.save_with_context("Saving after delete_id", &SaveMode::Erase)?; + Ok(()) + } + + /// Compute the next epoch, by defering the work to the Epochinfo -> World + /// Return the id of the next (and now present) epoch + pub fn compute_next(&mut self) -> Result { + // unimplemented!() + // TODO[1]: Implement this + print!("DEBUG LINE: COMPUTING NEXT EPOCH"); + // New fake epoch + Ok(EpochInfo::with_id(&self.epoch_id.next())) + } + + /// Insert the given epoch and save it + pub fn insert_and_save( + &mut self, + new_epoch: EpochInfo, + save_mode: &SaveMode, + ) -> Result<(), EpochError> { + if self.list_existing_epochs.contains_key(&new_epoch.epoch_id) { + return Err(EpochError::EpochAlreadyExists(new_epoch.epoch_id)); + } + + new_epoch.create_subfolders()?; + new_epoch.save_with_context("Saving new epoch", save_mode)?; + + // Add the epoch to the list of epochs, not doing so will still have it added + // at the next iteration since the command always parse the files to determine it's state rater that the list + // not doing so would likely create errors if insert is used before another command + let new_id = new_epoch.epoch_id; + self.list_existing_epochs.insert(new_id, Some(new_epoch)); + self.epoch_id = new_id; + self.save_with_context("Saving after insert_and_save", &SaveMode::Erase)?; + Ok(()) + } + + /// Loads into memory all elements to show them as log + pub fn log_elements(&mut self, list_ids: &[EpochId]) -> Result<(), EpochError> { + let mut items_to_log = Vec::with_capacity(list_ids.len()); + for id in list_ids { + self.try_load(id)?; + } + for id in list_ids { + if let Some(info) = self + .list_existing_epochs + .get(id) + .ok_or(EpochError::EpochNotFound(id.to_string()))? + { + items_to_log.push(info); + } + } + // items_to_log[0].as_log() + for item in items_to_log { + item.show_as_log(); + } + Ok(()) + } +} + +impl ConfigWritable for EpochConfig { + fn save_path(&self) -> String { + MAIN_NAME.to_string() + } + + fn save_folder(&self) -> String { + ".".to_string() + } +} diff --git a/lib_efo/src/epoch_traits.rs b/lib_efo/src/epoch_traits.rs index ade1775..124ccba 100644 --- a/lib_efo/src/epoch_traits.rs +++ b/lib_efo/src/epoch_traits.rs @@ -21,7 +21,7 @@ pub trait Nextable {} pub trait Prettiable { // TODO: Doc /// Show many as a table - fn show_as_table(list: &[Self]) + fn show_as_table(list: Vec) where Self: std::marker::Sized, { -- 2.45.1 From c5563c326049fcfb62a9fe4950d9adb61fe23b19 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sat, 29 Nov 2025 01:05:36 +0100 Subject: [PATCH 06/22] Refactors epoch_info --- bin_efo/src/commands/epoch.rs | 5 +- bin_efo/src/commands/init.rs | 7 +- lib_efo/src/epoch_struct.rs | 142 ++--------------------- lib_efo/src/epoch_struct/epoch_config.rs | 43 +++++-- lib_efo/src/epoch_struct/epoch_info.rs | 106 +++++++++++++++++ lib_efo/src/epoch_traits.rs | 43 +++++++ 6 files changed, 198 insertions(+), 148 deletions(-) create mode 100644 lib_efo/src/epoch_struct/epoch_info.rs diff --git a/bin_efo/src/commands/epoch.rs b/bin_efo/src/commands/epoch.rs index 34da5a6..f358e20 100644 --- a/bin_efo/src/commands/epoch.rs +++ b/bin_efo/src/commands/epoch.rs @@ -5,10 +5,7 @@ #![warn(missing_docs, clippy::missing_docs_in_private_items)] use crate::error::AppError; -use lib_efo::{ - epoch_struct::{ConfigWritable, EpochConfig}, - error::EpochError, -}; +use lib_efo::{epoch_struct::EpochConfig, epoch_traits::ConfigWritable, error::EpochError}; pub mod cli_epoch; diff --git a/bin_efo/src/commands/init.rs b/bin_efo/src/commands/init.rs index de03a71..6717cb3 100644 --- a/bin_efo/src/commands/init.rs +++ b/bin_efo/src/commands/init.rs @@ -12,8 +12,11 @@ #![warn(missing_docs, clippy::missing_docs_in_private_items)] use clap::Args; -use lib_efo::epoch_struct::{ConfigWritable, EpochConfig, EpochInfo}; -use lib_efo::error::EpochError; +use lib_efo::{ + epoch_struct::{EpochConfig, EpochInfo}, + epoch_traits::ConfigWritable, + error::EpochError, +}; use std::fs::read_dir; use crate::error::AppError; diff --git a/lib_efo/src/epoch_struct.rs b/lib_efo/src/epoch_struct.rs index 3a9d2e9..d197a85 100644 --- a/lib_efo/src/epoch_struct.rs +++ b/lib_efo/src/epoch_struct.rs @@ -20,19 +20,19 @@ //! `HEAD` pointer. #![warn(missing_docs, clippy::missing_docs_in_private_items)] use clap::error::ErrorKind; -use cli_table::Table; use derive_more::Display; use serde::{Deserialize, Serialize}; use std::{ - fs::{File, create_dir_all}, + ops::{Deref, DerefMut}, str::FromStr, }; -use std::{ - io::Write, - ops::{Deref, DerefMut}, -}; -use crate::{epoch_struct, epoch_traits::Prettiable, error::EpochError, io_err_with_help}; +use crate::error::EpochError; +pub mod epoch_config; +pub use epoch_config::EpochConfig; + +pub mod epoch_info; +pub use epoch_info::EpochInfo; // TODO[5]: Try to load from a config and have it inserted as a backup /// The subfolder naming convention @@ -42,83 +42,6 @@ static MAIN_NAME: &str = ".epoch"; /// The subname of the epochinfo static SUB_NAME: &str = ".epochinfo"; -pub mod epoch_config; -pub use epoch_config::EpochConfig; - -/// Trait representing a serialisable / writable config -pub trait ConfigWritable: Serialize { - /// The full path indicating where to save the config - fn save_path(&self) -> String; - - /// The folder where to save the file to save the config - fn save_folder(&self) -> String; - - /// Have the config as JSON - fn as_json(&self, action: String) -> Result { - serde_json::to_string_pretty(self).map_err(|e| EpochError::Serde { - source: e, - file_name: action, - help: None, - }) - } - - /// Save the config into it's nominal path - /// - /// This command will NOT create all subdirectories - fn save_with_context( - &self, - // Very unsure about this versus a macro - action_description: &str, - do_not_erase: &SaveMode, - // advice: Option, - ) -> Result<(), EpochError> { - let mut f = match *do_not_erase { - SaveMode::Erase => File::create(self.save_path()), - SaveMode::DoNotErase => File::create_new(self.save_path()), - } - .map_err(|e| EpochError::ConfigCreation(self.save_path(), e))?; - write!(f, "{}", self.as_json(action_description.to_owned())?) - .map_err(EpochError::ConfigWrite)?; - Ok(()) - } -} - -/// The metadata file stored inside each epoch directory -/// (`epoch//.epochinfo`). -/// -/// It contains only the information that is needed for the engine to -/// reconstruct the state *of that particular epoch* (seed, selected -/// events, parent link, etc.). The full world data is kept in -/// separate storage (e.g. `world.json`). -#[derive(Debug, Clone, Serialize, Deserialize, Display)] -#[display( - "Epoch ({epoch_id:>5}) | seed ({rng_seed:<10}) | tags ({tags:<10}) | summary ({summary:<20})" -)] -#[derive(Table)] -pub struct EpochInfo { - /// The ID of this epoch – should match the directory name. - #[table(title = "ID")] - pub epoch_id: EpochId, - - /// RNG seed that was used to generate randomised data for - /// this epoch. Keeping it in the file guarantees repeatable - /// behaviour when replaying the same epoch. - #[table(title = "Seed")] - pub rng_seed: u64, - - // /// List of event IDs that were accepted for this epoch. - // /// The engine uses this to replay the world from the - // /// parent epoch to the current one. - // pub selected_events: Vec, - /// Optional tags that help identify the epoch (e.g. `"Winter‑B"`). - #[table(title = "Tags")] - pub tags: TagList, - - /// Human‑readable description or summary, useful for the `log` command. - #[table(title = "Summary")] - pub summary: String, -} - /// A lightweight wrapper around a list of tags. /// /// The wrapper exists mainly to give the collection a semantic type @@ -150,30 +73,6 @@ impl DerefMut for TagList { } } -impl Prettiable for EpochInfo { - fn show_as_table(list: Vec) - where - Self: std::marker::Sized, - { - cli_table::print_stdout(list).unwrap(); - } - - fn as_log(&self) -> String { - format!("{}", self) - } -} - -impl Default for EpochInfo { - fn default() -> Self { - Self { - epoch_id: epoch_struct::EpochId::new(0), - rng_seed: 0, - tags: TagList::new(), - summary: String::new(), - } - } -} - /// Which save mode to use #[allow(missing_docs)] pub enum SaveMode { @@ -181,23 +80,6 @@ pub enum SaveMode { Erase, } -impl EpochInfo { - /// Create all subfolders as needed - /// - /// This command can be safely used even if the folder already exists - pub fn create_subfolders(&self) -> Result<(), EpochError> { - io_err_with_help!(create_dir_all(self.save_folder()), "Creating subfolders") - } - - /// Create an epoch with only an Id, please note that this function doesn't load the epoch at all - fn with_id(epoch_id: &EpochId) -> Self { - Self { - epoch_id: *epoch_id, - ..Default::default() - } - } -} - /// Thin type to handle EpochIds #[derive( Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Display, @@ -236,16 +118,6 @@ impl std::ops::Deref for EpochId { } } -impl ConfigWritable for EpochInfo { - fn save_path(&self) -> String { - format!("{}/{}/{}", SUBFOLDER_NAMING, self.epoch_id, SUB_NAME) - } - - fn save_folder(&self) -> String { - format!("{}/{}/", SUBFOLDER_NAMING, self.epoch_id) - } -} - /// A flexible identifier for *any* epoch – the world may be /// addressed by a numeric ID or by a friendly tag (e.g. `"winter‑b"`). /// diff --git a/lib_efo/src/epoch_struct/epoch_config.rs b/lib_efo/src/epoch_struct/epoch_config.rs index 6996153..1c88767 100644 --- a/lib_efo/src/epoch_struct/epoch_config.rs +++ b/lib_efo/src/epoch_struct/epoch_config.rs @@ -1,5 +1,16 @@ -//! Module containing all the EpochConfig functions +//! Management of the *current‑epoch* configuration. +//! +//! The configuration is stored in a file named `.epoch` and contains only +//! the lightweight information needed for the CLI to switch between epochs +//! quickly: +//! * the numeric ID of the current epoch, +//! * a map of human‑friendly tags to epoch IDs, +//! * a map of known epoch IDs to unloaded metadata (`EpochInfo`). +//! +//! The world data and all event logs belong to the individual epoch +//! directories and are **not** part of this file. +use crate::epoch_traits::ConfigWritable; use std::{ collections::HashMap, fs::{read_to_string, remove_dir_all}, @@ -10,7 +21,7 @@ use serde::{Deserialize, Serialize}; use crate::{ epoch_struct::{ - ConfigWritable, EpochId, EpochIdentifier, EpochInfo, MAIN_NAME, SUBFOLDER_NAMING, SaveMode, + EpochId, EpochIdentifier, MAIN_NAME, SUBFOLDER_NAMING, SaveMode, epoch_info::EpochInfo, }, epoch_traits::Prettiable, error::EpochError, @@ -169,7 +180,11 @@ impl EpochConfig { format!("{}/", SUBFOLDER_NAMING) } - /// Tries to delete an entire epoch folder by Id + /// Delete an entire epoch folder by its ID. + /// + /// The function removes the directory, deletes all references to the + /// epoch from `list_existing_epochs` and `tags`, and then writes the + /// updated configuration to disk. // TODO[9]: Create a delete_ids taking an iterator for added performance on huge deletions pub fn delete_id(&mut self, id: EpochId) -> Result<(), EpochError> { if !self.list_existing_epochs.contains_key(&id) { @@ -189,8 +204,11 @@ impl EpochConfig { Ok(()) } - /// Compute the next epoch, by defering the work to the Epochinfo -> World - /// Return the id of the next (and now present) epoch + /// Compute the next epoch. + /// + /// Currently this function is a placeholder that creates a new epoch + /// with the ID immediately following the current one. The actual logic + /// is deferred to the `EpochInfo -> World` subsystem. pub fn compute_next(&mut self) -> Result { // unimplemented!() // TODO[1]: Implement this @@ -199,7 +217,15 @@ impl EpochConfig { Ok(EpochInfo::with_id(&self.epoch_id.next())) } - /// Insert the given epoch and save it + /// Insert a new epoch into the configuration and persist it. + /// + /// The function creates the epoch’s directory, writes its metadata, + /// updates the internal maps, and finally writes the updated + /// configuration to disk. + /// + /// # Returns + /// * `Ok(())` – the epoch was added and the configuration was saved. + /// * `Err(EpochError::EpochAlreadyExists(..))` if an epoch with the same ID already exists. pub fn insert_and_save( &mut self, new_epoch: EpochInfo, @@ -222,7 +248,10 @@ impl EpochConfig { Ok(()) } - /// Loads into memory all elements to show them as log + /// Load and display the metadata for a list of epoch IDs. + /// + /// The function first ensures that each requested epoch’s metadata is + /// loaded into memory, then prints a formatted log for each one. pub fn log_elements(&mut self, list_ids: &[EpochId]) -> Result<(), EpochError> { let mut items_to_log = Vec::with_capacity(list_ids.len()); for id in list_ids { diff --git a/lib_efo/src/epoch_struct/epoch_info.rs b/lib_efo/src/epoch_struct/epoch_info.rs new file mode 100644 index 0000000..e963438 --- /dev/null +++ b/lib_efo/src/epoch_struct/epoch_info.rs @@ -0,0 +1,106 @@ +//! Metadata management for individual epochs. +//! +//! The `EpochInfo` struct holds all information that the engine needs to +//! reconstruct a particular epoch. +//! It is persisted to `epoch//.epochinfo`. The file contains the epoch ID, the RNG +//! seed that produced the world, any optional tags, and a human‑readable +//! summary. World data itself is stored separately (e.g. in `world.json`). + +use cli_table::Table; +use derive_more::Display; +use serde::{Deserialize, Serialize}; +use std::fs::create_dir_all; + +use crate::{ + epoch_struct::{self, EpochId, SUB_NAME, SUBFOLDER_NAMING, TagList}, + epoch_traits::{ConfigWritable, Prettiable}, + error::EpochError, + io_err_with_help, +}; + +/// The metadata file stored inside each epoch directory +/// (`epoch//.epochinfo`). +/// +/// It contains only the information that is needed for the engine to +/// reconstruct the state *of that particular epoch* (seed, selected +/// events, parent link, etc.). The full world data is kept in +/// separate storage (e.g. `world.json`). +#[derive(Debug, Clone, Serialize, Deserialize, Display)] +#[display( + "Epoch ({epoch_id:>5}) | seed ({rng_seed:<10}) | tags ({tags:<10}) | summary ({summary:<20})" +)] +#[derive(Table)] +pub struct EpochInfo { + /// The ID of this epoch – should match the directory name. + #[table(title = "ID")] + pub epoch_id: EpochId, + + /// RNG seed that was used to generate randomised data for + /// this epoch. Keeping it in the file guarantees repeatable + /// behaviour when replaying the same epoch. + #[table(title = "Seed")] + pub rng_seed: u64, + + // /// List of event IDs that were accepted for this epoch. + // /// The engine uses this to replay the world from the + // /// parent epoch to the current one. + // pub selected_events: Vec, + /// Optional tags that help identify the epoch (e.g. `"Winter‑B"`). + #[table(title = "Tags")] + pub tags: TagList, + + /// Human‑readable description or summary, useful for the `log` command. + #[table(title = "Summary")] + pub summary: String, +} + +impl Prettiable for EpochInfo { + fn show_as_table(list: Vec) + where + Self: std::marker::Sized, + { + cli_table::print_stdout(list).unwrap(); + } + + fn as_log(&self) -> String { + format!("{}", self) + } +} + +impl Default for EpochInfo { + fn default() -> Self { + Self { + epoch_id: epoch_struct::EpochId::new(0), + rng_seed: 0, + tags: TagList::new(), + summary: String::new(), + } + } +} + +impl EpochInfo { + /// Create all subfolders as needed + /// + /// This command can be safely used even if the folder already exists + pub fn create_subfolders(&self) -> Result<(), EpochError> { + io_err_with_help!(create_dir_all(self.save_folder()), "Creating subfolders") + } + + /// Create an epoch with only an Id, please note that this function doesn't load the epoch at all + pub(crate) fn with_id(epoch_id: &EpochId) -> Self { + Self { + epoch_id: *epoch_id, + ..Default::default() + } + } +} + +impl ConfigWritable for EpochInfo { + fn save_path(&self) -> String { + format!("{}/{}/{}", SUBFOLDER_NAMING, self.epoch_id, SUB_NAME) + } + + fn save_folder(&self) -> String { + format!("{}/{}/", SUBFOLDER_NAMING, self.epoch_id) + } +} diff --git a/lib_efo/src/epoch_traits.rs b/lib_efo/src/epoch_traits.rs index 124ccba..a6e6582 100644 --- a/lib_efo/src/epoch_traits.rs +++ b/lib_efo/src/epoch_traits.rs @@ -5,6 +5,11 @@ //! common to many of the library’s element types. #![warn(clippy::missing_docs_in_private_items)] +use serde::Serialize; +use std::{fs::File, io::Write}; + +use crate::{epoch_struct::SaveMode, error::EpochError}; + /// Elements that can be compared with another instance to produce a diff. pub trait Diffable {} @@ -38,3 +43,41 @@ pub trait Prettiable { /// Convert the struct into a pretty log fn as_log(&self) -> String; } + +/// Trait representing a serialisable / writable config +pub trait ConfigWritable: Serialize { + /// The full path indicating where to save the config + fn save_path(&self) -> String; + + /// The folder where to save the file to save the config + fn save_folder(&self) -> String; + + /// Have the config as JSON + fn as_json(&self, action: String) -> Result { + serde_json::to_string_pretty(self).map_err(|e| EpochError::Serde { + source: e, + file_name: action, + help: None, + }) + } + + /// Save the config into it's nominal path + /// + /// This command will NOT create all subdirectories + fn save_with_context( + &self, + // Very unsure about this versus a macro + action_description: &str, + do_not_erase: &SaveMode, + // advice: Option, + ) -> Result<(), EpochError> { + let mut f = match *do_not_erase { + SaveMode::Erase => File::create(self.save_path()), + SaveMode::DoNotErase => File::create_new(self.save_path()), + } + .map_err(|e| EpochError::ConfigCreation(self.save_path(), e))?; + write!(f, "{}", self.as_json(action_description.to_owned())?) + .map_err(EpochError::ConfigWrite)?; + Ok(()) + } +} -- 2.45.1 From 9153ffb1d1f5852f7b8f06c8b529bbc310901b74 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sat, 29 Nov 2025 01:26:12 +0100 Subject: [PATCH 07/22] Adds logging --- Cargo.lock | 110 +++++++++++++++++++++++ Cargo.toml | 2 + bin_efo/Cargo.toml | 2 + bin_efo/src/commands/epoch.rs | 10 ++- bin_efo/src/main.rs | 2 + lib_efo/Cargo.toml | 2 + lib_efo/src/epoch_struct/epoch_config.rs | 30 +++---- lib_efo/src/epoch_struct/epoch_info.rs | 9 +- lib_efo/src/epoch_traits.rs | 5 +- 9 files changed, 143 insertions(+), 29 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index fb51125..8b824cc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -17,6 +17,15 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" +[[package]] +name = "aho-corasick" +version = "1.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301" +dependencies = [ + "memchr", +] + [[package]] name = "anstream" version = "0.6.21" @@ -96,7 +105,9 @@ name = "bin_efo" version = "0.1.0" dependencies = [ "clap", + "env_logger", "lib_efo", + "log", "miette", "serde", "serde_json", @@ -226,6 +237,29 @@ dependencies = [ "unicode-xid", ] +[[package]] +name = "env_filter" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bf3c259d255ca70051b30e2e95b5446cdb8949ac4cd22c0d7fd634d89f568e2" +dependencies = [ + "log", + "regex", +] + +[[package]] +name = "env_logger" +version = "0.11.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c863f0904021b108aa8b2f55046443e6b1ebde8fd4a15c399893aae4fa069f" +dependencies = [ + "anstream", + "anstyle", + "env_filter", + "jiff", + "log", +] + [[package]] name = "errno" version = "0.3.14" @@ -266,6 +300,30 @@ version = "1.0.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4a5f13b858c8d314ee3e8f639011f7ccefe71f97f96e50151fb991f267928e2c" +[[package]] +name = "jiff" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "49cce2b81f2098e7e3efc35bc2e0a6b7abec9d34128283d7a26fa8f32a6dbb35" +dependencies = [ + "jiff-static", + "log", + "portable-atomic", + "portable-atomic-util", + "serde_core", +] + +[[package]] +name = "jiff-static" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "980af8b43c3ad5d8d349ace167ec8170839f753a42d233ba19e08afe1850fa69" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + [[package]] name = "lib_efo" version = "0.1.0" @@ -273,6 +331,8 @@ dependencies = [ "clap", "cli-table", "derive_more", + "env_logger", + "log", "miette", "serde", "serde_json", @@ -291,6 +351,12 @@ version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "df1d3c3b53da64cf5760482273a98e575c651a67eec7f77df96b5b642de8f039" +[[package]] +name = "log" +version = "0.4.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34080505efa8e45a4b816c349525ebe327ceaa8559756f0356cba97ef3bf7432" + [[package]] name = "memchr" version = "2.7.6" @@ -357,6 +423,21 @@ version = "4.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9c6901729fa79e91a0913333229e9ca5dc725089d1c363b2f4b4760709dc4a52" +[[package]] +name = "portable-atomic" +version = "1.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f84267b20a16ea918e43c6a88433c2d54fa145c92a811b5b047ccbe153674483" + +[[package]] +name = "portable-atomic-util" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8a2f0d8d040d7848a709caf78912debcc3f33ee4b3cac47d73d1e1069e83507" +dependencies = [ + "portable-atomic", +] + [[package]] name = "proc-macro2" version = "1.0.103" @@ -375,6 +456,35 @@ dependencies = [ "proc-macro2", ] +[[package]] +name = "regex" +version = "1.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "843bc0191f75f3e22651ae5f1e72939ab2f72a4bc30fa80a066bd66edefc24d4" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5276caf25ac86c8d810222b3dbb938e512c55c6831a10f3e6ed1c93b84041f1c" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a2d987857b319362043e95f5353c0535c1f58eec5336fdfcf626430af7def58" + [[package]] name = "rustc-demangle" version = "0.1.26" diff --git a/Cargo.toml b/Cargo.toml index 12fd715..839f255 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -8,3 +8,5 @@ clap = { version = "4.5.51", features = ["derive"] } thiserror = "2.0.17" serde_json = "1.0.145" miette = { version = "7.6.0", features = ["fancy"] } +env_logger = "0.11.8" +log = "0.4.28" diff --git a/bin_efo/Cargo.toml b/bin_efo/Cargo.toml index d381520..c239761 100644 --- a/bin_efo/Cargo.toml +++ b/bin_efo/Cargo.toml @@ -10,3 +10,5 @@ clap = {workspace = true} thiserror = {workspace = true} serde_json = {workspace = true} miette = {workspace = true} +env_logger = {workspace = true} +log = {workspace = true} diff --git a/bin_efo/src/commands/epoch.rs b/bin_efo/src/commands/epoch.rs index f358e20..7afdc3f 100644 --- a/bin_efo/src/commands/epoch.rs +++ b/bin_efo/src/commands/epoch.rs @@ -6,6 +6,7 @@ use crate::error::AppError; use lib_efo::{epoch_struct::EpochConfig, epoch_traits::ConfigWritable, error::EpochError}; +use log::{debug, info}; pub mod cli_epoch; @@ -14,7 +15,7 @@ pub mod cli_epoch; pub fn handle_cmd(cmd: cli_epoch::EpochCmd) -> Result<(), AppError> { let mut main_epoch = EpochConfig::new_from_path(None)?; // // TODO[2]: Remove this debug - // println!("The main epoch is {:#?}", main_epoch); + debug!("The main epoch befor any action is {:#?}", main_epoch); match cmd { cli_epoch::EpochCmd::Log(args) => handle_log(args, &mut main_epoch), cli_epoch::EpochCmd::Switch(args) => handle_switch(args, &mut main_epoch), @@ -25,8 +26,7 @@ pub fn handle_cmd(cmd: cli_epoch::EpochCmd) -> Result<(), AppError> { cli_epoch::EpochCmd::Fsck(args) => handle_fsck(args, &mut main_epoch), }?; - // // TODO[2]: Remove this debug - // println!("The main epoch is {:#?}", main_epoch); + info!("The main epoch after all actions is {:#?}", main_epoch); Ok(()) } @@ -38,6 +38,7 @@ fn handle_diff(args: cli_epoch::Diff) -> Result<(), AppError> { /// Show a log of all different epochs fn handle_log(args: cli_epoch::Log, main_epoch: &mut EpochConfig) -> Result<(), AppError> { + // TODO: Have a special centralized message dispacher println!("Epoch log (most recent first):"); let limit = args.limit; let start_id = &main_epoch.epoch_id; @@ -51,7 +52,6 @@ fn handle_log(args: cli_epoch::Log, main_epoch: &mut EpochConfig) -> Result<(), .copied() .collect::>(); - // TODO[8]: Consider other ways to log than one element at a time main_epoch.log_elements(&list_id)?; Ok(()) @@ -70,6 +70,7 @@ fn handle_switch(args: cli_epoch::Switch, main_epoch: &mut EpochConfig) -> Resul main_epoch.try_load(&target)?; main_epoch.epoch_id = target; + // TODO: Have a special centralized message dispacher println!("Switched to epoch {:?}", target); main_epoch.save_with_context( "Saving modified epoch config", @@ -140,6 +141,7 @@ fn handle_reset(args: cli_epoch::Reset, main_epoch: &mut EpochConfig) -> Result< { main_epoch.delete_id(id)? } + // TODO: Have a special centralized message dispacher println!("All future events deleted – back to epoch {current_id}",); Ok(()) } diff --git a/bin_efo/src/main.rs b/bin_efo/src/main.rs index 21fc81c..632e51d 100644 --- a/bin_efo/src/main.rs +++ b/bin_efo/src/main.rs @@ -69,6 +69,7 @@ enum TopLevelCmd { /// sub‑command. Errors returned by the sub‑command handlers are printed /// to stdout and returned as a `miette::Result<()>`. fn main() -> miette::Result<()> { + env_logger::init(); let cli = Cli::parse(); if let Err(e) = exec_dispatch(cli) { @@ -95,6 +96,7 @@ fn exec_dispatch(cli: Cli) -> Result<(), AppError> { match cli.command { TopLevelCmd::Init(cmd) => { commands::init::init(&cmd)?; + // TODO: Have a special centralized message dispacher println!("The folder was initialized as an epoch folder") } TopLevelCmd::Epoch(cmd) => { diff --git a/lib_efo/Cargo.toml b/lib_efo/Cargo.toml index 35184e2..8ab53cb 100644 --- a/lib_efo/Cargo.toml +++ b/lib_efo/Cargo.toml @@ -9,5 +9,7 @@ serde = {workspace = true} thiserror = {workspace = true} clap = {workspace = true} miette = {workspace = true} +env_logger = {workspace = true} +log = {workspace = true} derive_more = { version = "2.0.1", features = ["display"] } cli-table = "0.5.0" diff --git a/lib_efo/src/epoch_struct/epoch_config.rs b/lib_efo/src/epoch_struct/epoch_config.rs index 1c88767..2f6321c 100644 --- a/lib_efo/src/epoch_struct/epoch_config.rs +++ b/lib_efo/src/epoch_struct/epoch_config.rs @@ -17,6 +17,7 @@ use std::{ path::Path, }; +use log::info; use serde::{Deserialize, Serialize}; use crate::{ @@ -98,8 +99,7 @@ impl EpochConfig { let elt = io_err_with_help!(elt, "Opening file in main config folder")?; if io_err_with_help!(elt.file_type(), "Determining file type of {:?}", elt)?.is_dir() { let id = elt.file_name().to_string_lossy().parse::(); - // TODO: Logging - // println!("Initialized {:?}", id); + info!("Initialized {:?}", id); self.list_existing_epochs.insert(id.unwrap(), None); } } @@ -192,15 +192,16 @@ impl EpochConfig { "The given epoch {} doesn't exists and it's deletion was skipped", id ) + } else { + io_err_with_help!( + remove_dir_all(EpochInfo::with_id(&id).save_folder()), + "Removing the epoch {}", + id + )?; + self.list_existing_epochs.remove(&id); + self.tags.retain(|_k, v| *v != id); + self.save_with_context("Saving after delete_id", &SaveMode::Erase)?; } - io_err_with_help!( - remove_dir_all(EpochInfo::with_id(&id).save_folder()), - "Removing the epoch {}", - id - )?; - self.list_existing_epochs.remove(&id); - self.tags.retain(|_k, v| *v != id); - self.save_with_context("Saving after delete_id", &SaveMode::Erase)?; Ok(()) } @@ -212,7 +213,7 @@ impl EpochConfig { pub fn compute_next(&mut self) -> Result { // unimplemented!() // TODO[1]: Implement this - print!("DEBUG LINE: COMPUTING NEXT EPOCH"); + println!("DEBUG LINE: COMPUTING NEXT EPOCH"); // New fake epoch Ok(EpochInfo::with_id(&self.epoch_id.next())) } @@ -254,9 +255,11 @@ impl EpochConfig { /// loaded into memory, then prints a formatted log for each one. pub fn log_elements(&mut self, list_ids: &[EpochId]) -> Result<(), EpochError> { let mut items_to_log = Vec::with_capacity(list_ids.len()); + // Tries to load all ids into memory for id in list_ids { self.try_load(id)?; } + // Makes a vector with all elements from the list of ids for id in list_ids { if let Some(info) = self .list_existing_epochs @@ -266,10 +269,7 @@ impl EpochConfig { items_to_log.push(info); } } - // items_to_log[0].as_log() - for item in items_to_log { - item.show_as_log(); - } + EpochInfo::show_as_table(items_to_log); Ok(()) } } diff --git a/lib_efo/src/epoch_struct/epoch_info.rs b/lib_efo/src/epoch_struct/epoch_info.rs index e963438..4191705 100644 --- a/lib_efo/src/epoch_struct/epoch_info.rs +++ b/lib_efo/src/epoch_struct/epoch_info.rs @@ -6,7 +6,7 @@ //! seed that produced the world, any optional tags, and a human‑readable //! summary. World data itself is stored separately (e.g. in `world.json`). -use cli_table::Table; +use cli_table::{Table, WithTitle}; use derive_more::Display; use serde::{Deserialize, Serialize}; use std::fs::create_dir_all; @@ -55,11 +55,8 @@ pub struct EpochInfo { } impl Prettiable for EpochInfo { - fn show_as_table(list: Vec) - where - Self: std::marker::Sized, - { - cli_table::print_stdout(list).unwrap(); + fn show_as_table(list: Vec<&Self>) { + cli_table::print_stdout(list.with_title()).unwrap(); } fn as_log(&self) -> String { diff --git a/lib_efo/src/epoch_traits.rs b/lib_efo/src/epoch_traits.rs index a6e6582..9510172 100644 --- a/lib_efo/src/epoch_traits.rs +++ b/lib_efo/src/epoch_traits.rs @@ -26,10 +26,7 @@ pub trait Nextable {} pub trait Prettiable { // TODO: Doc /// Show many as a table - fn show_as_table(list: Vec) - where - Self: std::marker::Sized, - { + fn show_as_table(list: Vec<&Self>) { list.iter().for_each(|e| { e.show_as_log(); }); -- 2.45.1 From 9174a79e9a6bbf968858eebd09892f5591ae9d57 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sat, 29 Nov 2025 02:56:21 +0100 Subject: [PATCH 08/22] Mostly doc & Tags & Summary --- Cargo.lock | 1 + Cargo.toml | 1 + bin_efo/Cargo.toml | 1 + bin_efo/src/commands/epoch.rs | 119 +++++++++++++++++------ bin_efo/src/commands/epoch/cli_epoch.rs | 13 ++- bin_efo/src/commands/init.rs | 7 +- bin_efo/src/main.rs | 11 +-- bin_efo/src/success.rs | 25 +++++ lib_efo/Cargo.toml | 2 +- lib_efo/src/epoch_struct/epoch_config.rs | 12 +-- lib_efo/src/epoch_struct/epoch_info.rs | 15 +-- lib_efo/src/epoch_traits.rs | 57 ++++++++--- lib_efo/src/lib.rs | 1 + lib_efo/src/utils.rs | 13 +-- 14 files changed, 199 insertions(+), 79 deletions(-) create mode 100644 bin_efo/src/success.rs diff --git a/Cargo.lock b/Cargo.lock index 8b824cc..a70b004 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -105,6 +105,7 @@ name = "bin_efo" version = "0.1.0" dependencies = [ "clap", + "derive_more", "env_logger", "lib_efo", "log", diff --git a/Cargo.toml b/Cargo.toml index 839f255..12f5a22 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,3 +10,4 @@ serde_json = "1.0.145" miette = { version = "7.6.0", features = ["fancy"] } env_logger = "0.11.8" log = "0.4.28" +derive_more = { version = "2.0.1", features = ["display"] } diff --git a/bin_efo/Cargo.toml b/bin_efo/Cargo.toml index c239761..9537697 100644 --- a/bin_efo/Cargo.toml +++ b/bin_efo/Cargo.toml @@ -12,3 +12,4 @@ serde_json = {workspace = true} miette = {workspace = true} env_logger = {workspace = true} log = {workspace = true} +derive_more = {workspace = true} diff --git a/bin_efo/src/commands/epoch.rs b/bin_efo/src/commands/epoch.rs index 7afdc3f..a860281 100644 --- a/bin_efo/src/commands/epoch.rs +++ b/bin_efo/src/commands/epoch.rs @@ -4,14 +4,41 @@ //! next epoch, and resetting future events. #![warn(missing_docs, clippy::missing_docs_in_private_items)] -use crate::error::AppError; -use lib_efo::{epoch_struct::EpochConfig, epoch_traits::ConfigWritable, error::EpochError}; +use crate::{ + error::AppError, + success::{SuccessMessages, display_success}, +}; +use lib_efo::{ + epoch_struct::{EpochConfig, EpochId}, + epoch_traits::ConfigWritable, + error::EpochError, +}; use log::{debug, info}; pub mod cli_epoch; /// **Public entry point used by `efo::main`** – dispatches to the real /// handler that lives in `crate::world::EpochManager`. +/// +/// # Arguments +/// * `cmd` – The command to execute. This is an enum that represents +/// one of the possible sub‑commands for the `epoch` feature. +/// +/// # Returns +/// * `Ok(())` on success. +/// * `Err(AppError)` if any step of the command handling fails. +/// +/// # Examples +/// ```no_run +/// // Create a command to switch to epoch 3. +/// let cmd = cli_epoch::EpochCmd::Switch(cli_epoch::Switch { target: 3 }); +/// // Execute the command. +/// let result = handle_cmd(cmd); +/// assert!(result.is_ok()); +/// ``` +/// +/// The function never panics under normal operation. All errors are +/// reported via the returned `Result`. pub fn handle_cmd(cmd: cli_epoch::EpochCmd) -> Result<(), AppError> { let mut main_epoch = EpochConfig::new_from_path(None)?; // // TODO[2]: Remove this debug @@ -24,58 +51,91 @@ pub fn handle_cmd(cmd: cli_epoch::EpochCmd) -> Result<(), AppError> { cli_epoch::EpochCmd::Diff(args) => handle_diff(args), cli_epoch::EpochCmd::Tag(args) => handle_taging(args, &mut main_epoch), cli_epoch::EpochCmd::Fsck(args) => handle_fsck(args, &mut main_epoch), + cli_epoch::EpochCmd::Summary(args) => handle_summary(args, &mut main_epoch), }?; info!("The main epoch after all actions is {:#?}", main_epoch); Ok(()) } -/// Show the diff between two epochs +/// Edits the summary for the current epoch. +/// +/// The function loads the epoch that is currently active in +/// `main_epoch`, then replaces its `summary` field with the value +/// supplied in `args.summary`. The epoch map in `main_epoch` is +/// modified in place. +/// +/// This helper is internal to the `epoch` sub‑command and is not part +/// of the public API. +fn handle_summary(args: cli_epoch::Summary, main_epoch: &mut EpochConfig) -> Result<(), AppError> { + let epoch_id = main_epoch.epoch_id; + main_epoch.try_load(&epoch_id)?; + #[allow(clippy::unwrap_used)] // The epoch_id must exists at this point + if let Some(epoch) = main_epoch.list_existing_epochs.get_mut(&epoch_id).unwrap() { + epoch.summary = args.summary.clone(); + epoch.save_with_context( + "Saving new summary", + &lib_efo::epoch_struct::SaveMode::Erase, + )?; + display_success(&SuccessMessages::ChangedSummary(epoch_id, args.summary)); + } + + Ok(()) +} + +/// Show a diff between two epochs. +/// +/// Currently unimplemented. The function is a placeholder until a +/// world‑level diff algorithm is available. +/// +/// This helper is internal to the `epoch` sub‑command and is not part +/// of the public API. fn handle_diff(args: cli_epoch::Diff) -> Result<(), AppError> { let _ = args; unimplemented!("Blocker: There is actually no way to diff the world yet") } -/// Show a log of all different epochs +/// Show a log of all epochs up to the current one. +/// +/// The function collects the identifiers of all epochs that are +/// less than or equal to the currently active epoch (`main_epoch.epoch_id`), +/// sorts them, and then asks the configuration to log the elements +/// up to the supplied limit. The log is written by the +/// underlying `EpochConfig::log_elements` implementation. +/// +/// This helper is internal to the `epoch` sub‑command. fn handle_log(args: cli_epoch::Log, main_epoch: &mut EpochConfig) -> Result<(), AppError> { - // TODO: Have a special centralized message dispacher - println!("Epoch log (most recent first):"); let limit = args.limit; let start_id = &main_epoch.epoch_id; - let list_id = main_epoch + let mut list_id: Vec = main_epoch .list_existing_epochs .iter() .filter(|(id, _)| id <= &start_id) - .take(limit) - .map(|(id, _)| id) - .copied() - .collect::>(); - - main_epoch.log_elements(&list_id)?; - + .map(|(id, _)| *id) + .collect(); + list_id.sort(); + main_epoch.log_elements(&list_id[..std::cmp::min(list_id.len(), limit)])?; Ok(()) } /// Switches the current epoch to the one specified by the user. /// -/// This updates the in‑memory configuration, reloads the target epoch, -/// updates the epoch identifier, and persists the changes. +/// The function loads the target epoch, updates the epoch identifier +/// in the configuration, and persists the change. It also prints a +/// success message via `display_success`. /// -/// # Arguments -/// * `args` – `cli_epoch::Switch` containing the target epoch identifier. -/// * `main_epoch` – mutable reference to the current `EpochConfig`. +/// This helper is internal to the `epoch` sub‑command. fn handle_switch(args: cli_epoch::Switch, main_epoch: &mut EpochConfig) -> Result<(), AppError> { let target = main_epoch.get(&args.target)?; main_epoch.try_load(&target)?; main_epoch.epoch_id = target; - // TODO: Have a special centralized message dispacher - println!("Switched to epoch {:?}", target); main_epoch.save_with_context( "Saving modified epoch config", &lib_efo::epoch_struct::SaveMode::Erase, )?; + display_success(&SuccessMessages::EpochSwitchSuccess(target)); Ok(()) } @@ -108,9 +168,7 @@ fn handle_next(_args: cli_epoch::Next, main_epoch: &mut EpochConfig) -> Result<( let new_epoch = main_epoch.compute_next()?; // Insert new epoch - main_epoch - .insert_and_save(new_epoch, &lib_efo::epoch_struct::SaveMode::DoNotErase) - .unwrap(); + main_epoch.insert_and_save(new_epoch, &lib_efo::epoch_struct::SaveMode::DoNotErase)?; Ok(()) } } @@ -141,8 +199,8 @@ fn handle_reset(args: cli_epoch::Reset, main_epoch: &mut EpochConfig) -> Result< { main_epoch.delete_id(id)? } - // TODO: Have a special centralized message dispacher - println!("All future events deleted – back to epoch {current_id}",); + + display_success(&SuccessMessages::DeletedAllFutureEvents(current_id)); Ok(()) } @@ -200,10 +258,15 @@ fn handle_taging(args: cli_epoch::Tag, main_epoch: &mut EpochConfig) -> Result<( } } -/// Performs a basic sanity check. +/// Perform a filesystem consistency check on the epoch data. /// -/// Currently unimplemented – the function will panic at runtime. +/// The function invokes the internal consistency‑check logic of +/// `EpochConfig`. It is intended for use from the `fsck` sub‑command +/// and does **not** modify the current epoch. Any problems that +/// are detected are reported through the returned `Result`; the +/// command may also print a diagnostic message to the user. /// +/// This helper is internal to the `epoch` sub‑command. fn handle_fsck(args: cli_epoch::Fsck, main_epoch: &mut EpochConfig) -> Result<(), AppError> { let _ = main_epoch; let _ = args; diff --git a/bin_efo/src/commands/epoch/cli_epoch.rs b/bin_efo/src/commands/epoch/cli_epoch.rs index 1035258..f768f86 100644 --- a/bin_efo/src/commands/epoch/cli_epoch.rs +++ b/bin_efo/src/commands/epoch/cli_epoch.rs @@ -44,6 +44,9 @@ pub enum EpochCmd { /// Basic filesystem level maintenance Fsck(Fsck), + + /// Edits the summary for the current epoch + Summary(Summary), } /// Displays a git‑log style list of epochs. @@ -106,10 +109,18 @@ pub struct Diff { #[derive(Args, Debug)] pub struct Tag { #[arg(required = true)] - /// The tag to tag the current epoch with + #[allow(clippy::missing_docs_in_private_items)] pub tag: String, } /// Performs basic filesystem level maintenance. #[derive(Debug, Args)] pub struct Fsck {} + +/// Edits the current's epoch summary. +#[derive(Debug, Args)] +pub struct Summary { + #[arg(required = true)] + #[allow(clippy::missing_docs_in_private_items)] + pub summary: String, +} diff --git a/bin_efo/src/commands/init.rs b/bin_efo/src/commands/init.rs index 6717cb3..e7b7379 100644 --- a/bin_efo/src/commands/init.rs +++ b/bin_efo/src/commands/init.rs @@ -19,7 +19,10 @@ use lib_efo::{ }; use std::fs::read_dir; -use crate::error::AppError; +use crate::{ + error::AppError, + success::{SuccessMessages, display_success}, +}; #[derive(Args, Debug)] @@ -60,6 +63,8 @@ pub fn init(args: &InitCmd) -> Result<(), AppError> { .to_string(), ), })?; + + display_success(&SuccessMessages::FolderInitializedSuccessfully(".")); Ok(()) } diff --git a/bin_efo/src/main.rs b/bin_efo/src/main.rs index 632e51d..5182d77 100644 --- a/bin_efo/src/main.rs +++ b/bin_efo/src/main.rs @@ -21,12 +21,14 @@ //! ``` #![warn(missing_docs, clippy::missing_docs_in_private_items)] +#![deny(clippy::unwrap_used)] use clap::{ArgAction, Parser, Subcommand}; use crate::commands::init::InitCmd; use crate::{commands::epoch::cli_epoch::EpochCmd, error::AppError}; mod commands; mod error; +mod success; /// The root command‑line parser for the `efo` binary. /// @@ -66,8 +68,8 @@ enum TopLevelCmd { /// Program entry point. /// /// Parses the command‑line arguments and dispatches to the selected -/// sub‑command. Errors returned by the sub‑command handlers are printed -/// to stdout and returned as a `miette::Result<()>`. +/// sub‑command. Errors returned by the sub‑command handlers are shown +/// in stdout and returned as a `miette::Result<()>`. fn main() -> miette::Result<()> { env_logger::init(); let cli = Cli::parse(); @@ -90,18 +92,15 @@ fn main() -> miette::Result<()> { /// /// The function matches on the `TopLevelCmd` variant and calls the /// corresponding handler in the `commands` module. Any error is -/// propagated to the caller, which in `main` will be printed to +/// propagated to the caller, which in `main` will be shown to /// stdout and returned as a `miette::Result<()>`. fn exec_dispatch(cli: Cli) -> Result<(), AppError> { match cli.command { TopLevelCmd::Init(cmd) => { commands::init::init(&cmd)?; - // TODO: Have a special centralized message dispacher - println!("The folder was initialized as an epoch folder") } TopLevelCmd::Epoch(cmd) => { commands::epoch::handle_cmd(cmd)?; - // println!("") } } Ok(()) diff --git a/bin_efo/src/success.rs b/bin_efo/src/success.rs new file mode 100644 index 0000000..cb1e53b --- /dev/null +++ b/bin_efo/src/success.rs @@ -0,0 +1,25 @@ +//! List of all success messages possible + +use derive_more::Display; +use lib_efo::epoch_struct::EpochId; + +#[derive(Display, Clone, Debug)] +#[allow(missing_docs, clippy::missing_docs_in_private_items)] +pub enum SuccessMessages { + #[display("Switched to epoch {_0}")] + EpochSwitchSuccess(lib_efo::epoch_struct::EpochId), + + #[display("All future events deleted – back to epoch {_0}")] + DeletedAllFutureEvents(lib_efo::epoch_struct::EpochId), + + #[display("The folder was initialized as an epoch folder")] + FolderInitializedSuccessfully(&'static str), + + #[display("Changed the summary of epoch {_0} with: '{_1}'")] + ChangedSummary(EpochId, String), +} + +/// Display the success message to stdout +pub fn display_success(message: &SuccessMessages) { + println!("{}", message) +} diff --git a/lib_efo/Cargo.toml b/lib_efo/Cargo.toml index 8ab53cb..d9e38e8 100644 --- a/lib_efo/Cargo.toml +++ b/lib_efo/Cargo.toml @@ -11,5 +11,5 @@ clap = {workspace = true} miette = {workspace = true} env_logger = {workspace = true} log = {workspace = true} -derive_more = { version = "2.0.1", features = ["display"] } +derive_more = {workspace = true} cli-table = "0.5.0" diff --git a/lib_efo/src/epoch_struct/epoch_config.rs b/lib_efo/src/epoch_struct/epoch_config.rs index 2f6321c..217941c 100644 --- a/lib_efo/src/epoch_struct/epoch_config.rs +++ b/lib_efo/src/epoch_struct/epoch_config.rs @@ -17,7 +17,7 @@ use std::{ path::Path, }; -use log::info; +use log::{info, warn}; use serde::{Deserialize, Serialize}; use crate::{ @@ -98,9 +98,9 @@ impl EpochConfig { for elt in path { let elt = io_err_with_help!(elt, "Opening file in main config folder")?; if io_err_with_help!(elt.file_type(), "Determining file type of {:?}", elt)?.is_dir() { - let id = elt.file_name().to_string_lossy().parse::(); + let id = elt.file_name().to_string_lossy().parse::()?; info!("Initialized {:?}", id); - self.list_existing_epochs.insert(id.unwrap(), None); + self.list_existing_epochs.insert(id, None); } } Ok(self) @@ -188,7 +188,7 @@ impl EpochConfig { // TODO[9]: Create a delete_ids taking an iterator for added performance on huge deletions pub fn delete_id(&mut self, id: EpochId) -> Result<(), EpochError> { if !self.list_existing_epochs.contains_key(&id) { - println!( + warn!( "The given epoch {} doesn't exists and it's deletion was skipped", id ) @@ -213,7 +213,7 @@ impl EpochConfig { pub fn compute_next(&mut self) -> Result { // unimplemented!() // TODO[1]: Implement this - println!("DEBUG LINE: COMPUTING NEXT EPOCH"); + warn!("DEBUG LINE: COMPUTING NEXT EPOCH"); // New fake epoch Ok(EpochInfo::with_id(&self.epoch_id.next())) } @@ -252,7 +252,7 @@ impl EpochConfig { /// Load and display the metadata for a list of epoch IDs. /// /// The function first ensures that each requested epoch’s metadata is - /// loaded into memory, then prints a formatted log for each one. + /// loaded into memory, then displays a formatted log for each one. pub fn log_elements(&mut self, list_ids: &[EpochId]) -> Result<(), EpochError> { let mut items_to_log = Vec::with_capacity(list_ids.len()); // Tries to load all ids into memory diff --git a/lib_efo/src/epoch_struct/epoch_info.rs b/lib_efo/src/epoch_struct/epoch_info.rs index 4191705..7d28e9c 100644 --- a/lib_efo/src/epoch_struct/epoch_info.rs +++ b/lib_efo/src/epoch_struct/epoch_info.rs @@ -6,7 +6,7 @@ //! seed that produced the world, any optional tags, and a human‑readable //! summary. World data itself is stored separately (e.g. in `world.json`). -use cli_table::{Table, WithTitle}; +use cli_table::Table; use derive_more::Display; use serde::{Deserialize, Serialize}; use std::fs::create_dir_all; @@ -25,11 +25,10 @@ use crate::{ /// reconstruct the state *of that particular epoch* (seed, selected /// events, parent link, etc.). The full world data is kept in /// separate storage (e.g. `world.json`). -#[derive(Debug, Clone, Serialize, Deserialize, Display)] +#[derive(Debug, Clone, Serialize, Deserialize, Display, Table)] #[display( "Epoch ({epoch_id:>5}) | seed ({rng_seed:<10}) | tags ({tags:<10}) | summary ({summary:<20})" )] -#[derive(Table)] pub struct EpochInfo { /// The ID of this epoch – should match the directory name. #[table(title = "ID")] @@ -54,15 +53,7 @@ pub struct EpochInfo { pub summary: String, } -impl Prettiable for EpochInfo { - fn show_as_table(list: Vec<&Self>) { - cli_table::print_stdout(list.with_title()).unwrap(); - } - - fn as_log(&self) -> String { - format!("{}", self) - } -} +impl Prettiable for EpochInfo {} impl Default for EpochInfo { fn default() -> Self { diff --git a/lib_efo/src/epoch_traits.rs b/lib_efo/src/epoch_traits.rs index 9510172..85e16d9 100644 --- a/lib_efo/src/epoch_traits.rs +++ b/lib_efo/src/epoch_traits.rs @@ -5,8 +5,9 @@ //! common to many of the library’s element types. #![warn(clippy::missing_docs_in_private_items)] +use cli_table::{Style, Table, WithTitle}; use serde::Serialize; -use std::{fs::File, io::Write}; +use std::{fmt::Display, fs::File, io::Write}; use crate::{epoch_struct::SaveMode, error::EpochError}; @@ -23,22 +24,31 @@ pub trait Applyable {} pub trait Nextable {} /// Elements that can be rendered into a pretty, human‑readable form. -pub trait Prettiable { - // TODO: Doc - /// Show many as a table - fn show_as_table(list: Vec<&Self>) { - list.iter().for_each(|e| { - e.show_as_log(); - }); +pub trait Prettiable: Display { + /// Shows many items as a table. + /// + /// The table is printed to `stdout` using the `cli_table` crate. + /// + /// # Panics + /// Panics if printing the table to stdout fails. + fn show_as_table(list: Vec<&Self>) + where + for<'a> Vec<&'a Self>: Table + WithTitle, + { + #[allow(clippy::unwrap_used)] // There is no recovery of not being able to print a table + cli_table::print_stdout(list.with_title().bold(true)).unwrap(); } - /// Print function as a log + /// Displays the struct as a log entry by printing the output of + /// `as_log()` to stdout. fn show_as_log(&self) { println!("{}", self.as_log()) } - /// Convert the struct into a pretty log - fn as_log(&self) -> String; + /// Converts the struct into a pretty log string. + fn as_log(&self) -> String { + format!("{}", self) + } } /// Trait representing a serialisable / writable config @@ -49,7 +59,14 @@ pub trait ConfigWritable: Serialize { /// The folder where to save the file to save the config fn save_folder(&self) -> String; - /// Have the config as JSON + /// Serialises the config into a pretty JSON string. + /// + /// # Arguments + /// * `action` - A description of the action for error reporting. + /// + /// # Returns + /// * `Ok(String)` containing the pretty‑printed JSON. + /// * `Err(EpochError::Serde)` if serialisation fails. fn as_json(&self, action: String) -> Result { serde_json::to_string_pretty(self).map_err(|e| EpochError::Serde { source: e, @@ -58,9 +75,21 @@ pub trait ConfigWritable: Serialize { }) } - /// Save the config into it's nominal path + /// Saves the config into its nominal path. /// - /// This command will NOT create all subdirectories + /// Existing subdirectories are not created. + /// If `do_not_erase` is `SaveMode::Erase`, an existing file is overwritten. + /// If `do_not_erase` is `SaveMode::DoNotErase`, an error is returned when the + /// file already exists. + /// + /// # Arguments + /// * `action_description` – A human‑readable description used in error messages. + /// * `do_not_erase` – Determines whether to overwrite an existing file. + /// + /// # Returns + /// * `Ok(())` on success. + /// * `Err(EpochError::ConfigWrite)` on any serialization error. + /// * `Err(EpochError::ConfigCreation)` on any I/O error. fn save_with_context( &self, // Very unsure about this versus a macro diff --git a/lib_efo/src/lib.rs b/lib_efo/src/lib.rs index ee2acc6..5c0ffe5 100644 --- a/lib_efo/src/lib.rs +++ b/lib_efo/src/lib.rs @@ -18,6 +18,7 @@ //! `World::load()` / `World::save()` API that uses the default JSON file #![warn(missing_docs, clippy::missing_docs_in_private_items)] +#![deny(clippy::unwrap_used)] pub mod epoch_struct; pub mod epoch_traits; diff --git a/lib_efo/src/utils.rs b/lib_efo/src/utils.rs index d5c2794..67aac5b 100644 --- a/lib_efo/src/utils.rs +++ b/lib_efo/src/utils.rs @@ -13,20 +13,13 @@ use crate::error::EpochError; /// Check whether `path` points to a valid Epoch directory. /// /// A *valid* directory is one that satisfies the expectations of the `epoch` format. -#[deprecated] -pub fn is_a_epoch_directory(path: &Path) -> Result<(), EpochError> { - let dir = path.read_dir().map_err(|_e| { - EpochError::MainFolderInvalid(path.to_str().unwrap_or_default().to_owned()) - })?; - for e in dir.flatten() { - println!("{:?}", e.file_name()); - } - Ok(()) +pub fn is_a_epoch_directory(_path: &Path) -> Result<(), EpochError> { + todo!() } /// Validate that the configuration file at `path` is well‑formed. pub fn is_config_well_formated(_path: &Path) -> Result<(), EpochError> { - Ok(()) + todo!() } #[cfg(test)] -- 2.45.1 From debc59c02f80de4702a68a29545986f891a3ba92 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sat, 29 Nov 2025 20:11:52 +0100 Subject: [PATCH 09/22] Adds stats (lite) --- Cargo.lock | 119 +++++ bin_efo/src/commands/epoch.rs | 22 +- bin_efo/src/commands/epoch/cli_epoch.rs | 2 +- bin_efo/src/commands/init.rs | 7 +- bin_efo/src/success.rs | 9 +- lib_efo/Cargo.toml | 1 + lib_efo/src/{epoch_struct.rs => epoch.rs} | 1 + .../{epoch_struct => epoch}/epoch_config.rs | 14 +- .../src/{epoch_struct => epoch}/epoch_info.rs | 8 +- lib_efo/src/{ => epoch}/epoch_traits.rs | 2 +- lib_efo/src/error.rs | 8 +- lib_efo/src/lib.rs | 5 +- lib_efo/src/stats.rs | 485 ++++++++++++++++++ lib_efo/src/stats/implementations.rs | 159 ++++++ lib_efo/src/town.rs | 1 + 15 files changed, 800 insertions(+), 43 deletions(-) rename lib_efo/src/{epoch_struct.rs => epoch.rs} (99%) rename lib_efo/src/{epoch_struct => epoch}/epoch_config.rs (97%) rename lib_efo/src/{epoch_struct => epoch}/epoch_info.rs (94%) rename lib_efo/src/{ => epoch}/epoch_traits.rs (98%) create mode 100644 lib_efo/src/stats.rs create mode 100644 lib_efo/src/stats/implementations.rs create mode 100644 lib_efo/src/town.rs diff --git a/Cargo.lock b/Cargo.lock index a70b004..ff5f783 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -121,6 +121,12 @@ version = "2.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "812e12b5285cc515a9c72a5c1d3b6d46a19dac5acfef5265968c166106e31dd3" +[[package]] +name = "bumpalo" +version = "3.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "46c5e41b57b8bba42a04676d81cb89e9ee8e859a1a66f80a5a72e1cb76b34d43" + [[package]] name = "cfg-if" version = "1.0.4" @@ -271,6 +277,18 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "libc", + "r-efi", + "wasip2", +] + [[package]] name = "gimli" version = "0.32.3" @@ -325,6 +343,16 @@ dependencies = [ "syn", ] +[[package]] +name = "js-sys" +version = "0.3.83" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "464a3709c7f55f1f721e5389aa6ea4e3bc6aba669353300af094b29ffbdde1d8" +dependencies = [ + "once_cell", + "wasm-bindgen", +] + [[package]] name = "lib_efo" version = "0.1.0" @@ -338,6 +366,7 @@ dependencies = [ "serde", "serde_json", "thiserror", + "uuid", ] [[package]] @@ -412,6 +441,12 @@ dependencies = [ "memchr", ] +[[package]] +name = "once_cell" +version = "1.21.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d" + [[package]] name = "once_cell_polyfill" version = "1.70.2" @@ -457,6 +492,12 @@ dependencies = [ "proc-macro2", ] +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + [[package]] name = "regex" version = "1.12.2" @@ -505,6 +546,12 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "rustversion" +version = "1.0.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d" + [[package]] name = "ryu" version = "1.0.20" @@ -677,6 +724,72 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" +[[package]] +name = "uuid" +version = "1.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f87b8aa10b915a06587d0dec516c282ff295b475d94abf425d62b57710070a2" +dependencies = [ + "getrandom", + "js-sys", + "serde", + "wasm-bindgen", +] + +[[package]] +name = "wasip2" +version = "1.0.1+wasi-0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0562428422c63773dad2c345a1882263bbf4d65cf3f42e90921f787ef5ad58e7" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d759f433fa64a2d763d1340820e46e111a7a5ab75f993d1852d70b03dbb80fd" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48cb0d2638f8baedbc542ed444afc0644a29166f1595371af4fecf8ce1e7eeb3" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cefb59d5cd5f92d9dcf80e4683949f15ca4b511f4ac0a6e14d4e1ac60c6ecd40" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cbc538057e648b67f72a982e708d485b2efa771e1ac05fec311f9f63e5800db4" +dependencies = [ + "unicode-ident", +] + [[package]] name = "winapi-util" version = "0.1.11" @@ -774,3 +887,9 @@ name = "windows_x86_64_msvc" version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" + +[[package]] +name = "wit-bindgen" +version = "0.46.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f17a85883d4e6d00e8a97c586de764dabcc06133f7f1d55dce5cdc070ad7fe59" diff --git a/bin_efo/src/commands/epoch.rs b/bin_efo/src/commands/epoch.rs index a860281..2a567d2 100644 --- a/bin_efo/src/commands/epoch.rs +++ b/bin_efo/src/commands/epoch.rs @@ -9,8 +9,7 @@ use crate::{ success::{SuccessMessages, display_success}, }; use lib_efo::{ - epoch_struct::{EpochConfig, EpochId}, - epoch_traits::ConfigWritable, + epoch::{EpochConfig, EpochId, epoch_traits::ConfigWritable}, error::EpochError, }; use log::{debug, info}; @@ -73,10 +72,7 @@ fn handle_summary(args: cli_epoch::Summary, main_epoch: &mut EpochConfig) -> Res #[allow(clippy::unwrap_used)] // The epoch_id must exists at this point if let Some(epoch) = main_epoch.list_existing_epochs.get_mut(&epoch_id).unwrap() { epoch.summary = args.summary.clone(); - epoch.save_with_context( - "Saving new summary", - &lib_efo::epoch_struct::SaveMode::Erase, - )?; + epoch.save_with_context("Saving new summary", &lib_efo::epoch::SaveMode::Erase)?; display_success(&SuccessMessages::ChangedSummary(epoch_id, args.summary)); } @@ -133,7 +129,7 @@ fn handle_switch(args: cli_epoch::Switch, main_epoch: &mut EpochConfig) -> Resul main_epoch.save_with_context( "Saving modified epoch config", - &lib_efo::epoch_struct::SaveMode::Erase, + &lib_efo::epoch::SaveMode::Erase, )?; display_success(&SuccessMessages::EpochSwitchSuccess(target)); Ok(()) @@ -166,9 +162,11 @@ fn handle_next(_args: cli_epoch::Next, main_epoch: &mut EpochConfig) -> Result<( Err(AppError::Epoch(EpochError::FutureEpochExist)) } else { let new_epoch = main_epoch.compute_next()?; + let new_id = new_epoch.epoch_id; // Insert new epoch - main_epoch.insert_and_save(new_epoch, &lib_efo::epoch_struct::SaveMode::DoNotErase)?; + main_epoch.insert_and_save(new_epoch, &lib_efo::epoch::SaveMode::DoNotErase)?; + display_success(&SuccessMessages::EpochNextSuccess(current_id, new_id)); Ok(()) } } @@ -239,16 +237,14 @@ fn handle_taging(args: cli_epoch::Tag, main_epoch: &mut EpochConfig) -> Result<( .unwrap() { current_epoch_info.tags.push(args.tag.clone()); - current_epoch_info.save_with_context( - "Saving modified epoch", - &lib_efo::epoch_struct::SaveMode::Erase, - )?; + current_epoch_info + .save_with_context("Saving modified epoch", &lib_efo::epoch::SaveMode::Erase)?; main_epoch .tags .insert(args.tag.clone(), main_epoch.epoch_id); main_epoch.save_with_context( "Saving modified main config", - &lib_efo::epoch_struct::SaveMode::Erase, + &lib_efo::epoch::SaveMode::Erase, )?; Ok(()) } else { diff --git a/bin_efo/src/commands/epoch/cli_epoch.rs b/bin_efo/src/commands/epoch/cli_epoch.rs index f768f86..de436e6 100644 --- a/bin_efo/src/commands/epoch/cli_epoch.rs +++ b/bin_efo/src/commands/epoch/cli_epoch.rs @@ -16,7 +16,7 @@ #![warn(missing_docs, clippy::missing_docs_in_private_items)] use clap::{Args, Subcommand}; -use lib_efo::epoch_struct::EpochIdentifier; +use lib_efo::epoch::EpochIdentifier; /// Top‑level sub‑command for the `efo epoch` command. /// diff --git a/bin_efo/src/commands/init.rs b/bin_efo/src/commands/init.rs index e7b7379..fdb6bc2 100644 --- a/bin_efo/src/commands/init.rs +++ b/bin_efo/src/commands/init.rs @@ -13,8 +13,7 @@ use clap::Args; use lib_efo::{ - epoch_struct::{EpochConfig, EpochInfo}, - epoch_traits::ConfigWritable, + epoch::{EpochConfig, EpochInfo, epoch_traits::ConfigWritable}, error::EpochError, }; use std::fs::read_dir; @@ -55,7 +54,7 @@ pub fn init(args: &InitCmd) -> Result<(), AppError> { epoch_config .save_with_context( "Creatig initial config", - &lib_efo::epoch_struct::SaveMode::DoNotErase, + &lib_efo::epoch::SaveMode::DoNotErase, ) .map_err(|_| EpochError::AlreadyInitialized { advice: Some( @@ -77,7 +76,7 @@ fn init_epoch(_args: &InitCmd) -> Result<(), AppError> { _ = empty.create_subfolders(); empty.save_with_context( "Creating empty epoch file 0", - &lib_efo::epoch_struct::SaveMode::DoNotErase, + &lib_efo::epoch::SaveMode::DoNotErase, )?; Ok(()) } diff --git a/bin_efo/src/success.rs b/bin_efo/src/success.rs index cb1e53b..440e218 100644 --- a/bin_efo/src/success.rs +++ b/bin_efo/src/success.rs @@ -1,22 +1,25 @@ //! List of all success messages possible use derive_more::Display; -use lib_efo::epoch_struct::EpochId; +use lib_efo::epoch::EpochId; #[derive(Display, Clone, Debug)] #[allow(missing_docs, clippy::missing_docs_in_private_items)] pub enum SuccessMessages { #[display("Switched to epoch {_0}")] - EpochSwitchSuccess(lib_efo::epoch_struct::EpochId), + EpochSwitchSuccess(lib_efo::epoch::EpochId), #[display("All future events deleted – back to epoch {_0}")] - DeletedAllFutureEvents(lib_efo::epoch_struct::EpochId), + DeletedAllFutureEvents(lib_efo::epoch::EpochId), #[display("The folder was initialized as an epoch folder")] FolderInitializedSuccessfully(&'static str), #[display("Changed the summary of epoch {_0} with: '{_1}'")] ChangedSummary(EpochId, String), + + #[display("Successfully computed the new epoch. The current epoch is now {_1} (was {_0})")] + EpochNextSuccess(EpochId, EpochId), } /// Display the success message to stdout diff --git a/lib_efo/Cargo.toml b/lib_efo/Cargo.toml index d9e38e8..291afa5 100644 --- a/lib_efo/Cargo.toml +++ b/lib_efo/Cargo.toml @@ -13,3 +13,4 @@ env_logger = {workspace = true} log = {workspace = true} derive_more = {workspace = true} cli-table = "0.5.0" +uuid = { version = "1.18.1", features = ["serde", "v4"] } diff --git a/lib_efo/src/epoch_struct.rs b/lib_efo/src/epoch.rs similarity index 99% rename from lib_efo/src/epoch_struct.rs rename to lib_efo/src/epoch.rs index d197a85..7cc3713 100644 --- a/lib_efo/src/epoch_struct.rs +++ b/lib_efo/src/epoch.rs @@ -33,6 +33,7 @@ pub use epoch_config::EpochConfig; pub mod epoch_info; pub use epoch_info::EpochInfo; +pub mod epoch_traits; // TODO[5]: Try to load from a config and have it inserted as a backup /// The subfolder naming convention diff --git a/lib_efo/src/epoch_struct/epoch_config.rs b/lib_efo/src/epoch/epoch_config.rs similarity index 97% rename from lib_efo/src/epoch_struct/epoch_config.rs rename to lib_efo/src/epoch/epoch_config.rs index 217941c..27117a0 100644 --- a/lib_efo/src/epoch_struct/epoch_config.rs +++ b/lib_efo/src/epoch/epoch_config.rs @@ -10,7 +10,10 @@ //! The world data and all event logs belong to the individual epoch //! directories and are **not** part of this file. -use crate::epoch_traits::ConfigWritable; +use crate::epoch::{ + EpochId, EpochIdentifier, EpochInfo, MAIN_NAME, SUBFOLDER_NAMING, SaveMode, + epoch_traits::ConfigWritable, +}; use std::{ collections::HashMap, fs::{read_to_string, remove_dir_all}, @@ -20,14 +23,7 @@ use std::{ use log::{info, warn}; use serde::{Deserialize, Serialize}; -use crate::{ - epoch_struct::{ - EpochId, EpochIdentifier, MAIN_NAME, SUBFOLDER_NAMING, SaveMode, epoch_info::EpochInfo, - }, - epoch_traits::Prettiable, - error::EpochError, - io_err_with_help, -}; +use crate::{epoch::epoch_traits::Prettiable, error::EpochError, io_err_with_help}; /// The file written to *.epochconfig* that tells the CLI which /// epoch folder is the “current” one. diff --git a/lib_efo/src/epoch_struct/epoch_info.rs b/lib_efo/src/epoch/epoch_info.rs similarity index 94% rename from lib_efo/src/epoch_struct/epoch_info.rs rename to lib_efo/src/epoch/epoch_info.rs index 7d28e9c..b7fb7f1 100644 --- a/lib_efo/src/epoch_struct/epoch_info.rs +++ b/lib_efo/src/epoch/epoch_info.rs @@ -12,8 +12,10 @@ use serde::{Deserialize, Serialize}; use std::fs::create_dir_all; use crate::{ - epoch_struct::{self, EpochId, SUB_NAME, SUBFOLDER_NAMING, TagList}, - epoch_traits::{ConfigWritable, Prettiable}, + epoch::{ + EpochId, SUB_NAME, SUBFOLDER_NAMING, TagList, + epoch_traits::{ConfigWritable, Prettiable}, + }, error::EpochError, io_err_with_help, }; @@ -58,7 +60,7 @@ impl Prettiable for EpochInfo {} impl Default for EpochInfo { fn default() -> Self { Self { - epoch_id: epoch_struct::EpochId::new(0), + epoch_id: EpochId::new(0), rng_seed: 0, tags: TagList::new(), summary: String::new(), diff --git a/lib_efo/src/epoch_traits.rs b/lib_efo/src/epoch/epoch_traits.rs similarity index 98% rename from lib_efo/src/epoch_traits.rs rename to lib_efo/src/epoch/epoch_traits.rs index 85e16d9..ac7ec34 100644 --- a/lib_efo/src/epoch_traits.rs +++ b/lib_efo/src/epoch/epoch_traits.rs @@ -9,7 +9,7 @@ use cli_table::{Style, Table, WithTitle}; use serde::Serialize; use std::{fmt::Display, fs::File, io::Write}; -use crate::{epoch_struct::SaveMode, error::EpochError}; +use crate::{epoch::SaveMode, error::EpochError}; /// Elements that can be compared with another instance to produce a diff. pub trait Diffable {} diff --git a/lib_efo/src/error.rs b/lib_efo/src/error.rs index dd660b4..d0ad190 100644 --- a/lib_efo/src/error.rs +++ b/lib_efo/src/error.rs @@ -14,7 +14,7 @@ use std::{num::ParseIntError, path::PathBuf}; use thiserror::Error; -use crate::epoch_struct::EpochId; +use crate::epoch::EpochId; use miette::Diagnostic; /// Errors that can be returned by the storage layer. @@ -229,12 +229,6 @@ pub enum UserErrors { /// Helper macro to convert a `std::io::Error` into an `EpochError::Io` /// with an attached help message. /// -/// ```rust -/// # use lib_efo::error::io_err_with_help; -/// let result: Result<(), std::io::Error> = std::fs::read_to_string("does_not_exist").map(|_| ()); -/// let err = io_err_with_help!(result, "Make sure the file exists"); -/// ``` -/// /// The macro captures the current line number for debugging purposes. #[macro_export] macro_rules! io_err_with_help { diff --git a/lib_efo/src/lib.rs b/lib_efo/src/lib.rs index 5c0ffe5..a9a8e92 100644 --- a/lib_efo/src/lib.rs +++ b/lib_efo/src/lib.rs @@ -20,8 +20,9 @@ #![warn(missing_docs, clippy::missing_docs_in_private_items)] #![deny(clippy::unwrap_used)] -pub mod epoch_struct; -pub mod epoch_traits; +pub mod epoch; +pub mod stats; +pub mod town; #[macro_use] pub mod error; pub mod utils; diff --git a/lib_efo/src/stats.rs b/lib_efo/src/stats.rs new file mode 100644 index 0000000..0cd8903 --- /dev/null +++ b/lib_efo/src/stats.rs @@ -0,0 +1,485 @@ +//! Module holing all stats and methods to use them + +#![allow(dead_code)] + +use uuid::Uuid; +mod implementations; + +/// Statistics that describe the population of a city and its social climate. +/// +/// The struct is split into four logical groups: +/// * **Core metrics** – values that change every turn and drive the city’s behaviour. +/// * **Derived metrics** – calculated from the core metrics and other game data. +/// * **Hidden metrics** – internal state that influences derived values but is not exposed directly to the player. +/// * **Resource & skill metrics** – affect production and the city’s efficiency. +/// +/// All statistics are represented by custom wrappers (`PrimaryStat`, `InferredStat`, …) to keep +/// type‑safety and to indicate how they are normally updated. +struct Demographics { + // ──────────────────────────────────────────────────────────────────────────────── + // 1. Core metrics – the “raw” population data + // ──────────────────────────────────────────────────────────────────────────────── + /// Population count + /// + /// *Effect*: Drives resource consumption and output capacity. + /// *Source*: Updated by the growth/decay formulas each turn. + population: PrimaryStat, + + /// Growth rate of the population (per‑turn change). + /// + /// *Effect*: Forecasts future needs and indicates potential unrest. + /// *Source*: Derivative of `population`, `happiness`, and `stability`. + growth_rate: PrimaryStat, + + /// Crime level of the city. + /// + /// *Effect*: Can trigger riots and lower stability. + /// *Source*: Result of the crime function (often influenced by class disparity and law enforcement). + crime: PrimaryStat, + + /// Overall health of the population. + /// + /// *Effect*: Affects population size and can generate unrest. + /// *Source*: Output of the health function (influenced by sanitation, disease spread, etc.). + health: PrimaryStat, + + /// Base skill of the populace (e.g., general craftsmanship). + /// + /// *Effect*: Determines how efficiently the city can produce goods. + /// *Source*: Global slider set by the player; may be modified by education or tech bonuses. + skill: PrimaryStat, + + // ──────────────────────────────────────────────────────────────────────────────── + // 2. Derived metrics – calculated from the core data + // ──────────────────────────────────────────────────────────────────────────────── + /// Overall “demographics” score. + /// + /// *Effect*: Used as a weighting factor for major random events (e.g., disasters, hero visits). + /// *Source*: Inferred from the primary metrics, with a heavy emphasis on `population` and `unrest`. + demographics: InferredStat, + + /// Expected consumption of resources. + /// + /// *Effect*: Drives the city’s production targets and food/water needs. + /// *Source*: `consumption = f(population, class distribution, technology level)`. + consumption: InferredStat, + + /// Level of social unrest. + /// + /// *Effect*: Predicts riots, rebellions, tax evasion, and other disruptive behaviour. + /// *Source*: `unrest = f(happiness, crime, war, stability)`. + unrest: InferredStat, + + // ──────────────────────────────────────────────────────────────────────────────── + // 3. Hidden metrics – internal state not directly exposed + // ──────────────────────────────────────────────────────────────────────────────── + /// Base happiness of the population (internal scale). + /// + /// *Effect*: Influences productivity, tax compliance, and the calculation of `unrest`. + /// *Source*: Output of the happiness function (affected by class, war, and infrastructure). + happiness: HiddenStat, + + /// Base level of fear among citizens (internal scale). + /// + /// *Effect*: Contributes to `unrest`, crime, and population growth rate. + /// *Source*: Result of monster encounters, external threats, and environmental hazards. + fear: HiddenStat, +} +/// Statistics that describe the city’s economic health and its impact on the empire. +/// +/// The fields are divided into three groups: +/// * **Core metrics** – the raw values that the player can control or that the engine updates. +/// * **Derived metrics** – numbers calculated from the core metrics (often the ones displayed to the player). +/// * **Hidden metrics** – internal helpers that drive the derived values but are not exposed to the UI. +struct Economics { + // ──────────────────────────────────────── + // 1. Core metrics – raw, player‑controlled values + // ──────────────────────────────────────── + /// Amount of food produced by the city. + /// + /// *Effect*: Food is required to keep the population alive and productive. + /// *Source*: `food = farm_yield + tech_level`. + food: PrimaryStat, + + /// Strength of the city’s industry. + /// + /// *Effect*: Drives tax revenue and the ability to produce units. + /// *Source*: `industry = factory_output + tech_level`. + industry: PrimaryStat, + + /// Scientific output of the city. + /// + /// *Effect*: Determines how fast research is completed. + /// *Source*: `science = research_center_output + tech_level`. + science: PrimaryStat, + + /// Revenue collected through taxation. + /// + /// *Effect*: Funds city upkeep and projects. + /// *Source*: `tax = tax_rate × wealth × (1 – evasion)`. + tax: PrimaryStat, + + /// Debt / budget deficit of the city. + /// + /// *Effect*: Affects stability and population growth. + /// *Source*: Result of budget calculations; naturally decays if `eco_power` stays high. + debt: PrimaryStat, + + /// Trade volume / exports generated by the city. + /// + /// *Effect*: Influences influence and wealth. + /// *Source*: `trade = trade_network_output`. + trade: PrimaryStat, + + // ──────────────────────────────────────── + // 2. Derived metrics – calculated from core data + // ──────────────────────────────────────── + /// Overall economic power of the city. + /// + /// *Effect*: Used to rank the city’s importance within the empire. + /// *Source*: `eco_power = wealth × stability × influence`. + eco_power: InferredStat, + + /// Net monetary output – the city’s “wealth” or GDP. + /// + /// *Effect*: Determines the city’s overall financial health. + /// *Source*: `wealth = tax + trade + industry_profits`. + wealth: InferredStat, + + // ──────────────────────────────────────── + // 3. Hidden metrics – internal helpers + // ──────────────────────────────────────── + /// Cost of maintaining the city’s infrastructure. + /// + /// *Effect*: Drain on the budget (reduces available funds for projects). + /// *Source*: `infra_cost = cost_of_wonders + cost_of_roads + ...`. + infra_cost: InferredStat, +} +/// Statistics that govern the city’s cultural life and its influence on the empire. +/// +/// The fields are grouped into: +/// * **Core metrics** – the raw outputs that the player can build into. +/// * **Derived metrics** – values calculated from the core metrics (often the ones displayed to the player). +/// * **Hidden metrics** – internal helpers that help derive the derived values (none in this struct, but the pattern is kept for consistency). +struct Social { + // ───────────────────────────────────────────────────────────── + // 1. Core metrics – directly produced by the city + // ───────────────────────────────────────────────────────────── + /// Cultural output from arts, theatres, museums, etc. + /// + /// *Effect*: Drives tourism, prestige, and overall happiness. + /// *Source*: `culture = Σ(cultural_building_output)`. + culture: PrimaryStat, + + /// Religious influence from temples, churches, etc. + /// + /// *Effect*: Affects stability and political influence. + /// *Source*: `religion = Σ(religious_building_output)`. + religion: PrimaryStat, + + /// Level of education/literacy in the city. + /// + /// *Effect*: Improves productivity, science output, and reduces unrest. + /// *Source*: `education = Σ(education_building_output)`. + education: PrimaryStat, + + // ───────────────────────────────────────────────────────────── + // 2. Derived metrics – calculated from core data + // ───────────────────────────────────────────────────────────── + /// Tourism revenue generated by the city’s attractions. + /// + /// *Effect*: Provides an additional income stream. + /// *Source*: `tourism = number_of_tourists × price_per_tourist`. + tourism: PrimaryStat, + + /// Overall social prestige of the city. + /// + /// *Effect*: Determines the city’s standing in the empire and in diplomatic relations. + /// *Source*: `social = f(culture, religion, education, influence)` (the exact formula is hidden but inferred from the other values). + social: InferredStat, + + /// Cultural influence over the surrounding region. + /// + /// *Effect*: Increases the city’s sway in the empire and can grant diplomatic bonuses. + /// *Source*: `influence = culture × population`. + influence: InferredStat, +} + +/// Statistics that describe a city’s armed forces and its battlefield posture. +/// +/// The fields are split into two logical groups: +/// * **Core metrics** – raw numbers that the player can influence with units, training, or infrastructure. +/// * **Derived metrics** – values calculated each turn from the core metrics (the ones most players will see). +/// +/// All stats use wrapper types (`PrimaryStat`, `InferredStat`) so that the compiler can enforce +/// that only the correct kinds of values are combined in formulas. +struct Military { + // ───────────────────────────────────────────────── + // 1. Core metrics – the raw, game‑state numbers + // ───────────────────────────────────────────────── + /// Number of battle‑ready units (size, type, equipment, etc.). + /// + /// *Effect*: Determines the city’s direct defensive and offensive capability. + /// *Source*: Sum of all units in the army list that are trained and equipped. + army: PrimaryStat, + + /// Composite strength of the army (tech, training, equipment). + /// + /// *Effect*: Adds to combat power in battles and determines the required force to defeat the enemy. + /// *Source*: `strength = Σ(unit_strength) × tech_bonus × training_bonus`. + strength: PrimaryStat, + + /// Readiness/morale of the forces. + /// + /// *Effect*: Modifies the actual combat effectiveness in battles. + /// *Source*: Output of the morale function, which may depend on recent victories, supply levels, etc. + readiness: PrimaryStat, + + /// Defensive bonus from fortifications (walls, towers, etc.). + /// + /// *Effect*: Adds a defensive multiplier to the city’s overall defense rating. + /// *Source*: `fortification = Σ(fortification_building_bonus)`. + fortification: PrimaryStat, + + /// Strategic importance of the city’s location. + /// + /// *Effect*: Influences enemy targeting decisions and the city’s priority for defense upgrades. + /// *Source*: `strategic_value = f(proximity_to_borders, resource_nodes, transport_hubs)`. + strategic_value: PrimaryStat, + + // ───────────────────────────────────────────────── + // 2. Derived metrics – calculated from the core data + // ───────────────────────────────────────────────── + /// Overall threat level facing the city. + /// + /// *Effect*: Predicts the likelihood of being attacked and can trigger early warning alerts. + /// *Source*: `threat = (enemy_proximity + enemy_strength) / defense`. + threat: InferredStat, + + // ───────────────────────────────────────────────── + // 3. Main combined metric – the city’s total military power + // ───────────────────────────────────────────────── + /// Combined military power used for empire‑wide rankings and event weighting. + /// + /// *Effect*: The “size” of the city’s armed forces in the eyes of the empire. + /// *Source*: `military = f(army, strength, readiness, fortification, strategic_value)`. + military: InferredStat, +} +/// Statistics that describe a city’s built environment and its ability to support the population. +/// +/// The fields are separated into two logical groups: +/// * **Core infrastructure** – the raw assets the player builds and upgrades. +/// * **Derived infrastructure** – numbers calculated each turn from the core assets (the ones you’ll see in the UI). +/// +/// All stats use the wrapper types (`PrimaryStat`, `InferredStat`) so that the compiler can +/// keep the formulas type‑safe and easy to reason about. +struct Infrastructure { + // ─────────────────────────────────────────────────────────── + // 1. Core infrastructure – the raw, player‑controlled values + // ─────────────────────────────────────────────────────── + /// Communication network strength. + /// + /// *Effect*: Enables espionage, real‑time resource monitoring, and can unlock advanced building upgrades. + /// *Source*: `communications = Σ(communication_building_bonus)`. + communications: PrimaryStat, + + /// Total water and electricity supply capacity. + /// + /// *Effect*: Required for industry output and maintaining population health. + /// *Source*: `needs = Σ(supply_unit_output)`. + needs: PrimaryStat, + + /// Total amount of waste / pollution produced by the city. + /// + /// *Effect*: Reduces health and happiness, can trigger unrest if too high. + /// *Source*: `pollution = Σ(building_pollution)`. + pollution: PrimaryStat, + + /// Available building slots (housing, industry, etc.). + /// + /// *Effect*: Caps how many new structures can be added until more slots are built. + /// *Source*: `space = Σ(slot_building_capacity)`. + space: PrimaryStat, + + // ─────────────────────────────────────────────────────────── + // 2. Derived infrastructure – calculated from core data + // ─────────────────────────────────────────────────────── + /// Overall connectivity of the city (roads, rails, ports, etc.). + /// + /// *Effect*: Drives trade volume, military supply lines, and logistics efficiency. + /// *Source*: `connectivity = Σ(link_strength)`. + connectivity: InferredStat, + + /// Total infrastructure power of the city. + /// + /// *Effect*: Used to rank the city’s importance within the empire and to calculate event weights. + /// *Source*: `infrastructure = f(connectivity, communications, needs, pollution, space)`. + infrastructure: InferredStat, +} + +/// Strategic context and meta‑data for a city. +/// +/// The struct is divided into three logical parts: +/// * **Location & spatial data** – hidden values that feed map‑based calculations. +/// * **Strategic positioning** – meta‑information that determines specialization, trade, and defense. +/// * **Political & relational data** – things that influence diplomacy, governance, and inter‑city links. +/// +/// All fields use the wrapper types (`HiddenStat`, `PrimaryStat`, `InferredStat`) so the compiler +/// can enforce that only the correct kinds of values are combined in formulas. +struct Strategics { + // ──────────────────────────────────────── + // 1. Location & spatial data (hidden) + // ──────────────────────────────────────── + /// Cartesian coordinates of the city on the world map. + /// + /// *Effect*: Used for distance calculations, visibility, and map‑based event logic. + /// *Source*: Raw coordinates supplied by the map generator. + position: HiddenStat, + + /// Euclidean distance to the empire’s capital. + /// + /// *Effect*: Influences trade costs, supply line strength, and early warning range. + /// *Source*: `distance_to_capital = dist(position, capital_position)`. + distance_to_capital: HiddenStat, + + /// List of nearby resource nodes (mines, forests, farms, etc.). + /// + /// *Effect*: Drives the city’s specialization and determines the default output mix. + /// *Source*: `ressources = filter(resource_list, distance ≤ detection_radius)`. + ressources: HiddenStat, + + /// The city’s chosen specialization tag (e.g., “Agricultural Hub”, “Industrial Center”). + /// + /// *Effect*: Sets the default output multipliers for production. + /// *Source*: `specialisation = tag_assigned_by_player_or_ai`. + specialisation: HiddenStat, + + // ──────────────────────────────────────── + // 2. Strategic positioning (hidden + public) + // ──────────────────────────────────────── + /// Current governor or leader assigned to the city. + /// + /// *Effect*: Adds personal bonuses and can modify policies or diplomatic stance. + /// *Source*: `governor = selected_leader_uuid`. + governor: Uuid, + + /// The city’s classification (capital, trade hub, frontier post, etc.). + /// + /// *Effect*: Alters base production, tax rates, and certain event probabilities. + /// *Source*: `category = tag_assigned_by_player_or_ai`. + category: PrimaryStat, + + /// The faction or empire to which the city currently belongs. + /// + /// *Effect*: Determines diplomatic relations, war status, and access to empire‑wide bonuses. + /// *Source*: `faction = current_faction_uuid`. + faction: Uuid, + + // ──────────────────────────────────────── + // 3. Links & relational data + // ──────────────────────────────────────── + /// UIDs of all entities the city is linked to (roads, trade routes, alliances, war declarations, etc.). + /// + /// *Effect*: Influences economic, military, and diplomatic interactions. + /// *Source*: `links = Vec` collected from the city’s network manager. + links: Vec, + + // ──────────────────────────────────────── + // 4. Meta‑statistics (derived) + // ──────────────────────────────────────── + /// Prestige / reputation of the city in the eyes of the empire and foreign powers. + /// + /// *Effect*: Affects foreign relations, diplomatic offers, and event weighting. + /// *Source*: `prestige = f(culture, trade, military)`. + prestige: InferredStat, +} + +// --- STAT TYPES --------------------------------------------------------------- +// The game distinguishes four kinds of statistics. +// The *visibility* of a stat determines whether it is shown to the player +// (Primary / Inferred) and whether the player can change it manually +// (Primary / Hidden). +// +// All four stat structs simply wrap a signed integer, but they all +// implement the same behaviour via the `GameStat` trait below. + +/// A stat that is shown to the player *and* can be modified manually. +#[allow(missing_docs)] +pub struct PrimaryStat { + pub value: isize, +} + +/// A stat that is hidden from the recap UI, but still user‑editable. +#[allow(missing_docs)] +pub struct HiddenStat { + pub value: isize, +} + +/// A stat that is calculated from other data, shown to the player, +/// but not directly editable. +#[allow(missing_docs)] +pub struct InferredStat { + pub value: isize, +} + +/// A stat that is calculated from other data and hidden from the UI. +#[allow(missing_docs)] +pub struct HiddenInferredStat { + pub value: isize, +} + +// --- VISIBILITY ENUM ------------------------------------------------------------ + +/// The underlying visibility level for a stat. +/// The enum is used by `GameStat::visibility` to let the UI decide +/// whether to display a particular stat or not. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum VisibilityLevel { + /// Primary stat – shown & editable. + Primary, + /// Hidden stat – not shown, editable. + Hidden, + /// Inferred stat – shown, calculated. + Inferred, + /// Hidden inferred stat – not shown, calculated. + HiddenInferred, +} + +/// --- TRAITS --------------------------------------------------------------- +/// A stat is a *game value* that can be converted to two different +/// normalised ranges – a 50‑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. +pub trait GameStat { + /// Convert the raw integer to a 50‑point scale. + fn to_50(&self) -> isize { + (self.get_value().clamp(0, 70) - 10).min(50) + } + + /// Convert the raw integer to a 10‑point scale. + fn to_10(&self) -> isize { + self.to_50() / 5 + } + + /// Return the raw integer value, always bound to 0-70 + fn get_value(&self) -> isize; + + /// Return the stat’s visibility level. + fn visibility(&self) -> VisibilityLevel; + + /// 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`. + /// `None` if the key does not exist. + fn get_val(&self, key: &str) -> Option>; +} diff --git a/lib_efo/src/stats/implementations.rs b/lib_efo/src/stats/implementations.rs new file mode 100644 index 0000000..156d3e3 --- /dev/null +++ b/lib_efo/src/stats/implementations.rs @@ -0,0 +1,159 @@ +//! All traits implementatition for the main structs are deffered here + +use crate::stats::VisibilityLevel; +use crate::stats::{ + Demographics, Economics, GameStat, HiddenInferredStat, HiddenStat, InferredStat, + Infrastructure, Military, PrimaryStat, Social, +}; + +/// Generates an `impl GameStat for ` where the only difference between +/// multiple implementations is the visibility level. +/// +/// # Parameters +/// * `$type`: the concrete type that implements `GameStat` +/// * `$vis`: the enum variant of `VisibilityLevel` to return +macro_rules! impl_game_stat { + ($type:ident, $vis:ident) => { + impl GameStat for $type { + fn get_value(&self) -> isize { + self.value + } + + fn visibility(&self) -> VisibilityLevel { + VisibilityLevel::$vis + } + + fn change_value(&mut self, value: isize) { + self.value = value; + } + + fn from_value(value: isize) -> Self + where + Self: Sized, + { + Self { value } + } + } + }; +} + +impl_game_stat!(PrimaryStat, Primary); +impl_game_stat!(HiddenStat, Hidden); +impl_game_stat!(InferredStat, Inferred); +impl_game_stat!(HiddenInferredStat, HiddenInferred); + +/// A field accessor to be able to modify fields on the fly +macro_rules! field_accessor { + ($name:ident { $($field:ident),* }) => { + impl $name { + fn get_field(&self, key: &str) -> Option<&dyn GameStat> { + match key { + $( + stringify!($field) => Some(&self.$field), + )* + _ => None, + } + } + + fn get_field_mut(&mut self, key: &str) -> Option<&mut dyn GameStat> { + match key { + $( + stringify!($field) => Some(&mut self.$field), + )* + _ => None, + } + } + } + }; +} + +field_accessor!(Demographics { + population, + growth_rate, + crime, + health, + skill, + demographics, + consumption, + unrest, + happiness, + fear +}); +field_accessor!(Economics { + food, + industry, + science, + tax, + debt, + trade, + eco_power, + wealth, + infra_cost +}); +field_accessor!(Social { + culture, + religion, + education, + tourism, + social, + influence +}); + +field_accessor!(Military { + army, + strength, + readiness, + fortification, + strategic_value, + threat, + military +}); +field_accessor!(Infrastructure { + communications, + needs, + pollution, + space, + connectivity, + infrastructure +}); +// field_accessor!(Strategics { +// position, +// distance_to_capital, +// ressources, +// specialisation, +// governor, +// category, +// faction, +// links, +// prestige +// }); + +#[cfg(test)] +pub(crate) mod test { + #![allow(clippy::unwrap_used)] + use crate::stats::GameStat; + use crate::stats::PrimaryStat; + + struct Person { + name: PrimaryStat, + age: PrimaryStat, + email: PrimaryStat, + } + + field_accessor!(Person { name, age, email }); + + #[test] + fn bob() { + let person = Person { + name: PrimaryStat { value: 10 }, + age: PrimaryStat { value: 20 }, + email: PrimaryStat { value: 70 }, + }; + let name = person.get_field("name").unwrap(); + let email = person.get_field("email").unwrap(); + let age = person.get_field("age").unwrap(); + assert_eq!(name.to_50(), 0); + assert_eq!(age.to_50(), 10); + assert_eq!(email.to_50(), 50); + } +} diff --git a/lib_efo/src/town.rs b/lib_efo/src/town.rs new file mode 100644 index 0000000..30d2a85 --- /dev/null +++ b/lib_efo/src/town.rs @@ -0,0 +1 @@ +//! All the structs and logic surrounding towns -- 2.45.1 From 087425f4e82d96baf9be8bfef2b8ae014e13c508 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sun, 30 Nov 2025 01:12:52 +0100 Subject: [PATCH 10/22] Adds some stats implementations --- Cargo.lock | 101 +++- lib_efo/Cargo.toml | 1 + lib_efo/src/error.rs | 10 + lib_efo/src/stats.rs | 660 ++++++++++++--------------- lib_efo/src/stats/implementations.rs | 380 ++++++++++++--- 5 files changed, 700 insertions(+), 452 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index ff5f783..43dc96f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -202,6 +202,15 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b05b61dc5112cbb17e4b6cd61790d9845d13888356391624cbe7e41efeac1e75" +[[package]] +name = "colored" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fde0e0ec90c9dfb3b4b1a0891a7dcd0e2bffde2f7efed5fe7c9bb00e5bfb915e" +dependencies = [ + "windows-sys 0.59.0", +] + [[package]] name = "csv" version = "1.4.0" @@ -359,6 +368,7 @@ version = "0.1.0" dependencies = [ "clap", "cli-table", + "colored", "derive_more", "env_logger", "log", @@ -805,13 +815,22 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" +[[package]] +name = "windows-sys" +version = "0.59.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" +dependencies = [ + "windows-targets 0.52.6", +] + [[package]] name = "windows-sys" version = "0.60.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb" dependencies = [ - "windows-targets", + "windows-targets 0.53.5", ] [[package]] @@ -823,6 +842,22 @@ dependencies = [ "windows-link", ] +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm 0.52.6", + "windows_aarch64_msvc 0.52.6", + "windows_i686_gnu 0.52.6", + "windows_i686_gnullvm 0.52.6", + "windows_i686_msvc 0.52.6", + "windows_x86_64_gnu 0.52.6", + "windows_x86_64_gnullvm 0.52.6", + "windows_x86_64_msvc 0.52.6", +] + [[package]] name = "windows-targets" version = "0.53.5" @@ -830,58 +865,106 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3" dependencies = [ "windows-link", - "windows_aarch64_gnullvm", - "windows_aarch64_msvc", - "windows_i686_gnu", - "windows_i686_gnullvm", - "windows_i686_msvc", - "windows_x86_64_gnu", - "windows_x86_64_gnullvm", - "windows_x86_64_msvc", + "windows_aarch64_gnullvm 0.53.1", + "windows_aarch64_msvc 0.53.1", + "windows_i686_gnu 0.53.1", + "windows_i686_gnullvm 0.53.1", + "windows_i686_msvc 0.53.1", + "windows_x86_64_gnu 0.53.1", + "windows_x86_64_gnullvm 0.53.1", + "windows_x86_64_msvc 0.53.1", ] +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + [[package]] name = "windows_aarch64_gnullvm" version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53" +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + [[package]] name = "windows_aarch64_msvc" version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006" +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + [[package]] name = "windows_i686_gnu" version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3" +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + [[package]] name = "windows_i686_gnullvm" version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c" +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + [[package]] name = "windows_i686_msvc" version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2" +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + [[package]] name = "windows_x86_64_gnu" version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499" +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + [[package]] name = "windows_x86_64_gnullvm" version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1" +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + [[package]] name = "windows_x86_64_msvc" version = "0.53.1" diff --git a/lib_efo/Cargo.toml b/lib_efo/Cargo.toml index 291afa5..99817c4 100644 --- a/lib_efo/Cargo.toml +++ b/lib_efo/Cargo.toml @@ -14,3 +14,4 @@ log = {workspace = true} derive_more = {workspace = true} cli-table = "0.5.0" uuid = { version = "1.18.1", features = ["serde", "v4"] } +colored = "3.0.0" diff --git a/lib_efo/src/error.rs b/lib_efo/src/error.rs index d0ad190..f03e8ee 100644 --- a/lib_efo/src/error.rs +++ b/lib_efo/src/error.rs @@ -203,6 +203,16 @@ pub enum EpochError { #[diagnostic(code(EpochError::Unknown))] Unknown(String), + /// The user tried to parse an acronim that doen't match any stats known to the system. + #[error("Unknown stat acronym: {0}")] + #[diagnostic(code(EpochError::UnknownStatAcronim))] + UnknownStatAcronim(String), + + /// The user gave a stat:identifier pair that was incorrect + #[error("Expected a stat and a number, got: {0}")] + #[diagnostic(code(EpochError::IllFormedStatQualifier))] + IllFormedStatQualifier(String), + /// User error, meant to be very explicit over what happened and what to do. #[error("An user facing error")] #[diagnostic(code(EpochError::UserError))] diff --git a/lib_efo/src/stats.rs b/lib_efo/src/stats.rs index 0cd8903..7e5ad13 100644 --- a/lib_efo/src/stats.rs +++ b/lib_efo/src/stats.rs @@ -1,450 +1,351 @@ -//! Module holing all stats and methods to use them +//! 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. #![allow(dead_code)] +#![deny(clippy::missing_docs_in_private_items)] +use cli_table::Table; +use colored::Colorize; +use derive_more::Display; +use serde::{Deserialize, Serialize}; use uuid::Uuid; mod implementations; -/// Statistics that describe the population of a city and its social climate. +/// Aggregated statistics for a single entity. /// -/// The struct is split into four logical groups: -/// * **Core metrics** – values that change every turn and drive the city’s behaviour. -/// * **Derived metrics** – calculated from the core metrics and other game data. -/// * **Hidden metrics** – internal state that influences derived values but is not exposed directly to the player. -/// * **Resource & skill metrics** – affect production and the city’s efficiency. -/// -/// All statistics are represented by custom wrappers (`PrimaryStat`, `InferredStat`, …) to keep -/// type‑safety and to indicate how they are normally updated. -struct Demographics { - // ──────────────────────────────────────────────────────────────────────────────── - // 1. Core metrics – the “raw” population data - // ──────────────────────────────────────────────────────────────────────────────── - /// Population count +/// 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)] +// #[derive(Add, Sub)] +struct OverallStats { + // ──────────────────────── Demographics ──────────────────────── + /// Total economic health of the entity. /// - /// *Effect*: Drives resource consumption and output capacity. - /// *Source*: Updated by the growth/decay formulas each turn. - population: PrimaryStat, + /// **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. + 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. + pub population: GenericStat, - /// Growth rate of the population (per‑turn change). + /// Per‑turn change in population. /// - /// *Effect*: Forecasts future needs and indicates potential unrest. - /// *Source*: Derivative of `population`, `happiness`, and `stability`. - growth_rate: PrimaryStat, + /// **Purpose** – The growth rate of the population. + /// **Effect** – Predicts future needs and signals potential social unrest. + /// **Source** – Derived from `population`, `happiness`, and `stability`. + pub growth_rate: GenericStat, - /// Crime level of the city. + /// Crime level (0–1 scale). /// - /// *Effect*: Can trigger riots and lower stability. - /// *Source*: Result of the crime function (often influenced by class disparity and law enforcement). - crime: PrimaryStat, + /// **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). + pub crime: GenericStat, - /// Overall health of the population. + /// Base happiness of the population (0–1 scale). /// - /// *Effect*: Affects population size and can generate unrest. - /// *Source*: Output of the health function (influenced by sanitation, disease spread, etc.). - health: PrimaryStat, + /// **Purpose** – A measure of citizen contentment. + /// **Effect** – Influences productivity, tax compliance, and unrest. + /// **Source** – Output of the happiness function (affected by class, war, infrastructure). + pub happiness: GenericStat, - /// Base skill of the populace (e.g., general craftsmanship). + // ──────────────────────── Economy ──────────────────────── + /// Aggregate economic health of the entity. /// - /// *Effect*: Determines how efficiently the city can produce goods. - /// *Source*: Global slider set by the player; may be modified by education or tech bonuses. - skill: PrimaryStat, + /// **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. + pub economy: GenericStat, - // ──────────────────────────────────────────────────────────────────────────────── - // 2. Derived metrics – calculated from the core data - // ──────────────────────────────────────────────────────────────────────────────── - /// Overall “demographics” score. + /// Food produced by the entity. /// - /// *Effect*: Used as a weighting factor for major random events (e.g., disasters, hero visits). - /// *Source*: Inferred from the primary metrics, with a heavy emphasis on `population` and `unrest`. - demographics: InferredStat, + /// **Purpose** – Amount of consumable resources available. + /// **Effect** – Keeps the population alive and productive. + /// **Source** – `food = farm_yield + tech_level`. + pub food: GenericStat, - /// Expected consumption of resources. + /// Strength of the industry. /// - /// *Effect*: Drives the city’s production targets and food/water needs. - /// *Source*: `consumption = f(population, class distribution, technology level)`. - consumption: InferredStat, + /// **Purpose** – Industrial production capacity. + /// **Effect** – Drives tax revenue and unit production. + /// **Source** – `industry = factory_output + tech_level`. + pub industry: GenericStat, - /// Level of social unrest. + /// Scientific output. /// - /// *Effect*: Predicts riots, rebellions, tax evasion, and other disruptive behaviour. - /// *Source*: `unrest = f(happiness, crime, war, stability)`. - unrest: InferredStat, + /// **Purpose** – Rate of research progress. + /// **Effect** – Determines how quickly new technologies are unlocked. + /// **Source** – `science = research_center_output + tech_level`. + pub science: GenericStat, - // ──────────────────────────────────────────────────────────────────────────────── - // 3. Hidden metrics – internal state not directly exposed - // ──────────────────────────────────────────────────────────────────────────────── - /// Base happiness of the population (internal scale). + /// Trade volume / exports. /// - /// *Effect*: Influences productivity, tax compliance, and the calculation of `unrest`. - /// *Source*: Output of the happiness function (affected by class, war, and infrastructure). - happiness: HiddenStat, + /// **Purpose** – Measure of export activity. + /// **Effect** – Influences influence and wealth. + /// **Source** – `trade = trade_network_output`. + 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. + // pub social: GenericStat, - /// Base level of fear among citizens (internal scale). - /// - /// *Effect*: Contributes to `unrest`, crime, and population growth rate. - /// *Source*: Result of monster encounters, external threats, and environmental hazards. - fear: HiddenStat, -} -/// Statistics that describe the city’s economic health and its impact on the empire. -/// -/// The fields are divided into three groups: -/// * **Core metrics** – the raw values that the player can control or that the engine updates. -/// * **Derived metrics** – numbers calculated from the core metrics (often the ones displayed to the player). -/// * **Hidden metrics** – internal helpers that drive the derived values but are not exposed to the UI. -struct Economics { - // ──────────────────────────────────────── - // 1. Core metrics – raw, player‑controlled values - // ──────────────────────────────────────── - /// Amount of food produced by the city. - /// - /// *Effect*: Food is required to keep the population alive and productive. - /// *Source*: `food = farm_yield + tech_level`. - food: PrimaryStat, + // /// Cultural output from arts, theatres, museums, etc. + // /// + // /// **Purpose** – Measure of cultural production. + // /// **Effect** – Drives tourism, prestige, and happiness. + // /// **Source** – `culture = Σ(cultural_building_output)`. + // pub culture: GenericStat, - /// Strength of the city’s industry. - /// - /// *Effect*: Drives tax revenue and the ability to produce units. - /// *Source*: `industry = factory_output + tech_level`. - industry: PrimaryStat, + // /// Level of education/literacy. + // /// + // /// **Purpose** – Measure of the citizenry’s knowledge. + // /// **Effect** – Improves productivity, science output, and reduces unrest. + // /// **Source** – `education = Σ(education_building_output)`. + // pub education: GenericStat, - /// Scientific output of the city. - /// - /// *Effect*: Determines how fast research is completed. - /// *Source*: `science = research_center_output + tech_level`. - science: PrimaryStat, + // /// Tourism revenue. + // /// + // /// **Purpose** – Income generated by visitors. + // /// **Effect** – Provides an additional income stream. + // /// **Source** – `tourism = number_of_tourists × price_per_tourist`. + // pub tourism: GenericStat, - /// Revenue collected through taxation. - /// - /// *Effect*: Funds city upkeep and projects. - /// *Source*: `tax = tax_rate × wealth × (1 – evasion)`. - tax: PrimaryStat, + // /// Cultural influence over the region. + // /// + // /// **Purpose** – Measure of soft power. + // /// **Effect** – Grants diplomatic bonuses and increases sway in the empire. + // /// **Source** – `influence = culture × population`. + // pub influence: GenericStat, - /// Debt / budget deficit of the city. + // ──────────────────────── Military ──────────────────────── + /// Overall military power. /// - /// *Effect*: Affects stability and population growth. - /// *Source*: Result of budget calculations; naturally decays if `eco_power` stays high. - debt: PrimaryStat, + /// **Purpose** – Composite measure of combat capability. + /// **Effect** – Determines defensive and offensive strength. + /// **Source** – Sum of `army`, `strength`, `fortification`, etc. + pub military: GenericStat, - /// Trade volume / exports generated by the city. + /// Number of battle‑ready units. /// - /// *Effect*: Influences influence and wealth. - /// *Source*: `trade = trade_network_output`. - trade: PrimaryStat, + /// **Purpose** – Size of the active army. + /// **Effect** – Directly dictates defense and attack potential. + /// **Source** – Sum of all trained and equipped units. + pub army: GenericStat, - // ──────────────────────────────────────── - // 2. Derived metrics – calculated from core data - // ──────────────────────────────────────── - /// Overall economic power of the city. + /// Composite strength of the army. /// - /// *Effect*: Used to rank the city’s importance within the empire. - /// *Source*: `eco_power = wealth × stability × influence`. - eco_power: InferredStat, + /// **Purpose** – Tech, training, and equipment bonuses aggregated. + /// **Effect** – Determines combat effectiveness and required force to defeat an enemy. + /// **Source** – `strength = Σ(unit_strength) × tech_bonus × training_bonus`. + pub strength: GenericStat, - /// Net monetary output – the city’s “wealth” or GDP. + /// Defensive bonus from fortifications. /// - /// *Effect*: Determines the city’s overall financial health. - /// *Source*: `wealth = tax + trade + industry_profits`. - wealth: InferredStat, + /// **Purpose** – Wall and tower defenses. + /// **Effect** – Adds a multiplier to overall defense. + /// **Source** – `fortification = Σ(fortification_building_bonus)`. + pub fortification: GenericStat, - // ──────────────────────────────────────── - // 3. Hidden metrics – internal helpers - // ──────────────────────────────────────── - /// Cost of maintaining the city’s infrastructure. + /// Threat level facing the entity. /// - /// *Effect*: Drain on the budget (reduces available funds for projects). - /// *Source*: `infra_cost = cost_of_wonders + cost_of_roads + ...`. - infra_cost: InferredStat, -} -/// Statistics that govern the city’s cultural life and its influence on the empire. -/// -/// The fields are grouped into: -/// * **Core metrics** – the raw outputs that the player can build into. -/// * **Derived metrics** – values calculated from the core metrics (often the ones displayed to the player). -/// * **Hidden metrics** – internal helpers that help derive the derived values (none in this struct, but the pattern is kept for consistency). -struct Social { - // ───────────────────────────────────────────────────────────── - // 1. Core metrics – directly produced by the city - // ───────────────────────────────────────────────────────────── - /// Cultural output from arts, theatres, museums, etc. - /// - /// *Effect*: Drives tourism, prestige, and overall happiness. - /// *Source*: `culture = Σ(cultural_building_output)`. - culture: PrimaryStat, + /// **Purpose** – Likelihood of being attacked. + /// **Effect** – Triggers early warning alerts and strategic decisions. + /// **Source** – `threat = (enemy_proximity + enemy_strength) / defense`. + pub threat: GenericStat, - /// Religious influence from temples, churches, etc. + // ──────────────────────── Infrastructure ──────────────────────── + /// Total infrastructure power. /// - /// *Effect*: Affects stability and political influence. - /// *Source*: `religion = Σ(religious_building_output)`. - religion: PrimaryStat, + /// **Purpose** – Overall built‑environment capacity. + /// **Effect** – Supports population size and efficiency. + /// **Source** – Sum of all infrastructure components. + pub infrastructure: GenericStat, - /// Level of education/literacy in the city. + /// Bureaucratic power. /// - /// *Effect*: Improves productivity, science output, and reduces unrest. - /// *Source*: `education = Σ(education_building_output)`. - education: PrimaryStat, + /// **Purpose** – Efficiency of the city’s administrative machinery. + /// **Effect** – Improves resource management and policy implementation. + /// **Source** – `bureaucracy = Σ(bureaucracy_building_output)`. + pub bureaucracy: GenericStat, - // ───────────────────────────────────────────────────────────── - // 2. Derived metrics – calculated from core data - // ───────────────────────────────────────────────────────────── - /// Tourism revenue generated by the city’s attractions. + /// Transportation level. /// - /// *Effect*: Provides an additional income stream. - /// *Source*: `tourism = number_of_tourists × price_per_tourist`. - tourism: PrimaryStat, + /// **Purpose** – Availability and quality of transport infrastructure. + /// **Effect** – Impacts logistics, mobility, and trade. + /// **Source** – `transportation = Σ(transport_building_output)`. + pub transportation: GenericStat, - /// Overall social prestige of the city. + /// Sprawl / urban density. /// - /// *Effect*: Determines the city’s standing in the empire and in diplomatic relations. - /// *Source*: `social = f(culture, religion, education, influence)` (the exact formula is hidden but inferred from the other values). - social: InferredStat, + /// **Purpose** – Measure of city sprawl and clutter. + /// **Effect** – Affects health, happiness, and infrastructure efficiency. + /// **Source** – `sprawl = Σ(sprawl_factor)`. + pub sprawl: GenericStat, - /// Cultural influence over the surrounding region. + /// Health infrastructure quality. /// - /// *Effect*: Increases the city’s sway in the empire and can grant diplomatic bonuses. - /// *Source*: `influence = culture × population`. - influence: InferredStat, + /// **Purpose** – Public health capacity. + /// **Effect** – Affects population health and can generate unrest. + /// **Source** – `health = output_of_health_function` (influenced by sanitation, disease spread, etc.). + pub health: GenericStat, } -/// Statistics that describe a city’s armed forces and its battlefield posture. +/// Strategic context and meta‑data for an entity. /// -/// The fields are split into two logical groups: -/// * **Core metrics** – raw numbers that the player can influence with units, training, or infrastructure. -/// * **Derived metrics** – values calculated each turn from the core metrics (the ones most players will see). -/// -/// All stats use wrapper types (`PrimaryStat`, `InferredStat`) so that the compiler can enforce -/// that only the correct kinds of values are combined in formulas. -struct Military { - // ───────────────────────────────────────────────── - // 1. Core metrics – the raw, game‑state numbers - // ───────────────────────────────────────────────── - /// Number of battle‑ready units (size, type, equipment, etc.). +/// All fields are intentionally simple – the logic that interprets them +/// lives in separate modules (e.g. `map`, `network`, `governance`). +#[derive(Debug, Clone, Default)] +pub struct Strategics { + // ──── Location & Spatial Data (hidden) ─────────────────────────────── + /// Cartesian coordinates of the entity on the world map. /// - /// *Effect*: Determines the city’s direct defensive and offensive capability. - /// *Source*: Sum of all units in the army list that are trained and equipped. - army: PrimaryStat, + /// **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: (usize, usize), - /// Composite strength of the army (tech, training, equipment). + /// Euclidean distance to the empire’s capital (in tile units). /// - /// *Effect*: Adds to combat power in battles and determines the required force to defeat the enemy. - /// *Source*: `strength = Σ(unit_strength) × tech_bonus × training_bonus`. - strength: PrimaryStat, - - /// Readiness/morale of the forces. - /// - /// *Effect*: Modifies the actual combat effectiveness in battles. - /// *Source*: Output of the morale function, which may depend on recent victories, supply levels, etc. - readiness: PrimaryStat, - - /// Defensive bonus from fortifications (walls, towers, etc.). - /// - /// *Effect*: Adds a defensive multiplier to the city’s overall defense rating. - /// *Source*: `fortification = Σ(fortification_building_bonus)`. - fortification: PrimaryStat, - - /// Strategic importance of the city’s location. - /// - /// *Effect*: Influences enemy targeting decisions and the city’s priority for defense upgrades. - /// *Source*: `strategic_value = f(proximity_to_borders, resource_nodes, transport_hubs)`. - strategic_value: PrimaryStat, - - // ───────────────────────────────────────────────── - // 2. Derived metrics – calculated from the core data - // ───────────────────────────────────────────────── - /// Overall threat level facing the city. - /// - /// *Effect*: Predicts the likelihood of being attacked and can trigger early warning alerts. - /// *Source*: `threat = (enemy_proximity + enemy_strength) / defense`. - threat: InferredStat, - - // ───────────────────────────────────────────────── - // 3. Main combined metric – the city’s total military power - // ───────────────────────────────────────────────── - /// Combined military power used for empire‑wide rankings and event weighting. - /// - /// *Effect*: The “size” of the city’s armed forces in the eyes of the empire. - /// *Source*: `military = f(army, strength, readiness, fortification, strategic_value)`. - military: InferredStat, -} -/// Statistics that describe a city’s built environment and its ability to support the population. -/// -/// The fields are separated into two logical groups: -/// * **Core infrastructure** – the raw assets the player builds and upgrades. -/// * **Derived infrastructure** – numbers calculated each turn from the core assets (the ones you’ll see in the UI). -/// -/// All stats use the wrapper types (`PrimaryStat`, `InferredStat`) so that the compiler can -/// keep the formulas type‑safe and easy to reason about. -struct Infrastructure { - // ─────────────────────────────────────────────────────────── - // 1. Core infrastructure – the raw, player‑controlled values - // ─────────────────────────────────────────────────────── - /// Communication network strength. - /// - /// *Effect*: Enables espionage, real‑time resource monitoring, and can unlock advanced building upgrades. - /// *Source*: `communications = Σ(communication_building_bonus)`. - communications: PrimaryStat, - - /// Total water and electricity supply capacity. - /// - /// *Effect*: Required for industry output and maintaining population health. - /// *Source*: `needs = Σ(supply_unit_output)`. - needs: PrimaryStat, - - /// Total amount of waste / pollution produced by the city. - /// - /// *Effect*: Reduces health and happiness, can trigger unrest if too high. - /// *Source*: `pollution = Σ(building_pollution)`. - pollution: PrimaryStat, - - /// Available building slots (housing, industry, etc.). - /// - /// *Effect*: Caps how many new structures can be added until more slots are built. - /// *Source*: `space = Σ(slot_building_capacity)`. - space: PrimaryStat, - - // ─────────────────────────────────────────────────────────── - // 2. Derived infrastructure – calculated from core data - // ─────────────────────────────────────────────────────── - /// Overall connectivity of the city (roads, rails, ports, etc.). - /// - /// *Effect*: Drives trade volume, military supply lines, and logistics efficiency. - /// *Source*: `connectivity = Σ(link_strength)`. - connectivity: InferredStat, - - /// Total infrastructure power of the city. - /// - /// *Effect*: Used to rank the city’s importance within the empire and to calculate event weights. - /// *Source*: `infrastructure = f(connectivity, communications, needs, pollution, space)`. - infrastructure: InferredStat, -} - -/// Strategic context and meta‑data for a city. -/// -/// The struct is divided into three logical parts: -/// * **Location & spatial data** – hidden values that feed map‑based calculations. -/// * **Strategic positioning** – meta‑information that determines specialization, trade, and defense. -/// * **Political & relational data** – things that influence diplomacy, governance, and inter‑city links. -/// -/// All fields use the wrapper types (`HiddenStat`, `PrimaryStat`, `InferredStat`) so the compiler -/// can enforce that only the correct kinds of values are combined in formulas. -struct Strategics { - // ──────────────────────────────────────── - // 1. Location & spatial data (hidden) - // ──────────────────────────────────────── - /// Cartesian coordinates of the city on the world map. - /// - /// *Effect*: Used for distance calculations, visibility, and map‑based event logic. - /// *Source*: Raw coordinates supplied by the map generator. - position: HiddenStat, - - /// Euclidean distance to the empire’s capital. - /// - /// *Effect*: Influences trade costs, supply line strength, and early warning range. - /// *Source*: `distance_to_capital = dist(position, capital_position)`. - distance_to_capital: HiddenStat, + /// **Purpose** – Metric of remoteness from the political centre. + /// **Effect** – Influences trade costs, supply‑line strength, + /// and the range of early‑warning signals. + /// **Source** – `distance_to_capital = dist(position, capital_position)`. + pub distance_to_capital: usize, /// List of nearby resource nodes (mines, forests, farms, etc.). /// - /// *Effect*: Drives the city’s specialization and determines the default output mix. - /// *Source*: `ressources = filter(resource_list, distance ≤ detection_radius)`. - ressources: HiddenStat, + /// **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, - /// The city’s chosen specialization tag (e.g., “Agricultural Hub”, “Industrial Center”). + /// The entity’s chosen specialization tag + /// (e.g., “Agricultural Hub”, “Industrial Center”). /// - /// *Effect*: Sets the default output multipliers for production. - /// *Source*: `specialisation = tag_assigned_by_player_or_ai`. - specialisation: HiddenStat, + /// **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, - // ──────────────────────────────────────── - // 2. Strategic positioning (hidden + public) - // ──────────────────────────────────────── - /// Current governor or leader assigned to the city. + // ──── Strategic Positioning (hidden + public) ───────────────────── + /// Current governor or leader assigned to the entity. /// - /// *Effect*: Adds personal bonuses and can modify policies or diplomatic stance. - /// *Source*: `governor = selected_leader_uuid`. - governor: Uuid, + /// **Purpose** – Leadership identity. + /// **Effect** – Adds personal bonuses and may modify policies + /// or diplomatic stance. + /// **Source** – `governor = selected_leader_uuid`. + pub governor: Uuid, - /// The city’s classification (capital, trade hub, frontier post, etc.). + /// The entity’s classification (capital, trade hub, frontier post, etc.). /// - /// *Effect*: Alters base production, tax rates, and certain event probabilities. - /// *Source*: `category = tag_assigned_by_player_or_ai`. - category: PrimaryStat, + /// **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 city currently belongs. + /// The faction or empire to which the entity currently belongs. /// - /// *Effect*: Determines diplomatic relations, war status, and access to empire‑wide bonuses. - /// *Source*: `faction = current_faction_uuid`. - faction: Uuid, + /// **Purpose** – Political affiliation. + /// **Effect** – Determines diplomatic relations, war status, + /// and access to empire‑wide bonuses. + /// **Source** – `faction = current_faction_uuid`. + pub faction: Uuid, - // ──────────────────────────────────────── - // 3. Links & relational data - // ──────────────────────────────────────── - /// UIDs of all entities the city is linked to (roads, trade routes, alliances, war declarations, etc.). + /// UIDs of all entities the entity is linked to (roads, trade routes, + /// alliances, war declarations, etc.). /// - /// *Effect*: Influences economic, military, and diplomatic interactions. - /// *Source*: `links = Vec` collected from the city’s network manager. - links: Vec, + /// **Purpose** – Connectivity network. + /// **Effect** – Influences economic, military, and diplomatic + /// interactions. + /// **Source** – `links = Vec` collected from the entity’s + /// network manager. + pub links: Vec, - // ──────────────────────────────────────── - // 4. Meta‑statistics (derived) - // ──────────────────────────────────────── - /// Prestige / reputation of the city in the eyes of the empire and foreign powers. + /// Prestige / reputation of the entity in the eyes of the empire + /// and foreign powers. /// - /// *Effect*: Affects foreign relations, diplomatic offers, and event weighting. - /// *Source*: `prestige = f(culture, trade, military)`. - prestige: InferredStat, + /// **Purpose** – Social standing metric. + /// **Effect** – Affects diplomatic influence, trade bonuses, + /// and event outcomes. + /// **Source** – `prestige = calculate_prestige(...)`. + pub prestige: usize, } -// --- STAT TYPES --------------------------------------------------------------- -// The game distinguishes four kinds of statistics. -// The *visibility* of a stat determines whether it is shown to the player -// (Primary / Inferred) and whether the player can change it manually -// (Primary / Hidden). -// -// All four stat structs simply wrap a signed integer, but they all -// implement the same behaviour via the `GameStat` trait below. +/// 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, +} +/// Bridge between the CLI and the statistics logic. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +#[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, +} + +// fn print_generic_stat() /// A stat that is shown to the player *and* can be modified manually. #[allow(missing_docs)] -pub struct PrimaryStat { +#[derive(Debug, Clone, Default, Serialize, Deserialize, Display)] +pub struct GenericStat { pub value: isize, } -/// A stat that is hidden from the recap UI, but still user‑editable. -#[allow(missing_docs)] -pub struct HiddenStat { - pub value: isize, -} - -/// A stat that is calculated from other data, shown to the player, -/// but not directly editable. -#[allow(missing_docs)] -pub struct InferredStat { - pub value: isize, -} - -/// A stat that is calculated from other data and hidden from the UI. -#[allow(missing_docs)] -pub struct HiddenInferredStat { - pub value: isize, -} - -// --- VISIBILITY ENUM ------------------------------------------------------------ - -/// The underlying visibility level for a stat. -/// The enum is used by `GameStat::visibility` to let the UI decide -/// whether to display a particular stat or not. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum VisibilityLevel { - /// Primary stat – shown & editable. - Primary, - /// Hidden stat – not shown, editable. - Hidden, - /// Inferred stat – shown, calculated. - Inferred, - /// Hidden inferred stat – not shown, calculated. - HiddenInferred, -} - /// --- TRAITS --------------------------------------------------------------- /// A stat is a *game value* that can be converted to two different /// normalised ranges – a 50‑point range for “gaming” logic and a @@ -461,12 +362,19 @@ pub trait GameStat { self.to_50() / 5 } + /// 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 stat’s visibility level. - fn visibility(&self) -> VisibilityLevel; - /// Return the raw integer value, always bound to 0-70 fn change_value(&mut self, value: isize); @@ -475,6 +383,7 @@ pub trait GameStat { 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. @@ -483,3 +392,8 @@ pub trait Accessible { /// `None` if the key does not exist. fn get_val(&self, key: &str) -> Option>; } + +// pub trait Displayable { +// fn summary(&self) -> String; +// fn full_description(&self) -> String; +// } diff --git a/lib_efo/src/stats/implementations.rs b/lib_efo/src/stats/implementations.rs index 156d3e3..508cfd2 100644 --- a/lib_efo/src/stats/implementations.rs +++ b/lib_efo/src/stats/implementations.rs @@ -1,10 +1,13 @@ //! All traits implementatition for the main structs are deffered here -use crate::stats::VisibilityLevel; -use crate::stats::{ - Demographics, Economics, GameStat, HiddenInferredStat, HiddenStat, InferredStat, - Infrastructure, Military, PrimaryStat, Social, -}; +use std::str::FromStr; + +use crate::error::EpochError; +use crate::stats; +use crate::stats::GameStat; +use crate::stats::GenericStat; +use crate::stats::ListStats; +use crate::stats::OverallStats; /// Generates an `impl GameStat for ` where the only difference between /// multiple implementations is the visibility level. @@ -13,16 +16,12 @@ use crate::stats::{ /// * `$type`: the concrete type that implements `GameStat` /// * `$vis`: the enum variant of `VisibilityLevel` to return macro_rules! impl_game_stat { - ($type:ident, $vis:ident) => { + ($type:ident) => { impl GameStat for $type { fn get_value(&self) -> isize { self.value } - fn visibility(&self) -> VisibilityLevel { - VisibilityLevel::$vis - } - fn change_value(&mut self, value: isize) { self.value = value; } @@ -37,11 +36,6 @@ macro_rules! impl_game_stat { }; } -impl_game_stat!(PrimaryStat, Primary); -impl_game_stat!(HiddenStat, Hidden); -impl_game_stat!(InferredStat, Inferred); -impl_game_stat!(HiddenInferredStat, HiddenInferred); - /// A field accessor to be able to modify fields on the fly macro_rules! field_accessor { ($name:ident { $($field:ident),* }) => { @@ -67,87 +61,158 @@ macro_rules! field_accessor { }; } -field_accessor!(Demographics { +impl_game_stat!(GenericStat); +field_accessor!(OverallStats { + demographics, population, growth_rate, crime, - health, - skill, - demographics, - consumption, - unrest, happiness, - fear -}); -field_accessor!(Economics { + economy, food, industry, science, - tax, - debt, trade, - eco_power, - wealth, - infra_cost -}); -field_accessor!(Social { - culture, - religion, - education, - tourism, - social, - influence -}); - -field_accessor!(Military { + // social, + // culture, + // education, + // tourism, + // influence, + military, army, strength, - readiness, fortification, - strategic_value, threat, - military + infrastructure, + bureaucracy, + transportation, + sprawl, + health }); -field_accessor!(Infrastructure { - communications, - needs, - pollution, - space, - connectivity, - infrastructure -}); -// field_accessor!(Strategics { -// position, -// distance_to_capital, -// ressources, -// specialisation, -// governor, -// category, -// faction, -// links, -// prestige -// }); + +impl FromStr for ListStats { + type Err = EpochError; + + /// Convert an acronym (e.g. `"cri"`) into the corresponding enum variant. + fn from_str(s: &str) -> Result { + match s.to_ascii_lowercase().as_str() { + "dem" | "demog" | "demographics" | "demo" => Ok(ListStats::Demographics), + "pop" | "popul" | "populations" => Ok(ListStats::Population), + "grow" | "grw" | "growth" => Ok(ListStats::Growthrate), + "cri" | "crim" | "crimes" => Ok(ListStats::Crime), + "hapn" | "happines" | "hap" => Ok(ListStats::Happiness), + "eco" | "economy" | "econ" => Ok(ListStats::Economy), + "food" | "fo" | "agr" | "agri" => Ok(ListStats::Food), + "industry" | "indus" | "ind" => Ok(ListStats::Industry), + "science" | "sci" | "sc" => Ok(ListStats::Science), + "trade" | "trd" | "tr" => Ok(ListStats::Trade), + "social" | "soc" | "sl" => Ok(ListStats::Social), + "culture" | "cul" | "cl" => Ok(ListStats::Culture), + "education" | "edu" | "ed" => Ok(ListStats::Education), + "tourism" | "tour" | "tm" => Ok(ListStats::Tourism), + "influence" | "infl" | "influ" => Ok(ListStats::Influence), + "military" | "mil" | "mt" => Ok(ListStats::Military), + "army" | "arm" | "ar" => Ok(ListStats::Army), + "strength" | "str" | "st" => Ok(ListStats::Strength), + "fortification" | "fort" | "ft" => Ok(ListStats::Fortification), + "threat" | "thr" | "th" => Ok(ListStats::Threat), + "infrastructure" | "infra" | "infr" => Ok(ListStats::Infrastructure), + "bureaucracy" | "bureau" | "bur" => Ok(ListStats::Bureaucracy), + "transportation" | "trans" | "trns" => Ok(ListStats::Transportation), + "sprawl" | "spr" | "spra" => Ok(ListStats::Sprawl), + "health" | "hlth" | "hlt" => Ok(ListStats::Health), + _ => Err(EpochError::UnknownStatAcronim(s.to_owned())), + } + } +} + +impl From for &str { + fn from(value: ListStats) -> Self { + match value { + ListStats::Demographics => "demographics", + ListStats::Population => "population", + ListStats::Growthrate => "growthrate", + ListStats::Crime => "crime", + ListStats::Happiness => "happiness", + ListStats::Economy => "economy", + ListStats::Food => "food", + ListStats::Industry => "industry", + ListStats::Science => "science", + ListStats::Trade => "trade", + ListStats::Social => "social", + ListStats::Culture => "culture", + ListStats::Education => "education", + ListStats::Tourism => "tourism", + ListStats::Influence => "influence", + ListStats::Military => "military", + ListStats::Army => "army", + ListStats::Strength => "strength", + ListStats::Fortification => "fortification", + ListStats::Threat => "threat", + ListStats::Infrastructure => "infrastructure", + ListStats::Bureaucracy => "bureaucracy", + ListStats::Transportation => "transportation", + ListStats::Sprawl => "sprawl", + ListStats::Health => "health", + } + } +} + +/// A generic stat pair with (stat, value), used mainly for clap +/// Accepts two forms +/// 1. "cri 10" (two separate tokens) +/// 2. "cri:10" (one token with a separator) +pub struct StatPair(ListStats, GenericStat); +impl FromStr for StatPair { + type Err = EpochError; + + fn from_str(s: &str) -> Result { + let (stat_str, val_str) = if let Some(idx) = s.find(':') { + (&s[..idx], &s[idx + 1..]) + } else { + let parts: Vec<&str> = s.split_whitespace().collect(); + if parts.len() != 2 { + return Err(EpochError::IllFormedStatQualifier(s.to_owned())); + } + (parts[0], parts[1]) + }; + + let stat: ListStats = stat_str.parse()?; + let value: isize = val_str + .parse() + .map_err(|_| EpochError::IllFormedStatQualifier(val_str.to_owned()))?; + Ok(StatPair(stat, stats::GenericStat { value })) + } +} #[cfg(test)] pub(crate) mod test { #![allow(clippy::unwrap_used)] + use super::*; use crate::stats::GameStat; - use crate::stats::PrimaryStat; + use crate::stats::GenericStat; + use std::str::FromStr; struct Person { - name: PrimaryStat, - age: PrimaryStat, - email: PrimaryStat, + name: GenericStat, + age: GenericStat, + email: GenericStat, + } + + /// Helper that asserts that a string parses to the expected ListStats variant. + fn assert_stat_ok(input: &str, expected: ListStats) { + let parsed = ListStats::from_str(input).expect("should parse"); + assert_eq!(parsed, expected, "input `{}` parsed incorrectly", input); } field_accessor!(Person { name, age, email }); #[test] - fn bob() { + fn test_field_accessors() { let person = Person { - name: PrimaryStat { value: 10 }, - age: PrimaryStat { value: 20 }, - email: PrimaryStat { value: 70 }, + name: GenericStat { value: 10 }, + age: GenericStat { value: 20 }, + email: GenericStat { value: 70 }, }; let name = person.get_field("name").unwrap(); let email = person.get_field("email").unwrap(); @@ -156,4 +221,179 @@ pub(crate) mod test { assert_eq!(age.to_50(), 10); assert_eq!(email.to_50(), 50); } + + #[test] + fn test_clap_serialisation() {} + /// Helper that asserts that a stat pair string parses to the expected `StatPair`. + fn assert_pair_ok(input: &str, expected_stat: ListStats, expected_val: isize) { + let pair = StatPair::from_str(input).expect("should parse"); + assert_eq!(pair.0, expected_stat, "stat mismatch"); + assert_eq!(pair.1.value, expected_val, "value mismatch"); + } + #[test] + fn test_stat_pair_parsing() { + // Colon syntax + assert_pair_ok("cri:10", ListStats::Crime, 10); + assert_pair_ok("POP:-5", ListStats::Population, -5); + assert_pair_ok("growth:0", ListStats::Growthrate, 0); + + // Space syntax (clap concatenates two separate args into one string) + assert_pair_ok("cri 10", ListStats::Crime, 10); + assert_pair_ok("Pop -5", ListStats::Population, -5); + assert_pair_ok("grow 0", ListStats::Growthrate, 0); + } + #[test] + fn test_list_stats_all_aliases() { + let stats = OverallStats::default(); + // Demographics + assert_stat_ok("dem", ListStats::Demographics); + assert_stat_ok("Demog", ListStats::Demographics); + assert_stat_ok("DEMOGRAPHICS", ListStats::Demographics); + assert_stat_ok("Demo", ListStats::Demographics); + stats.get_field(ListStats::Demographics.into()); + // Population + assert_stat_ok("pop", ListStats::Population); + assert_stat_ok("Popul", ListStats::Population); + assert_stat_ok("POPULATIONS", ListStats::Population); + stats.get_field(ListStats::Population.into()); + + // Growthrate + assert_stat_ok("grow", ListStats::Growthrate); + assert_stat_ok("GRW", ListStats::Growthrate); + assert_stat_ok("Growth", ListStats::Growthrate); + stats.get_field(ListStats::Growthrate.into()); + + // Crime + assert_stat_ok("cri", ListStats::Crime); + assert_stat_ok("CRIM", ListStats::Crime); + assert_stat_ok("Crimes", ListStats::Crime); + stats.get_field(ListStats::Crime.into()); + + // Happiness + assert_stat_ok("hapn", ListStats::Happiness); + assert_stat_ok("HAPPINES", ListStats::Happiness); + assert_stat_ok("hap", ListStats::Happiness); + stats.get_field(ListStats::Happiness.into()); + + // Economy + assert_stat_ok("eco", ListStats::Economy); + assert_stat_ok("Economy", ListStats::Economy); + assert_stat_ok("econ", ListStats::Economy); + stats.get_field(ListStats::Economy.into()); + + // Food + assert_stat_ok("food", ListStats::Food); + assert_stat_ok("fo", ListStats::Food); + assert_stat_ok("agr", ListStats::Food); + assert_stat_ok("agri", ListStats::Food); + stats.get_field(ListStats::Food.into()); + + // Industry + assert_stat_ok("industry", ListStats::Industry); + assert_stat_ok("Indus", ListStats::Industry); + assert_stat_ok("ind", ListStats::Industry); + stats.get_field(ListStats::Industry.into()); + + // Science + assert_stat_ok("science", ListStats::Science); + assert_stat_ok("sci", ListStats::Science); + assert_stat_ok("sc", ListStats::Science); + stats.get_field(ListStats::Science.into()); + + // Trade + assert_stat_ok("trade", ListStats::Trade); + assert_stat_ok("trd", ListStats::Trade); + assert_stat_ok("tr", ListStats::Trade); + stats.get_field(ListStats::Trade.into()); + + // Social + assert_stat_ok("social", ListStats::Social); + assert_stat_ok("soc", ListStats::Social); + assert_stat_ok("sl", ListStats::Social); + stats.get_field(ListStats::Social.into()); + + // Culture + assert_stat_ok("culture", ListStats::Culture); + assert_stat_ok("cul", ListStats::Culture); + assert_stat_ok("cl", ListStats::Culture); + stats.get_field(ListStats::Culture.into()); + + // Education + assert_stat_ok("education", ListStats::Education); + assert_stat_ok("edu", ListStats::Education); + assert_stat_ok("ed", ListStats::Education); + stats.get_field(ListStats::Education.into()); + + // Tourism + assert_stat_ok("tourism", ListStats::Tourism); + assert_stat_ok("tour", ListStats::Tourism); + assert_stat_ok("tm", ListStats::Tourism); + stats.get_field(ListStats::Tourism.into()); + + // Influence + assert_stat_ok("influence", ListStats::Influence); + assert_stat_ok("infl", ListStats::Influence); + assert_stat_ok("influ", ListStats::Influence); + stats.get_field(ListStats::Influence.into()); + + // Military + assert_stat_ok("military", ListStats::Military); + assert_stat_ok("mil", ListStats::Military); + assert_stat_ok("mt", ListStats::Military); + stats.get_field(ListStats::Military.into()); + + // Army + assert_stat_ok("army", ListStats::Army); + assert_stat_ok("arm", ListStats::Army); + assert_stat_ok("ar", ListStats::Army); + stats.get_field(ListStats::Army.into()); + + // Strength + assert_stat_ok("strength", ListStats::Strength); + assert_stat_ok("str", ListStats::Strength); + assert_stat_ok("st", ListStats::Strength); + stats.get_field(ListStats::Strength.into()); + + // Fortification + assert_stat_ok("fortification", ListStats::Fortification); + assert_stat_ok("fort", ListStats::Fortification); + assert_stat_ok("ft", ListStats::Fortification); + stats.get_field(ListStats::Fortification.into()); + + // Threat + assert_stat_ok("threat", ListStats::Threat); + assert_stat_ok("thr", ListStats::Threat); + assert_stat_ok("th", ListStats::Threat); + stats.get_field(ListStats::Threat.into()); + + // Infrastructure + assert_stat_ok("infrastructure", ListStats::Infrastructure); + assert_stat_ok("infra", ListStats::Infrastructure); + assert_stat_ok("infr", ListStats::Infrastructure); + stats.get_field(ListStats::Infrastructure.into()); + + // Bureaucracy + assert_stat_ok("bureaucracy", ListStats::Bureaucracy); + assert_stat_ok("bureau", ListStats::Bureaucracy); + assert_stat_ok("bur", ListStats::Bureaucracy); + stats.get_field(ListStats::Bureaucracy.into()); + + // Transportation + assert_stat_ok("transportation", ListStats::Transportation); + assert_stat_ok("trans", ListStats::Transportation); + assert_stat_ok("trns", ListStats::Transportation); + stats.get_field(ListStats::Transportation.into()); + + // Sprawl + assert_stat_ok("sprawl", ListStats::Sprawl); + assert_stat_ok("spr", ListStats::Sprawl); + assert_stat_ok("spra", ListStats::Sprawl); + stats.get_field(ListStats::Sprawl.into()); + + // Health + assert_stat_ok("health", ListStats::Health); + assert_stat_ok("hlth", ListStats::Health); + assert_stat_ok("hlt", ListStats::Health); + stats.get_field(ListStats::Health.into()); + } } -- 2.45.1 From 45d2cc495c5cfed4609a3bb78b3c1917790d53a2 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sun, 30 Nov 2025 14:56:10 +0100 Subject: [PATCH 11/22] Adds generic entities --- lib_efo/src/entity.rs | 19 +++++ lib_efo/src/lib.rs | 6 +- lib_efo/src/stats.rs | 108 ++++++++++++++++----------- lib_efo/src/stats/implementations.rs | 65 ++++++++++++++-- lib_efo/src/town.rs | 1 - 5 files changed, 144 insertions(+), 55 deletions(-) create mode 100644 lib_efo/src/entity.rs delete mode 100644 lib_efo/src/town.rs diff --git a/lib_efo/src/entity.rs b/lib_efo/src/entity.rs new file mode 100644 index 0000000..d841042 --- /dev/null +++ b/lib_efo/src/entity.rs @@ -0,0 +1,19 @@ +//! All the structs and logic surrounding entities +//! +//! + +use serde::{Deserialize, Serialize}; + +use crate::stats::{EntityType, MetaStats, OverallStats}; + +/// Fundamentaly everything is an entity, this can be error prone but the reduction of code duplication makes it worth it right now +/// Traits and thin structs could solve this but this will be added later and will be greatly simplified by the existence of the sub structs holding all the logic +#[derive(Serialize, Deserialize)] +pub struct Entity { + /// The stats of the entity, holding all the logic + stats: OverallStats, + /// Meta information + metadata: MetaStats, + /// Enum listing all entity types, this is bound to disapear in favor Typed Etities lateer + entity_type: EntityType, +} diff --git a/lib_efo/src/lib.rs b/lib_efo/src/lib.rs index a9a8e92..f18c370 100644 --- a/lib_efo/src/lib.rs +++ b/lib_efo/src/lib.rs @@ -20,11 +20,11 @@ #![warn(missing_docs, clippy::missing_docs_in_private_items)] #![deny(clippy::unwrap_used)] -pub mod epoch; -pub mod stats; -pub mod town; #[macro_use] pub mod error; +pub mod entity; +pub mod epoch; +pub mod stats; pub mod utils; use std::io::Result as IoResult; diff --git a/lib_efo/src/stats.rs b/lib_efo/src/stats.rs index 7e5ad13..dc73c6f 100644 --- a/lib_efo/src/stats.rs +++ b/lib_efo/src/stats.rs @@ -16,7 +16,8 @@ use cli_table::Table; use colored::Colorize; use derive_more::Display; use serde::{Deserialize, Serialize}; -use uuid::Uuid; + +use crate::thin_newtype; mod implementations; /// Aggregated statistics for a single entity. @@ -27,7 +28,7 @@ mod implementations; // Derive more #[derive(Table)] // #[derive(Add, Sub)] -struct OverallStats { +pub struct OverallStats { // ──────────────────────── Demographics ──────────────────────── /// Total economic health of the entity. /// @@ -211,8 +212,8 @@ struct OverallStats { /// /// All fields are intentionally simple – the logic that interprets them /// lives in separate modules (e.g. `map`, `network`, `governance`). -#[derive(Debug, Clone, Default)] -pub struct Strategics { +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub struct MetaStats { // ──── Location & Spatial Data (hidden) ─────────────────────────────── /// Cartesian coordinates of the entity on the world map. /// @@ -220,31 +221,26 @@ pub struct Strategics { /// **Effect** – Used for distance calculations, visibility, and /// map‑based event logic. /// **Source** – Supplied by the map generator. - pub position: (usize, usize), + pub position: Position, - /// Euclidean distance to the empire’s capital (in tile units). - /// - /// **Purpose** – Metric of remoteness from the political centre. - /// **Effect** – Influences trade costs, supply‑line strength, - /// and the range of early‑warning signals. - /// **Source** – `distance_to_capital = dist(position, capital_position)`. - pub distance_to_capital: usize, + /// Identifier for the capital + pub capital: 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, + // /// 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, - /// 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, + // /// 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. @@ -253,23 +249,22 @@ pub struct Strategics { /// **Effect** – Adds personal bonuses and may modify policies /// or diplomatic stance. /// **Source** – `governor = selected_leader_uuid`. - pub governor: Uuid, - - /// 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, + pub governor: 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: Uuid, + pub faction: FactionId, /// UIDs of all entities the entity is linked to (roads, trade routes, /// alliances, war declarations, etc.). @@ -279,7 +274,7 @@ pub struct Strategics { /// interactions. /// **Source** – `links = Vec` collected from the entity’s /// network manager. - pub links: Vec, + pub links: Vec, /// Prestige / reputation of the entity in the eyes of the empire /// and foreign powers. @@ -291,6 +286,21 @@ pub struct Strategics { pub prestige: usize, } +/// Structure used to indicate position, possess nice helper methods to use as is in the program +#[derive(Debug, Default, Serialize, Deserialize, Clone)] +pub struct Position(isize, isize); + +impl Position { + /// The euclidian distance between two points + fn distance(&self, other: &Self) -> isize { + ((self.0 - other.0).pow(2) + (self.1 * other.1).pow(2)).isqrt() + } + + /// The position in grid coordinates + fn to_grid_distance(&self) -> (isize, isize) { + (self.0 / 200, self.1 / 200) + } +} /// A summary of the stats, only for display purposes #[allow(clippy::missing_docs_in_private_items)] #[derive(Table)] @@ -338,19 +348,31 @@ pub enum ListStats { Health, } -// fn print_generic_stat() -/// A stat that is shown to the player *and* can be modified manually. +/// The list of all types of entities #[allow(missing_docs)] -#[derive(Debug, Clone, Default, Serialize, Deserialize, Display)] -pub struct GenericStat { - pub value: isize, +#[derive(Serialize, Deserialize)] +pub enum EntityType { + Character, + Player, + Town, + Monster, + Blocker, + Event, } -/// --- TRAITS --------------------------------------------------------------- +// A stat that is shown to the player *and* can be modified manually. +thin_newtype!(GenericStat, isize); +thin_newtype!(TownId, usize); +thin_newtype!(CharacterId, usize); +thin_newtype!(FactionId, usize); + +// --- TRAITS --------------------------------------------------------------- /// A stat is a *game value* that can be converted to two different /// normalised ranges – a 50‑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_50(&self) -> isize { diff --git a/lib_efo/src/stats/implementations.rs b/lib_efo/src/stats/implementations.rs index 508cfd2..091627e 100644 --- a/lib_efo/src/stats/implementations.rs +++ b/lib_efo/src/stats/implementations.rs @@ -9,6 +9,55 @@ use crate::stats::GenericStat; use crate::stats::ListStats; use crate::stats::OverallStats; +/// Creates a thin, deref‑able wrapper around an inner type. +#[macro_export] +macro_rules! thin_newtype { + ($name:ident, $inner:ty) => { + /// Thin wrapper that derefs to the inner type. + /// Ideal for zero‑overhead new‑type patterns. + #[repr(transparent)] + #[derive( + Debug, + Clone, + Default, + PartialEq, + Eq, + PartialOrd, + Ord, + Hash, + Serialize, + Deserialize, + Display, + )] + pub struct $name(pub $inner); + + impl std::ops::Deref for $name { + type Target = $inner; + fn deref(&self) -> &Self::Target { + &self.0 + } + } + + impl std::ops::DerefMut for $name { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } + } + + impl From<$inner> for $name { + fn from(v: $inner) -> Self { + $name(v) + } + } + + impl From<$name> for $inner { + fn from(v: $name) -> Self { + v.0 + } + } + }; +} + /// Generates an `impl GameStat for ` where the only difference between /// multiple implementations is the visibility level. /// @@ -19,18 +68,18 @@ macro_rules! impl_game_stat { ($type:ident) => { impl GameStat for $type { fn get_value(&self) -> isize { - self.value + self.0 } fn change_value(&mut self, value: isize) { - self.value = value; + self.0 = value; } fn from_value(value: isize) -> Self where Self: Sized, { - Self { value } + Self(value) } } }; @@ -181,7 +230,7 @@ impl FromStr for StatPair { let value: isize = val_str .parse() .map_err(|_| EpochError::IllFormedStatQualifier(val_str.to_owned()))?; - Ok(StatPair(stat, stats::GenericStat { value })) + Ok(StatPair(stat, stats::GenericStat(value))) } } @@ -210,9 +259,9 @@ pub(crate) mod test { #[test] fn test_field_accessors() { let person = Person { - name: GenericStat { value: 10 }, - age: GenericStat { value: 20 }, - email: GenericStat { value: 70 }, + name: GenericStat(10), + age: GenericStat(20), + email: GenericStat(70), }; let name = person.get_field("name").unwrap(); let email = person.get_field("email").unwrap(); @@ -228,7 +277,7 @@ pub(crate) mod test { fn assert_pair_ok(input: &str, expected_stat: ListStats, expected_val: isize) { let pair = StatPair::from_str(input).expect("should parse"); assert_eq!(pair.0, expected_stat, "stat mismatch"); - assert_eq!(pair.1.value, expected_val, "value mismatch"); + assert_eq!(pair.1.0, expected_val, "value mismatch"); } #[test] fn test_stat_pair_parsing() { diff --git a/lib_efo/src/town.rs b/lib_efo/src/town.rs deleted file mode 100644 index 30d2a85..0000000 --- a/lib_efo/src/town.rs +++ /dev/null @@ -1 +0,0 @@ -//! All the structs and logic surrounding towns -- 2.45.1 From 822281db3c7c1dd64210eb0e83844c0b050b5771 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sun, 30 Nov 2025 17:10:30 +0100 Subject: [PATCH 12/22] Adds rng/naming --- Cargo.lock | 60 +++ bin_efo/src/main.rs | 12 + lib_efo/Cargo.toml | 2 + lib_efo/naming.json | 551 +++++++++++++++++++++++++++ lib_efo/src/lib.rs | 1 + lib_efo/src/naming.rs | 183 +++++++++ lib_efo/src/stats.rs | 9 +- lib_efo/src/stats/implementations.rs | 6 +- 8 files changed, 818 insertions(+), 6 deletions(-) create mode 100644 lib_efo/naming.json create mode 100644 lib_efo/src/naming.rs diff --git a/Cargo.lock b/Cargo.lock index 43dc96f..c87971d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -373,6 +373,8 @@ dependencies = [ "env_logger", "log", "miette", + "once_cell", + "rand", "serde", "serde_json", "thiserror", @@ -484,6 +486,15 @@ dependencies = [ "portable-atomic", ] +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + [[package]] name = "proc-macro2" version = "1.0.103" @@ -508,6 +519,35 @@ version = "5.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" +[[package]] +name = "rand" +version = "0.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6db2770f06117d490610c7488547d543617b21bfa07796d7a12f6f1bd53850d1" +dependencies = [ + "rand_chacha", + "rand_core", +] + +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "99d9a13982dcf210057a8a78572b2217b667c3beacbf3a0d8b454f6f82837d38" +dependencies = [ + "getrandom", +] + [[package]] name = "regex" version = "1.12.2" @@ -976,3 +1016,23 @@ name = "wit-bindgen" version = "0.46.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f17a85883d4e6d00e8a97c586de764dabcc06133f7f1d55dce5cdc070ad7fe59" + +[[package]] +name = "zerocopy" +version = "0.8.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea879c944afe8a2b25fef16bb4ba234f47c694565e97383b36f3a878219065c" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf955aa904d6040f70dc8e9384444cb1030aed272ba3cb09bbc4ab9e7c1f34f5" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] diff --git a/bin_efo/src/main.rs b/bin_efo/src/main.rs index 5182d77..e7f70c2 100644 --- a/bin_efo/src/main.rs +++ b/bin_efo/src/main.rs @@ -23,6 +23,7 @@ #![warn(missing_docs, clippy::missing_docs_in_private_items)] #![deny(clippy::unwrap_used)] use clap::{ArgAction, Parser, Subcommand}; +use lib_efo::naming::NAMING; use crate::commands::init::InitCmd; use crate::{commands::epoch::cli_epoch::EpochCmd, error::AppError}; @@ -72,6 +73,17 @@ enum TopLevelCmd { /// in stdout and returned as a `miette::Result<()>`. fn main() -> miette::Result<()> { env_logger::init(); + // 1. Generate a character name + let character = NAMING.generate_character_name(); + println!("Character: {}", character); + + // 2. Generate a town name + let town = NAMING.generate_town_name(); + println!("Town: {}", town); + + // 3. Pick an event idea + let event = NAMING.generate_long_character_name(); + println!("Event idea: {}", event); let cli = Cli::parse(); if let Err(e) = exec_dispatch(cli) { diff --git a/lib_efo/Cargo.toml b/lib_efo/Cargo.toml index 99817c4..624361b 100644 --- a/lib_efo/Cargo.toml +++ b/lib_efo/Cargo.toml @@ -15,3 +15,5 @@ derive_more = {workspace = true} cli-table = "0.5.0" uuid = { version = "1.18.1", features = ["serde", "v4"] } colored = "3.0.0" +rand = "0.9.2" +once_cell = "1.21.3" diff --git a/lib_efo/naming.json b/lib_efo/naming.json new file mode 100644 index 0000000..808a66d --- /dev/null +++ b/lib_efo/naming.json @@ -0,0 +1,551 @@ +{ + "first_names": [ + "Aeron", + "Brienne", + "Cedric", + "Darya", + "Eldon", + "Fiora", + "Galen", + "Hela", + "Ivor", + "Juno", + "Aldric", + "Briar", + "Caelum", + "Dorin", + "Elysia", + "Fendrel", + "Gryphon", + "Hector", + "Iseult", + "Kael", + "Lysander", + "Morgath", + "Nyx", + "Odin", + "Riven", + "Sylvan", + "Thorne", + "Valen", + "Wraith", + "Xander", + "Yara", + "Zarek", + "Artemis", + "Baldric", + "Corvin", + "Draven", + "Eira", + "Fenris", + "Gale", + "Helios", + "Ivy", + "Jasper", + "Kara", + "Luna", + "Mira", + "Nimrod", + "Onyx", + "Peregrine", + "Quinn", + "Aegon", + "Brek", + "Calandra", + "Darrion", + "Eryndor", + "Fenn", + "Galax", + "Hestia", + "Ilarion", + "Jareth", + "Kassandra", + "Lyris", + "Maelor", + "Nyssa", + "Oren", + "Phaedra", + "Quillon", + "Rhea", + "Soren", + "Thalia", + "Uther", + "Vesper", + "Wulfric", + "Xara", + "Yoren", + "Zorath", + "Aerith", + "Baldrick", + "Cress", + "Dazai", + "Elara", + "Fira" + ], + "last_names": [ + "Ashwood", + "Blackthorn", + "Cinderglow", + "Dunwynn", + "Everfield", + "Frosthelm", + "Goldleaf", + "Holloway", + "Iverson", + "Jasper", + "Ravencrest", + "Stormblade", + "Nightshade", + "Wraithborne", + "Dreadmoor", + "Ironhart", + "Bloodstone", + "Stonegate", + "Gloomreach", + "Sablewick", + "Rookhaven", + "Ironcrest", + "Bleakmoor", + "Thornshield", + "Wyrmwood", + "Darkwater", + "Stormbreaker", + "Ebonhart", + "Bloodbane", + "Eclipseborne", + "Firethorn", + "Silvershade", + "Blackfrost", + "Sorrowblade", + "Stonehelm", + "Gravelock", + "Voidwalker", + "Nightfall", + "Ashenfall", + "Ashenridge", + "Duskfall", + "Thornhaven", + "Gloombreaker", + "Riftwalker", + "Althmar", + "Brimstone", + "Cinderfall", + "Duskbane", + "Emberforge", + "Frostbane", + "Grimsbane", + "Ironbark", + "Jaggedspire", + "Keldrith", + "Lament", + "Mistveil", + "Nightglow", + "Oathbreaker", + "Palegrave", + "Quicksilver", + "Riftshard", + "Shadowforge", + "Thornbane", + "Umbral", + "Vengeance", + "Wraithbane", + "Xylander", + "Yester", + "Zephyr", + "Blackfire", + "Bloodthorn", + "Crimsonveil", + "Dreadspire", + "Eboncrest", + "Firebrand", + "Grimshard", + "Ironheart", + "Javelin", + "Krait", + "Luminous", + "Marrowbone", + "Nocturne", + "Obsidian", + "Pyre", + "Quagmire", + "Reaver", + "Sableheart", + "Tidebreaker" + ], + "town_prefixes": [ + "Ash", + "Bright", + "Cedar", + "Deep", + "Elder", + "Frost", + "Glen", + "High", + "Iron", + "Jade", + "Ashen", + "Blood", + "Cobalt", + "Dusk", + "Ebon", + "Gloom", + "Ironforge", + "Keen", + "Mourn", + "Raven", + "Storm", + "Void", + "Wraith", + "Night", + "Silvers", + "Black", + "Crimson", + "Fire", + "Grim", + "Briar", + "Obsidian", + "Shade", + "Thorn", + "Sable", + "Rift", + "Dread", + "Sorrow", + "Bleak", + "Eclipse", + "Eternity", + "Glint", + "Gleam", + "Hollow", + "Lament", + "Mire", + "Molt", + "Nocturne", + "Onyx", + "Pale", + "Rook", + "Shimmer", + "Stonem", + "Stone", + "Stonehold", + "Stonekeep", + "Stoneforge", + "Stormfall", + "Stormgate", + "Stormhold", + "Stormreach", + "Stormspire", + "Stormwind", + "Throne", + "Twilight", + "Valiant", + "Valest", + "Valer", + "Vex", + "Vile", + "Warden" + ], + "town_suffixes": [ + "brook", + "dale", + "field", + "haven", + "keep", + "moor", + "port", + "reach", + "stone", + "vale", + "forge", + "shard", + "hollow", + "cove", + "hall", + "watch", + "spire", + "glade", + "cliff", + "glen", + "tower", + "fort", + "hold", + "bastion", + "crypt", + "crossing", + "crown", + "ridge", + "fell", + "breach", + "briar", + "bloom", + "field", + "river", + "canyon", + "fen", + "crag", + "gate", + "bridge", + "watchtower", + "watcher", + "mire", + "waste", + "breach", + "fall", + "crone", + "shadow", + "veil", + "blight", + "soul", + "night", + "storm", + "fire", + "ice", + "iron", + "dark", + "glimmer", + "glare", + "scar", + "scarred", + "spire", + "peak", + "ridge", + "hall", + "hold", + "spire", + "vale", + "vale", + "haven", + "hollow", + "breach", + "crust" + ], + "character_adjectives": [ + "the Blind", + "the Magnificent", + "the Cunning", + "the Swift", + "the Stoic", + "the Fearless", + "the Enigmatic", + "the Shadow", + "the Light", + "the Wanderer", + "the Unbroken", + "the Relentless", + "the Ruthless", + "the Merciless", + "the Devourer", + "the Ancient", + "the Fallen", + "the Immortal", + "the Vengeful", + "the Stormborn", + "the Silent", + "the Bloodied", + "the Corrupt", + "the Darkened", + "the Ember", + "the Crimson", + "the Iron", + "the Sable", + "the Radiant", + "the Tempest", + "the Gloom", + "the Warlord", + "the Titan", + "the Behemoth", + "the Leviathan", + "the Doombringer", + "the Wraith", + "the Sundered", + "the Gloomstalker", + "the Blight", + "the Harbinger", + "the Abyssal", + "the Scourge", + "the Dread", + "the Fury", + "the Specter", + "the Maw", + "the Protector", + "the Guardian", + "the Champion", + "the Savior", + "the Reaper", + "the Harvester", + "the Seeker", + "the Whisperer", + "the Tempest‑born", + "the Iron‑clad", + "the Moonlit", + "the Sun‑scarred", + "the Bone‑choked", + "the Frost‑kissed", + "the Ashen", + "the Shattered", + "the Echo‑bound", + "the Vile", + "the Harsh", + "the Unseen", + "the Unyielding", + "of the North", + "of the South", + "of the East", + "of the West", + "of the Dark", + "of the Light", + "of the Forgotten", + "of the Broken", + "of the Eternal", + "of the Shadowlands", + "of the Burning", + "of the Frozen", + "of the Storm", + "of the Depths", + "of the Maw", + "of the Ashen Sea", + "of the Crimson Dawn" + ], + "character_prefixes": [ + "Sir", + "Lady", + "Mighty", + "Elder", + "Grand", + "Humble", + "Radiant", + "Lord", + "High", + "Royal", + "Ancient", + "Warden", + "Seer", + "Master" + ], + "event_ideas": [ + { + "name": "storm_flood", + "description": "A sudden storm floods the river, threatening the local farms.", + "stats": [ + { "stat": "Population", "value": -5 }, + { "stat": "Food", "value": -12 } + ] + }, + { + "name": "earthquake", + "description": "A massive quake ripples across the continent, cracking roads and collapsing half the cities.", + "stats": [ + { "stat": "Infrastructure", "value": -15 }, + { "stat": "Population", "value": -10 }, + { "stat": "Happiness", "value": -8 } + ] + }, + { + "name": "region_blood_monsoon", + "description": "A crimson rain falls over the region, poisoning crops and water sources.", + "stats": [ + { "stat": "Food", "value": -18 }, + { "stat": "Health", "value": -12 }, + { "stat": "Population", "value": -7 } + ] + }, + { + "name": "town_haunted_market", + "description": "Spectral merchants appear, selling wares that vanish upon purchase, driving up prices.", + "stats": [ + { "stat": "Trade", "value": -9 }, + { "stat": "Economy", "value": -6 }, + { "stat": "Crime", "value": 4 } + ] + }, + { + "name": "region_darkening_sun", + "description": "The sky is forever shrouded in an unnatural pallid dusk, lowering morale and crop yields.", + "stats": [ + { "stat": "Happiness", "value": -14 }, + { "stat": "Food", "value": -10 }, + { "stat": "Culture", "value": -5 } + ] + }, + { + "name": "town_giant_earthworm", + "description": "A colossal earthworm burrows beneath the town, destabilizing foundations and causing tremors.", + "stats": [ + { "stat": "Infrastructure", "value": -12 }, + { "stat": "Fortification", "value": -8 }, + { "stat": "Population", "value": -4 } + ] + }, + { + "name": "region_arcane_surge", + "description": "An uncontrollable surge of raw sangressence tears through reality, causing unpredictable effects.", + "stats": [ + { "stat": "Science", "value": 12 }, + { "stat": "Education", "value": 8 }, + { "stat": "Population", "value": -6 } + ] + }, + { + "name": "town_mushroom_meteor", + "description": "A meteor of colossal fungi explodes over a town, releasing spores that induce vivid hallucinations.", + "stats": [ + { "stat": "Health", "value": -10 }, + { "stat": "Crime", "value": 6 }, + { "stat": "Population", "value": -3 } + ] + }, + { + "name": "region_infernal_flood", + "description": "Molten rivers run through the region, boiling over cities and devouring forests.", + "stats": [ + { "stat": "Infrastructure", "value": -20 }, + { "stat": "Food", "value": -15 }, + { "stat": "Population", "value": -12 } + ] + }, + { + "name": "region_sand_vortex", + "description": "A vortex of shifting sands sweeps the region, burying entire nations under dunes.", + "stats": [ + { "stat": "Infrastructure", "value": -14 }, + { "stat": "Population", "value": -16 }, + { "stat": "Trade", "value": -10 } + ] + }, + { + "name": "town_fall_of_mages", + "description": "A rogue wizard unleashes a catastrophic spell, destroying a town's center and leaving a scar in reality.", + "stats": [ + { "stat": "Science", "value": -8 }, + { "stat": "Population", "value": -10 }, + { "stat": "Fortification", "value": -6 } + ] + }, + { + "name": "region_wind_of_gods", + "description": "A relentless gale from the gods tears through the region, scattering armies and wrecking supply lines.", + "stats": [ + { "stat": "Transportation", "value": -12 }, + { "stat": "Military", "value": -9 }, + { "stat": "Population", "value": -3 } + ] + }, + { + "name": "region_ancient_sunrise", + "description": "The sun rises in a crimson glow, amplifying the power of all dark cults and spreading fear.", + "stats": [ + { "stat": "Crime", "value": 9 }, + { "stat": "Happiness", "value": -8 }, + { "stat": "Influence", "value": -5 } + ] + }, + { + "name": "town_forest_of_eyes", + "description": "A forest that watches every step, slowly siphoning the life force from any who walk through.", + "stats": [ + { "stat": "Health", "value": -10 }, + { "stat": "Crime", "value": 7 }, + { "stat": "Population", "value": -5 } + ] + } + ] +} diff --git a/lib_efo/src/lib.rs b/lib_efo/src/lib.rs index f18c370..d46903f 100644 --- a/lib_efo/src/lib.rs +++ b/lib_efo/src/lib.rs @@ -24,6 +24,7 @@ pub mod error; pub mod entity; pub mod epoch; +pub mod naming; pub mod stats; pub mod utils; diff --git a/lib_efo/src/naming.rs b/lib_efo/src/naming.rs new file mode 100644 index 0000000..1d24bcd --- /dev/null +++ b/lib_efo/src/naming.rs @@ -0,0 +1,183 @@ +//! Autonaming generator +//! Supposed to be loaded with the world if needed +use once_cell::sync::Lazy; +use rand::prelude::*; +use serde::{Deserialize, Serialize}; +use std::fs; +use std::io; +use std::path::{Path, PathBuf}; + +use crate::stats::StatPair; + +/// The structure that holds everything we need for name generation. +#[derive(Debug, Serialize, Deserialize)] +pub struct NamingData { + /// First name for characters + pub first_names: Vec, + /// Last names for characters + pub last_names: Vec, + /// Good prefixes for towns + pub town_prefixes: Vec, + /// Good suffixes for town names + pub town_suffixes: Vec, + + /// Character adjectives + pub character_adjectives: Vec, + /// Name prefixes + pub character_prefixes: Vec, + + /// A list of event ideas and characteristic associated to it + pub event_ideas: Vec, +} + +#[derive(Debug, Serialize, Deserialize)] +/// An event with a description +pub struct EventDescription { + /// A short and meaninful name (an id of a sort) + pub name: String, + + /// A short description of the event + pub description: String, + + /// The stats affected by the event, and how much (-20 to +20) (100 being the maximum of a stat, event a change of -10 is meaningful) + pub stats: Vec, +} + +// /// A generic stat pair with (stat, value), used mainly for clap +// /// Accepts two forms +// /// 1. "cri 10" (two separate tokens) +// /// 2. "cri:10" (one token with a separator) +// pub struct StatPair(ListStats, GenericStat); +// +// 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, +// } + +impl NamingData { + /// Load the data from the supplied path. + /// If the file does **not** exist, a default (embedded) version is written + /// to that path and returned. + pub fn load_or_create>(path: P) -> io::Result { + let path = path.as_ref(); + + if path.exists() { + // File exists → read & parse + let contents = fs::read_to_string(path)?; + let data: Self = serde_json::from_str(&contents)?; + Ok(data) + } else { + // File does *not* exist → create from embedded default + let default = + serde_json::from_str(DEFAULT_JSON_STR).expect("Default JSON is malformed"); + // Ensure parent dirs exist + if let Some(parent) = path.parent() { + fs::create_dir_all(parent)?; + } + let json = serde_json::to_string_pretty(&default)?; + fs::write(path, json)?; + Ok(default) + } + } + + /// Generate a random **character** name. + pub fn generate_character_name(&self) -> String { + let mut rng = rand::rng(); + + let binding = "Unnamed".into(); + let first = self.first_names.choose(&mut rng).unwrap_or(&binding); + let binding = "".into(); + let last = self.last_names.choose(&mut rng).unwrap_or(&binding); + format!("{} {}", first, last).trim().to_string() + } + + /// Generate a random **town** name. + pub fn generate_town_name(&self) -> String { + let mut rng = rand::rng(); + let binding = "".into(); + let prefix = self.town_prefixes.choose(&mut rng).unwrap_or(&binding); + let suffix = self.town_suffixes.choose(&mut rng).unwrap_or(&binding); + format!("{}{}", prefix, suffix).trim().to_string() + } + + // /// Pick a random event idea (you can reuse this or make a dedicated method). + // pub fn random_event_idea(&self) -> &str { + // let mut rng = rand::rng(); + // self.event_ideas + // .choose(&mut rng) + // .map(String::as_str) + // .unwrap_or("No Event.") + // } + + /// Generates something like: + /// “The Magnificent Sir Aurelius Blackthorn the Swift” + /// Random adjective, prefix, base name and suffix are all optional. + /// If a list is empty, that part is omitted. + pub fn generate_long_character_name(&self) -> String { + let mut rng = rand::rng(); + + // Helper: get a random element or None + let adjective = self.character_adjectives.choose(&mut rng).cloned(); + let prefix = self.character_prefixes.choose(&mut rng).cloned(); + + // Base name (first + last) + let base = self.generate_character_name(); + + // Assemble pieces + let mut parts = Vec::new(); + + if let Some(pre) = prefix + && rand::random_bool(0.3) + { + parts.push(pre); + } + + parts.push(base); + + if let Some(adj) = adjective + && rand::random_bool(0.3) + { + parts.push(adj); + } + + parts.join(" ") + } +} + +/// The JSON that ships with the binary. +/// `include_str!` pulls the file at compile time. +const DEFAULT_JSON_STR: &str = include_str!("../naming.json"); + +/// Helper that determines the *runtime* location of the `naming.json` file. +fn naming_file_path() -> PathBuf { + PathBuf::from("naming.json") +} + +/// Global instance that is lazily initialised on first use. +pub static NAMING: Lazy = Lazy::new(|| { + let path = naming_file_path(); + NamingData::load_or_create(path).expect("Failed to load naming data") +}); diff --git a/lib_efo/src/stats.rs b/lib_efo/src/stats.rs index dc73c6f..e74555d 100644 --- a/lib_efo/src/stats.rs +++ b/lib_efo/src/stats.rs @@ -286,6 +286,13 @@ pub struct MetaStats { pub prestige: usize, } +/// A generic stat pair with (stat, value), 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)] +pub struct StatPair(ListStats, GenericStat); + /// Structure used to indicate position, possess nice helper methods to use as is in the program #[derive(Debug, Default, Serialize, Deserialize, Clone)] pub struct Position(isize, isize); @@ -318,7 +325,7 @@ pub struct SummaryStats { } /// Bridge between the CLI and the statistics logic. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] #[allow(missing_docs)] pub enum ListStats { Demographics, diff --git a/lib_efo/src/stats/implementations.rs b/lib_efo/src/stats/implementations.rs index 091627e..5eabfcb 100644 --- a/lib_efo/src/stats/implementations.rs +++ b/lib_efo/src/stats/implementations.rs @@ -8,6 +8,7 @@ use crate::stats::GameStat; use crate::stats::GenericStat; use crate::stats::ListStats; use crate::stats::OverallStats; +use crate::stats::StatPair; /// Creates a thin, deref‑able wrapper around an inner type. #[macro_export] @@ -207,11 +208,6 @@ impl From for &str { } } -/// A generic stat pair with (stat, value), used mainly for clap -/// Accepts two forms -/// 1. "cri 10" (two separate tokens) -/// 2. "cri:10" (one token with a separator) -pub struct StatPair(ListStats, GenericStat); impl FromStr for StatPair { type Err = EpochError; -- 2.45.1 From 8043e6bd56eba48289144a129032515c8053f495 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sun, 30 Nov 2025 18:10:25 +0100 Subject: [PATCH 13/22] Still on naming --- bin_efo/src/main.rs | 2 + lib_efo/naming.json | 507 ++++++++++++++++++++++++++- lib_efo/src/naming.rs | 81 ++--- lib_efo/src/stats.rs | 7 +- lib_efo/src/stats/implementations.rs | 9 +- 5 files changed, 549 insertions(+), 57 deletions(-) diff --git a/bin_efo/src/main.rs b/bin_efo/src/main.rs index e7f70c2..018696c 100644 --- a/bin_efo/src/main.rs +++ b/bin_efo/src/main.rs @@ -22,6 +22,7 @@ #![warn(missing_docs, clippy::missing_docs_in_private_items)] #![deny(clippy::unwrap_used)] + use clap::{ArgAction, Parser, Subcommand}; use lib_efo::naming::NAMING; @@ -71,6 +72,7 @@ enum TopLevelCmd { /// Parses the command‑line arguments and dispatches to the selected /// sub‑command. Errors returned by the sub‑command handlers are shown /// in stdout and returned as a `miette::Result<()>`. +#[allow(clippy::unwrap_used)] fn main() -> miette::Result<()> { env_logger::init(); // 1. Generate a character name diff --git a/lib_efo/naming.json b/lib_efo/naming.json index 808a66d..ebcba9f 100644 --- a/lib_efo/naming.json +++ b/lib_efo/naming.json @@ -432,7 +432,7 @@ }, { "name": "earthquake", - "description": "A massive quake ripples across the continent, cracking roads and collapsing half the cities.", + "description": "A massive quake ripples across the region.", "stats": [ { "stat": "Infrastructure", "value": -15 }, { "stat": "Population", "value": -10 }, @@ -511,15 +511,6 @@ { "stat": "Trade", "value": -10 } ] }, - { - "name": "town_fall_of_mages", - "description": "A rogue wizard unleashes a catastrophic spell, destroying a town's center and leaving a scar in reality.", - "stats": [ - { "stat": "Science", "value": -8 }, - { "stat": "Population", "value": -10 }, - { "stat": "Fortification", "value": -6 } - ] - }, { "name": "region_wind_of_gods", "description": "A relentless gale from the gods tears through the region, scattering armies and wrecking supply lines.", @@ -546,6 +537,502 @@ { "stat": "Crime", "value": 7 }, { "stat": "Population", "value": -5 } ] + }, + { + "name": "city_corruption_scandal", + "description": "A high‑ranking magistrate is discovered embezzling city funds, sparking public outrage and a demand for accountability.", + "stats": [ + { "stat": "Economy", "value": -9 }, + { "stat": "Bureaucracy", "value": -7 }, + { "stat": "Crime", "value": 5 } + ] + }, + { + "name": "city_tax_reform", + "description": "The council implements a sweeping tax overhaul that raises revenue but triggers protests among merchants.", + "stats": [ + { "stat": "Economy", "value": 12 }, + { "stat": "Population", "value": -4 }, + { "stat": "Crime", "value": 3 } + ] + }, + { + "name": "city_watch_mutiny", + "description": "The city guard, disgruntled by unpaid wages, mutinies and seizes control of the main gate.", + "stats": [ + { "stat": "Military", "value": -6 }, + { "stat": "Crime", "value": 8 }, + { "stat": "Population", "value": -2 } + ] + }, + { + "name": "city_water_contamination", + "description": "Tainted water leaks into the municipal supply, causing a sudden spike in illnesses.", + "stats": [ + { "stat": "Health", "value": -14 }, + { "stat": "Population", "value": -5 }, + { "stat": "Bureaucracy", "value": -3 } + ] + }, + { + "name": "city_bureaucratic_bureaucracy", + "description": "A new procedural reform overhauls city administration, halting projects for months and stalling economic growth.", + "stats": [ + { "stat": "Infrastructure", "value": -7 }, + { "stat": "Economy", "value": -5 }, + { "stat": "Bureaucracy", "value": 10 } + ] + }, + { + "name": "city_guild_suppression", + "description": "The council cracks down on the city’s merchant guilds, confiscating goods and driving merchants underground.", + "stats": [ + { "stat": "Trade", "value": -11 }, + { "stat": "Crime", "value": 6 }, + { "stat": "Population", "value": -3 } + ] + }, + { + "name": "city_civic_riot", + "description": "An assembly of disgruntled workers erupts into a violent riot, tearing through market stalls and public buildings.", + "stats": [ + { "stat": "Infrastructure", "value": -12 }, + { "stat": "Happiness", "value": -9 }, + { "stat": "Crime", "value": 10 } + ] + }, + { + "name": "city_public_health_crisis", + "description": "A mysterious disease spreads through the city’s crowded streets, overwhelming the local infirmaries.", + "stats": [ + { "stat": "Health", "value": -16 }, + { "stat": "Population", "value": -8 }, + { "stat": "Happiness", "value": -7 } + ] + }, + { + "name": "city_transport_infrastructure_fail", + "description": "The city’s main aqueduct collapses, cutting off water supply to half the districts.", + "stats": [ + { "stat": "Infrastructure", "value": -15 }, + { "stat": "Population", "value": -4 }, + { "stat": "Bureaucracy", "value": -2 } + ] + }, + { + "name": "city_festival_corruption", + "description": "During a grand city festival, officials accept bribes to award contracts, compromising civic integrity.", + "stats": [ + { "stat": "Bureaucracy", "value": -8 }, + { "stat": "Crime", "value": 4 }, + { "stat": "Happiness", "value": -3 } + ] + }, + { + "name": "city_gold_exodus", + "description": "A sudden discovery of gold in the hinterlands draws merchants away, leaving local markets starved of currency.", + "stats": [ + { "stat": "Economy", "value": -11 }, + { "stat": "Trade", "value": -8 }, + { "stat": "Population", "value": -2 } + ] + }, + { + "name": "regional_drought", + "description": "An extended dry spell cripples crop yields, driving up food prices and crippling the agrarian economy.", + "stats": [ + { "stat": "Food", "value": -15 }, + { "stat": "Economy", "value": -9 }, + { "stat": "Happiness", "value": -5 } + ] + }, + { + "name": "city_tariff_levy", + "description": "The city council imposes a high tariff on imported goods to boost local industry, sparking backlash from merchants.", + "stats": [ + { "stat": "Trade", "value": -10 }, + { "stat": "Economy", "value": 7 }, + { "stat": "Crime", "value": 4 } + ] + }, + { + "name": "market_hoarding", + "description": "A powerful merchant cartel hoards staple goods, manipulating prices to inflate profits at the cost of ordinary citizens.", + "stats": [ + { "stat": "Economy", "value": -8 }, + { "stat": "Trade", "value": -7 }, + { "stat": "Population", "value": -3 } + ] + }, + { + "name": "industrial_explosion", + "description": "A catastrophic blast at the main ironworks destroys equipment and halts production for months.", + "stats": [ + { "stat": "Industry", "value": -18 }, + { "stat": "Economy", "value": -12 }, + { "stat": "Population", "value": -4 } + ] + }, + { + "name": "foreign_investment_boom", + "description": "A foreign dynasty invests heavily in local mining, sparking a surge in jobs and wealth but also widening inequality.", + "stats": [ + { "stat": "Industry", "value": 12 }, + { "stat": "Economy", "value": 9 }, + { "stat": "Crime", "value": 5 } + ] + }, + { + "name": "tax_evasion_scheme", + "description": "A sophisticated tax evasion network siphons off a large portion of city revenue, forcing austerity measures.", + "stats": [ + { "stat": "Economy", "value": -10 }, + { "stat": "Bureaucracy", "value": -6 }, + { "stat": "Population", "value": -2 } + ] + }, + { + "name": "currency_devaluation", + "description": "The city’s coinage is devalued by a sudden policy shift, causing imported goods to skyrocket in price.", + "stats": [ + { "stat": "Economy", "value": -13 }, + { "stat": "Trade", "value": -9 }, + { "stat": "Health", "value": -4 } + ] + }, + { + "name": "artisan_fair_success", + "description": "A grand artisan fair attracts wealthy patrons, boosting local crafts and increasing export revenues.", + "stats": [ + { "stat": "Industry", "value": 8 }, + { "stat": "Economy", "value": 6 }, + { "stat": "Population", "value": 2 } + ] + }, + { + "name": "resource_piracy", + "description": "Sea‑borne raiders seize a shipment of precious stones destined for the city, flooding the market with counterfeit goods.", + "stats": [ + { "stat": "Trade", "value": -12 }, + { "stat": "Economy", "value": -7 }, + { "stat": "Crime", "value": 9 } + ] + }, + { + "name": "steel_furnace_overheat", + "description": "A critical failure in the city’s primary steel furnace sparks an uncontrollable fire, destroying production lines.", + "stats": [ + { "stat": "Industry", "value": -17 }, + { "stat": "Economy", "value": -10 }, + { "stat": "Population", "value": -3 } + ] + }, + { + "name": "artisan_tech_innovation", + "description": "A guild of master craftsmen invents a new forging technique that doubles output and lowers raw material usage.", + "stats": [ + { "stat": "Industry", "value": 14 }, + { "stat": "Economy", "value": 8 }, + { "stat": "Crime", "value": 3 } + ] + }, + { + "name": "coal_mine_sabotage", + "description": "Covert saboteurs collapse a major coal shaft, halting fuel supply to all local factories for weeks.", + "stats": [ + { "stat": "Industry", "value": -15 }, + { "stat": "Economy", "value": -9 }, + { "stat": "Crime", "value": 6 } + ] + }, + { + "name": "foreign_factory_purchase", + "description": "A foreign conglomerate purchases the city’s largest textile mill, imposing new quotas that reduce local employment.", + "stats": [ + { "stat": "Industry", "value": -9 }, + { "stat": "Economy", "value": -7 }, + { "stat": "Population", "value": -4 } + ] + }, + { + "name": "blacksmiths_rebel", + "description": "Skilled blacksmiths organize a strike demanding better wages, halting the production of critical weapons.", + "stats": [ + { "stat": "Industry", "value": -10 }, + { "stat": "Military", "value": -5 }, + { "stat": "Crime", "value": 4 } + ] + }, + { + "name": "machine_revolution", + "description": "The introduction of automated presses in the leather works cuts labor costs but renders many artisans obsolete.", + "stats": [ + { "stat": "Industry", "value": 11 }, + { "stat": "Population", "value": -5 }, + { "stat": "Crime", "value": 3 } + ] + }, + { + "name": "bottleneck_transportation", + "description": "The city’s main rail line is seized by gangsters, disrupting the flow of raw materials to factories.", + "stats": [ + { "stat": "Infrastructure", "value": -8 }, + { "stat": "Industry", "value": -6 }, + { "stat": "Crime", "value": 7 } + ] + }, + { + "name": "energy_rationing", + "description": "A sudden spike in electricity prices forces factories to shut down during peak hours, halving output.", + "stats": [ + { "stat": "Industry", "value": -13 }, + { "stat": "Economy", "value": -8 }, + { "stat": "Population", "value": -2 } + ] + }, + { + "name": "export_tariff_relief", + "description": "An unexpected removal of export tariffs on metal goods opens new markets, boosting production rates.", + "stats": [ + { "stat": "Industry", "value": 12 }, + { "stat": "Trade", "value": 9 }, + { "stat": "Economy", "value": 6 } + ] + }, + { + "name": "smelter_piracy", + "description": "A band of raiders captures a shipment of precious ores destined for the city, flooding the market with cheap counterfeit.", + "stats": [ + { "stat": "Industry", "value": -11 }, + { "stat": "Trade", "value": -7 }, + { "stat": "Crime", "value": 10 } + ] + }, + { + "name": "frontline_betrayal", + "description": "A key vanguard commander secretly defects, scattering a significant portion of the army and boosting enemy threat.", + "stats": [ + { "stat": "Army", "value": -10 }, + { "stat": "Military", "value": -6 }, + { "stat": "Threat", "value": 8 } + ] + }, + { + "name": "naval_battle_victory", + "description": "The city’s navy defeats a hostile threat, securing coastal trade routes and striking a blow to the enemy’s threat level.", + "stats": [ + { "stat": "Military", "value": 12 }, + { "stat": "Threat", "value": -9 }, + { "stat": "Economy", "value": 4 } + ] + }, + { + "name": "disease_in_soldiers", + "description": "A virulent pestilence breaks out among the ranks, lowering army numbers and damaging overall health.", + "stats": [ + { "stat": "Army", "value": -14 }, + { "stat": "Health", "value": -10 }, + { "stat": "Military", "value": -5 } + ] + }, + { + "name": "recruitment_panic", + "description": "A surge of conscripts floods the army, but poor training causes a sharp drop in combat effectiveness.", + "stats": [ + { "stat": "Army", "value": 8 }, + { "stat": "Strength", "value": -9 }, + { "stat": "Military", "value": -3 } + ] + }, + { + "name": "training_expedition", + "description": "A focused military academy expedition hones the troops’ skills, raising overall strength at the cost of a temporary manpower drain.", + "stats": [ + { "stat": "Strength", "value": 11 }, + { "stat": "Army", "value": -6 }, + { "stat": "Military", "value": 4 } + ] + }, + { + "name": "spy_operation_success", + "description": "A covert spy network uncovers threats around, reducing the threat level and providing a tactical advantage.", + "stats": [ + { "stat": "Threat", "value": -10 }, + { "stat": "Military", "value": 3 }, + { "stat": "Strength", "value": 4 } + ] + }, + { + "name": "war_taxes_harsh", + "description": "The council imposes severe war taxes to fund the army, inflating military budgets but cracking public happiness.", + "stats": [ + { "stat": "Military", "value": 9 }, + { "stat": "Happiness", "value": -8 }, + { "stat": "Economy", "value": -5 } + ] + }, + { + "name": "battlefield_innovation", + "description": "A revolutionary tactic is adopted on the front lines, dramatically boosting army strength and lowering enemy threat.", + "stats": [ + { "stat": "Strength", "value": 13 }, + { "stat": "Threat", "value": -8 }, + { "stat": "Military", "value": 2 } + ] + }, + { + "name": "trade_agreement", + "description": "The city brokered a favorable trade pact with a neighboring realm, opening new markets for local goods.", + "stats": [ + { "stat": "Trade", "value": 12 }, + { "stat": "Economy", "value": 8 }, + { "stat": "Population", "value": 3 } + ] + }, + { + "name": "peace_council", + "description": "A diplomatic summit ends a long‑standing border conflict, reducing threat levels and fostering cultural exchange.", + "stats": [ + { "stat": "Trade", "value": 10 }, + { "stat": "Culture", "value": 7 }, + { "stat": "Happiness", "value": 5 } + ] + }, + { + "name": "bounty_hunt_success", + "description": "A coordinated hunt eliminates a notorious calamity, restoring safety to nearby villages.", + "stats": [ + { "stat": "Crime", "value": -12 }, + { "stat": "Threat", "value": -8 }, + { "stat": "Happiness", "value": 4 } + ] + }, + { + "name": "technological_breakthrough", + "description": "Inventors in the city unveiled new technologies with huge applications in the industrial field.", + "stats": [ + { "stat": "Science", "value": 15 }, + { "stat": "Industry", "value": 6 }, + { "stat": "Economy", "value": 5 } + ] + }, + { + "name": "festival_of_luxury", + "description": "A grand festival draws wealthy merchants and foreign dignitaries, boosting tourism and local pride.", + "stats": [ + { "stat": "Tourism", "value": 13 }, + { "stat": "Economy", "value": 7 }, + { "stat": "Happiness", "value": 6 } + ] + }, + { + "name": "military_training_expedition", + "description": "An intensive training expedition sharpens the army’s tactics, increasing overall strength without cost.", + "stats": [ + { "stat": "Strength", "value": 12 }, + { "stat": "Army", "value": 3 }, + { "stat": "Military", "value": 4 } + ] + }, + { + "name": "health_initiative", + "description": "A citywide vaccination campaign eradicates a deadly plague, dramatically improving public health.", + "stats": [ + { "stat": "Health", "value": 16 }, + { "stat": "Population", "value": 4 }, + { "stat": "Happiness", "value": 5 } + ] + }, + { + "name": "artisan_summit", + "description": "A gathering of master artisans leads to the sharing of techniques that double production efficiency.", + "stats": [ + { "stat": "Industry", "value": 14 }, + { "stat": "Economy", "value": 6 }, + { "stat": "Population", "value": 2 } + ] + }, + { + "name": "infrastructure_repair", + "description": "A massive repair drive restores crumbling roads and bridges, slashing travel time and boosting trade.", + "stats": [ + { "stat": "Infrastructure", "value": 15 }, + { "stat": "Trade", "value": 5 }, + { "stat": "Economy", "value": 3 } + ] + }, + { + "name": "cultural_exposition", + "description": "The city hosts an international exposition, showcasing its heritage and attracting scholars and tourists alike.", + "stats": [ + { "stat": "Culture", "value": 12 }, + { "stat": "Tourism", "value": 10 }, + { "stat": "Happiness", "value": 4 }, + { "stat": "Influence", "value": 4 } + ] + }, + { + "name": "great_earthquake", + "description": "A massive quake rips through the city, shattering buildings, collapsing bridges, and killing thousands.", + "stats": [ + { "stat": "Infrastructure", "value": -20 }, + { "stat": "Population", "value": -18 }, + { "stat": "Happiness", "value": -15 } + ] + }, + { + "name": "plague_of_scorpion", + "description": "A deadly disease spreads through the populace, turning citizens into venom‑infused monsters.", + "stats": [ + { "stat": "Health", "value": -22 }, + { "stat": "Population", "value": -16 }, + { "stat": "Crime", "value": 8 } + ] + }, + { + "name": "oil_fire_in_barnyard", + "description": "An oil storage depot explodes, sending a wave of fire over the city that reduces the army’s morale and strength.", + "stats": [ + { "stat": "Industry", "value": -19 }, + { "stat": "Military", "value": -12 }, + { "stat": "Threat", "value": 10 } + ] + }, + { + "name": "fire_of_sacred_temple", + "description": "The city’s most revered temple is consumed by a supernatural inferno, spilling holy ash into the streets and igniting widespread panic.", + "stats": [ + { "stat": "Culture", "value": -15 }, + { "stat": "Threat", "value": 12 }, + { "stat": "Happiness", "value": -6 } + ] + }, + { + "name": "cursed_great_flood", + "description": "An unseasonal deluge swallows the city, flooding every district, destroying crops, and causing widespread disease.", + "stats": [ + { "stat": "Food", "value": -20 }, + { "stat": "Economy", "value": -17 }, + { "stat": "Threat", "value": 13 } + ] + }, + { + "name": "massive_barricade_breach", + "description": "A minor calamity overpowers the city’s fortifications, unleashing a wave of slaughter and chaos.", + "stats": [ + { "stat": "Fortification", "value": -19 }, + { "stat": "Threat", "value": 20 }, + { "stat": "Happiness", "value": -12 } + ] + }, + { + "name": "invasion_of_the_undead", + "description": "A horde of reanimated skeletons breaks through the gates, attacking citizens and military alike.", + "stats": [ + { "stat": "Threat", "value": 25 }, + { "stat": "Crime", "value": -10 }, + { "stat": "Population", "value": -12 } + ] } ] } diff --git a/lib_efo/src/naming.rs b/lib_efo/src/naming.rs index 1d24bcd..02aa54c 100644 --- a/lib_efo/src/naming.rs +++ b/lib_efo/src/naming.rs @@ -10,7 +10,7 @@ use std::path::{Path, PathBuf}; use crate::stats::StatPair; /// The structure that holds everything we need for name generation. -#[derive(Debug, Serialize, Deserialize)] +#[derive(Debug, Serialize, Deserialize, Default)] pub struct NamingData { /// First name for characters pub first_names: Vec, @@ -43,40 +43,6 @@ pub struct EventDescription { pub stats: Vec, } -// /// A generic stat pair with (stat, value), used mainly for clap -// /// Accepts two forms -// /// 1. "cri 10" (two separate tokens) -// /// 2. "cri:10" (one token with a separator) -// pub struct StatPair(ListStats, GenericStat); -// -// 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, -// } - impl NamingData { /// Load the data from the supplied path. /// If the file does **not** exist, a default (embedded) version is written @@ -123,14 +89,12 @@ impl NamingData { format!("{}{}", prefix, suffix).trim().to_string() } - // /// Pick a random event idea (you can reuse this or make a dedicated method). - // pub fn random_event_idea(&self) -> &str { - // let mut rng = rand::rng(); - // self.event_ideas - // .choose(&mut rng) - // .map(String::as_str) - // .unwrap_or("No Event.") - // } + /// Pick a random event idea (you can reuse this or make a dedicated method). + #[allow(clippy::unwrap_used)] + pub fn random_event_idea(&self) -> &EventDescription { + let mut rng = rand::rng(); + self.event_ideas.choose(&mut rng).unwrap() + } /// Generates something like: /// “The Magnificent Sir Aurelius Blackthorn the Swift” @@ -181,3 +145,34 @@ pub static NAMING: Lazy = Lazy::new(|| { let path = naming_file_path(); NamingData::load_or_create(path).expect("Failed to load naming data") }); + +#[cfg(test)] +mod tests { + use super::*; + // use std::fs::{self, File}; + // use std::io::Write; + // use std::path::PathBuf; + + /// Helper that deserialises the embedded default JSON so we can compare against it. + fn default_data() -> NamingData { + serde_json::from_str::(DEFAULT_JSON_STR) + .expect("DEFAULT_JSON_STR should be a valid JSON") + } + + #[test] + fn try_load() {} + #[test] + fn basic_testing() { + // 1. Generate a character name + let character = NAMING.generate_character_name(); + println!("Character: {}", character); + + // 2. Generate a town name + let town = NAMING.generate_town_name(); + println!("Town: {}", town); + + // 3. Pick an event idea + let event = NAMING.generate_long_character_name(); + println!("Event idea: {}", event); + } +} diff --git a/lib_efo/src/stats.rs b/lib_efo/src/stats.rs index e74555d..4290d4a 100644 --- a/lib_efo/src/stats.rs +++ b/lib_efo/src/stats.rs @@ -291,7 +291,12 @@ pub struct MetaStats { /// 1. "cri 10" (two separate tokens) /// 2. "cri:10" (one token with a separator) #[derive(Debug, Serialize, Deserialize)] -pub struct StatPair(ListStats, GenericStat); +pub struct StatPair { + /// The stat selected + pub stat: ListStats, + /// The value of the modifier + pub value: GenericStat, +} /// Structure used to indicate position, possess nice helper methods to use as is in the program #[derive(Debug, Default, Serialize, Deserialize, Clone)] diff --git a/lib_efo/src/stats/implementations.rs b/lib_efo/src/stats/implementations.rs index 5eabfcb..b55f8ad 100644 --- a/lib_efo/src/stats/implementations.rs +++ b/lib_efo/src/stats/implementations.rs @@ -226,7 +226,10 @@ impl FromStr for StatPair { let value: isize = val_str .parse() .map_err(|_| EpochError::IllFormedStatQualifier(val_str.to_owned()))?; - Ok(StatPair(stat, stats::GenericStat(value))) + Ok(StatPair { + stat, + value: stats::GenericStat(value), + }) } } @@ -272,8 +275,8 @@ pub(crate) mod test { /// Helper that asserts that a stat pair string parses to the expected `StatPair`. fn assert_pair_ok(input: &str, expected_stat: ListStats, expected_val: isize) { let pair = StatPair::from_str(input).expect("should parse"); - assert_eq!(pair.0, expected_stat, "stat mismatch"); - assert_eq!(pair.1.0, expected_val, "value mismatch"); + assert_eq!(pair.stat, expected_stat, "stat mismatch"); + assert_eq!(pair.value.0, expected_val, "value mismatch"); } #[test] fn test_stat_pair_parsing() { -- 2.45.1 From a7c6e849cd7d51f9dc392b1f1cbfde16bdb3388a Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sun, 30 Nov 2025 18:19:20 +0100 Subject: [PATCH 14/22] Deslop --- LICENSE | 10 +- README.md | 14 +- bin_efo/src/commands.rs | 8 +- bin_efo/src/commands/epoch.rs | 42 ++--- bin_efo/src/commands/epoch/cli_epoch.rs | 42 ++--- bin_efo/src/commands/init.rs | 10 +- bin_efo/src/error.rs | 12 +- bin_efo/src/main.rs | 36 ++-- bin_efo/src/success.rs | 2 +- lib_efo/naming.json | 46 ++--- lib_efo/src/epoch.rs | 12 +- lib_efo/src/epoch/epoch_config.rs | 20 +- lib_efo/src/epoch/epoch_info.rs | 8 +- lib_efo/src/epoch/epoch_traits.rs | 12 +- lib_efo/src/error.rs | 16 +- lib_efo/src/lib.rs | 18 +- lib_efo/src/stats.rs | 234 ++++++++++++------------ lib_efo/src/stats/implementations.rs | 4 +- lib_efo/src/utils.rs | 2 +- 19 files changed, 274 insertions(+), 274 deletions(-) diff --git a/LICENSE b/LICENSE index c17e26f..d5ef671 100644 --- a/LICENSE +++ b/LICENSE @@ -6,10 +6,10 @@ treat the Software as is, without restriction, subject to the following condition: • The Software may not be used, directly or indirectly, for training, - fine‑tuning, or otherwise feeding into any artificial‑intelligence + fine-tuning, or otherwise feeding into any artificial-intelligence model or system. This includes, but is not limited to, usage as a - training dataset for machine‑learning or deep‑learning models, - model‑optimization, reinforcement‑learning, or any AI‑based analytics + training dataset for machine-learning or deep-learning models, + model-optimization, reinforcement-learning, or any AI-based analytics pipeline. • The Software may not be “scraped,” extracted, or otherwise harvested @@ -24,8 +24,8 @@ condition: All other rights granted under the MIT license remain in force, namely: - • The Software may be used for any non‑AI purpose, including commercial - or non‑commercial use, modification, distribution, private or public + • The Software may be used for any non-AI purpose, including commercial + or non-commercial use, modification, distribution, private or public deployment, and so on. • The Software is provided “as is,” without warranty of any kind, diff --git a/README.md b/README.md index 5c963ba..557228f 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ # 📦 Epoch Forge (`epoch_forge`) -> **A Rust‑powered CLI for managing fantasy organisations across time.** -> *Think of it as a living, breathing world‑state engine that lets you “rewind”, “fast‑forward”, and **alter** the history of guilds, towns, wars, and characters.* +> **A Rust-powered CLI for managing fantasy organisations across time.** +> *Think of it as a living, breathing world-state engine that lets you “rewind”, “fast-forward”, and **alter** the history of guilds, towns, wars, and characters.* -> 🚀 *Fast, type‑safe, and fully testable.* +> 🚀 *Fast, type-safe, and fully testable.* ## ✨ Quick start @@ -40,19 +40,19 @@ cat world.json | Feature | What it gives you | Where it lives | |---------|------------------|----------------| | **Epoch management** | Switch, advance, or rewind the timeline | `core::epoch` | -| **Event handling** | Add/remove world‑shaping events (storms, festivals, wars) | `core::event` | +| **Event handling** | Add/remove world-shaping events (storms, festivals, wars) | `core::event` | | **Organisation CRUD** | Guilds, factions, corporations | `core::org` | | **Character CRUD** | Heroes, villains, NPCs | `core::character` | | **Town CRUD** | Villages, cities, trade hubs | `core::town` | | **Link network** | Alliances, wars, roads, trade routes | `core::link` | -| **Persistence** | JSON/YAML stores, pluggable back‑ends | `core::storage` | -| **CLI** | `efo` binary with sub‑commands | `efo` crate | +| **Persistence** | JSON/YAML stores, pluggable back-ends | `core::storage` | +| **CLI** | `efo` binary with sub-commands | `efo` crate | | **Tests** | Unit & integration coverage | `tests/` | ### 📃 Quick reference table -| Sub‑command | Usage | What it changes | +| Sub-command | Usage | What it changes | |-------------|-------|-----------------| | `epoch` | `efo epoch --init`
`efo epoch --advance N`
`efo epoch --target ID` | Creates a world; moves time forward or back. | | `event` | `efo event add ...`
`efo event remove ...` | Adds or removes an event. | diff --git a/bin_efo/src/commands.rs b/bin_efo/src/commands.rs index 3bbee69..2b3f2e9 100644 --- a/bin_efo/src/commands.rs +++ b/bin_efo/src/commands.rs @@ -1,10 +1,10 @@ //! # `commands` module //! -//! This module is the entry point for all CLI sub‑commands of the `efo` binary. -//! Each sub‑command (e.g. `epoch`, `org`, `event`, `town`, `link`) lives in its -//! own file inside this directory and is re‑exported here so that the main +//! This module is the entry point for all CLI sub-commands of the `efo` binary. +//! Each sub-command (e.g. `epoch`, `org`, `event`, `town`, `link`) lives in its +//! own file inside this directory and is re-exported here so that the main //! `efo::main.rs` can simply `use commands::*;` and dispatch based on the -//! clap‑parsed enum. +//! clap-parsed enum. #![warn(missing_docs, clippy::missing_docs_in_private_items)] diff --git a/bin_efo/src/commands/epoch.rs b/bin_efo/src/commands/epoch.rs index 2a567d2..d260bfd 100644 --- a/bin_efo/src/commands/epoch.rs +++ b/bin_efo/src/commands/epoch.rs @@ -1,6 +1,6 @@ -//! # `epoch` sub‑command +//! # `epoch` sub-command //! -//! Handles all epoch‑related logic – logging, switching, computing the +//! Handles all epoch-related logic - logging, switching, computing the //! next epoch, and resetting future events. #![warn(missing_docs, clippy::missing_docs_in_private_items)] @@ -16,12 +16,12 @@ use log::{debug, info}; pub mod cli_epoch; -/// **Public entry point used by `efo::main`** – dispatches to the real +/// **Public entry point used by `efo::main`** - dispatches to the real /// handler that lives in `crate::world::EpochManager`. /// /// # Arguments -/// * `cmd` – The command to execute. This is an enum that represents -/// one of the possible sub‑commands for the `epoch` feature. +/// * `cmd` - The command to execute. This is an enum that represents +/// one of the possible sub-commands for the `epoch` feature. /// /// # Returns /// * `Ok(())` on success. @@ -64,7 +64,7 @@ pub fn handle_cmd(cmd: cli_epoch::EpochCmd) -> Result<(), AppError> { /// supplied in `args.summary`. The epoch map in `main_epoch` is /// modified in place. /// -/// This helper is internal to the `epoch` sub‑command and is not part +/// This helper is internal to the `epoch` sub-command and is not part /// of the public API. fn handle_summary(args: cli_epoch::Summary, main_epoch: &mut EpochConfig) -> Result<(), AppError> { let epoch_id = main_epoch.epoch_id; @@ -82,9 +82,9 @@ fn handle_summary(args: cli_epoch::Summary, main_epoch: &mut EpochConfig) -> Res /// Show a diff between two epochs. /// /// Currently unimplemented. The function is a placeholder until a -/// world‑level diff algorithm is available. +/// world-level diff algorithm is available. /// -/// This helper is internal to the `epoch` sub‑command and is not part +/// This helper is internal to the `epoch` sub-command and is not part /// of the public API. fn handle_diff(args: cli_epoch::Diff) -> Result<(), AppError> { let _ = args; @@ -99,7 +99,7 @@ fn handle_diff(args: cli_epoch::Diff) -> Result<(), AppError> { /// up to the supplied limit. The log is written by the /// underlying `EpochConfig::log_elements` implementation. /// -/// This helper is internal to the `epoch` sub‑command. +/// This helper is internal to the `epoch` sub-command. fn handle_log(args: cli_epoch::Log, main_epoch: &mut EpochConfig) -> Result<(), AppError> { let limit = args.limit; let start_id = &main_epoch.epoch_id; @@ -121,7 +121,7 @@ fn handle_log(args: cli_epoch::Log, main_epoch: &mut EpochConfig) -> Result<(), /// in the configuration, and persists the change. It also prints a /// success message via `display_success`. /// -/// This helper is internal to the `epoch` sub‑command. +/// This helper is internal to the `epoch` sub-command. fn handle_switch(args: cli_epoch::Switch, main_epoch: &mut EpochConfig) -> Result<(), AppError> { let target = main_epoch.get(&args.target)?; main_epoch.try_load(&target)?; @@ -135,15 +135,15 @@ fn handle_switch(args: cli_epoch::Switch, main_epoch: &mut EpochConfig) -> Resul Ok(()) } -/// Handle the `next` sub‑command. +/// Handle the `next` sub-command. /// /// Advances the epoch to the next scheduled event. If the current /// configuration contains any epochs with an identifier larger than -/// the current one, an error is returned – otherwise the next epoch +/// the current one, an error is returned - otherwise the next epoch /// is computed. /// /// # Arguments -/// * `main_epoch` – mutable reference to the current `EpochConfig` +/// * `main_epoch` - mutable reference to the current `EpochConfig` /// (the `cli_epoch::Next` argument is unused). /// /// # Returns @@ -171,13 +171,13 @@ fn handle_next(_args: cli_epoch::Next, main_epoch: &mut EpochConfig) -> Result<( } } -/// Handle the `reset` sub‑command. +/// Handle the `reset` sub-command. /// /// Deletes all epochs whose identifier is greater than the current one, /// effectively rolling back to the present epoch. /// /// # Arguments -/// * `main_epoch` – mutable reference to the current `EpochConfig` +/// * `main_epoch` - mutable reference to the current `EpochConfig` /// (the `cli_epoch::Reset` argument is unused). /// /// # Returns @@ -202,14 +202,14 @@ fn handle_reset(args: cli_epoch::Reset, main_epoch: &mut EpochConfig) -> Result< Ok(()) } -/// Handle the `tag` sub‑command. +/// Handle the `tag` sub-command. /// /// Adds a tag to the current epoch. The tag must not already exist /// elsewhere in the configuration; otherwise an error is returned. /// /// # Arguments -/// * `args` – `cli_epoch::Tag` containing the tag to add. -/// * `main_epoch` – mutable reference to the current `EpochConfig`. +/// * `args` - `cli_epoch::Tag` containing the tag to add. +/// * `main_epoch` - mutable reference to the current `EpochConfig`. /// /// # Returns /// * `Ok(())` if the tag was successfully added. @@ -256,13 +256,13 @@ fn handle_taging(args: cli_epoch::Tag, main_epoch: &mut EpochConfig) -> Result<( /// Perform a filesystem consistency check on the epoch data. /// -/// The function invokes the internal consistency‑check logic of -/// `EpochConfig`. It is intended for use from the `fsck` sub‑command +/// The function invokes the internal consistency-check logic of +/// `EpochConfig`. It is intended for use from the `fsck` sub-command /// and does **not** modify the current epoch. Any problems that /// are detected are reported through the returned `Result`; the /// command may also print a diagnostic message to the user. /// -/// This helper is internal to the `epoch` sub‑command. +/// This helper is internal to the `epoch` sub-command. fn handle_fsck(args: cli_epoch::Fsck, main_epoch: &mut EpochConfig) -> Result<(), AppError> { let _ = main_epoch; let _ = args; diff --git a/bin_efo/src/commands/epoch/cli_epoch.rs b/bin_efo/src/commands/epoch/cli_epoch.rs index de436e6..63e9f8b 100644 --- a/bin_efo/src/commands/epoch/cli_epoch.rs +++ b/bin_efo/src/commands/epoch/cli_epoch.rs @@ -1,30 +1,30 @@ //! # `epoch` CLI module //! -//! This module defines the command‑line interface for the `efo epoch` -//! sub‑command. +//! This module defines the command-line interface for the `efo epoch` +//! sub-command. //! //! ## Overview of commands //! -//! * **`log`** – list epochs in a git‑log style. -//! * **`switch`** – switch to a specific epoch (by id, name or tag). -//! * **`next`** – compute the next epoch from the current one. -//! * **`reset`** – delete all future events after the current epoch. -//! * **`diff`** – show differences between two epochs. -//! * **`tag`** – add a tag to the current epoch. -//! * **`fsck`** – perform basic filesystem level maintenance. +//! * **`log`** - list epochs in a git-log style. +//! * **`switch`** - switch to a specific epoch (by id, name or tag). +//! * **`next`** - compute the next epoch from the current one. +//! * **`reset`** - delete all future events after the current epoch. +//! * **`diff`** - show differences between two epochs. +//! * **`tag`** - add a tag to the current epoch. +//! * **`fsck`** - perform basic filesystem level maintenance. #![warn(missing_docs, clippy::missing_docs_in_private_items)] use clap::{Args, Subcommand}; use lib_efo::epoch::EpochIdentifier; -/// Top‑level sub‑command for the `efo epoch` command. +/// Top-level sub-command for the `efo epoch` command. /// /// Each variant represents a distinct epoch operation that can be /// invoked from the command line. #[derive(Subcommand, Debug)] pub enum EpochCmd { - /// List all epochs – a git‑log style view + /// List all epochs - a git-log style view Log(Log), /// Switch to an epoch (by numeric ID, name, or tag) @@ -49,10 +49,10 @@ pub enum EpochCmd { Summary(Summary), } -/// Displays a git‑log style list of epochs. +/// Displays a git-log style list of epochs. /// /// # Arguments -/// * `limit` – (Optional) Limit the number of entries shown. +/// * `limit` - (Optional) Limit the number of entries shown. /// Default: `50`. #[derive(Args, Debug)] pub struct Log { @@ -65,16 +65,16 @@ pub struct Log { /// a name, or a tag. /// /// # Arguments -/// * `target` – The epoch to switch to. -/// * `force` – If set, drops all pending work and forces the switch. +/// * `target` - The epoch to switch to. +/// * `force` - If set, drops all pending work and forces the switch. #[derive(Args, Debug)] pub struct Switch { - /// The epoch to switch to – can be an integer, a name, or a tag. + /// The epoch to switch to - can be an integer, a name, or a tag. #[arg(required = true)] pub target: EpochIdentifier, - /// Optional confirmation flag (if you ever want to force‑switch) - #[arg(long, short, help = "Force‑switch dropping all the pending work")] + /// Optional confirmation flag (if you ever want to force-switch) + #[arg(long, short, help = "Force-switch dropping all the pending work")] pub force: bool, } @@ -89,8 +89,8 @@ pub struct Reset; /// Shows the differences between two epochs. /// /// # Arguments -/// * `start` – The starting point to compute the differences. -/// * `end` – The end point to compute the differences; defaults to the +/// * `start` - The starting point to compute the differences. +/// * `end` - The end point to compute the differences; defaults to the /// current epoch if omitted. #[derive(Args, Debug)] pub struct Diff { @@ -105,7 +105,7 @@ pub struct Diff { /// Adds a tag to the current epoch. /// /// # Arguments -/// * `tag` – The tag to tag the current epoch with. +/// * `tag` - The tag to tag the current epoch with. #[derive(Args, Debug)] pub struct Tag { #[arg(required = true)] diff --git a/bin_efo/src/commands/init.rs b/bin_efo/src/commands/init.rs index fdb6bc2..f6bea46 100644 --- a/bin_efo/src/commands/init.rs +++ b/bin_efo/src/commands/init.rs @@ -1,13 +1,13 @@ //! # `init` module //! -//! Provides the implementation of the `init` sub‑command for the -//! command‑line interface. The sub‑command creates an empty +//! Provides the implementation of the `init` sub-command for the +//! command-line interface. The sub-command creates an empty //! repository, writes the default configuration (`.epoch`), -//! and sets up the first epoch (epoch 0). +//! and sets up the first epoch (epoch 0). //! //! The main public API consists of: //! -//! * `InitCmd` – a struct containing the command‑line arguments. +//! * `InitCmd` - a struct containing the command-line arguments. #![warn(missing_docs, clippy::missing_docs_in_private_items)] @@ -67,7 +67,7 @@ pub fn init(args: &InitCmd) -> Result<(), AppError> { Ok(()) } -/// Helper that creates the initial epoch (epoch 0). +/// Helper that creates the initial epoch (epoch 0). /// /// This function is not part of the public API; it is kept internal /// to `init`. It creates an empty `EpochInfo`, crea diff --git a/bin_efo/src/error.rs b/bin_efo/src/error.rs index 0199a3c..cf2e886 100644 --- a/bin_efo/src/error.rs +++ b/bin_efo/src/error.rs @@ -1,7 +1,7 @@ //! General error type that the CLI propagates. //! //! `AppError` aggregates all error kinds that may surface during a command -//! execution: parsing, I/O, epoch logic, storage, and a catch‑all. +//! execution: parsing, I/O, epoch logic, storage, and a catch-all. #![warn(missing_docs, clippy::missing_docs_in_private_items)] @@ -13,8 +13,8 @@ use thiserror::Error; #[derive(Debug, Error, Diagnostic)] #[allow(dead_code)] pub enum AppError { - /// Generic “invalid command / missing flag” – emitted by clap. - #[error("Command‑line error: {0}")] + /// Generic “invalid command / missing flag” - emitted by clap. + #[error("Command-line error: {0}")] // #[diagnostic(transparent)] Clap(#[from] clap::Error), @@ -23,17 +23,17 @@ pub enum AppError { // #[diagnostic(transparent)] Io(#[from] std::io::Error), - /// Domain‑specific problems (see `EpochError`). + /// Domain-specific problems (see `EpochError`). #[error("Epoch error:")] #[diagnostic(transparent)] Epoch(#[from] EpochError), - /// Storage‑layer (e.g. DB) errors. + /// Storage-layer (e.g. DB) errors. #[error("Storage error: {0}")] // #[diagnostic(transparent)] Storage(#[from] StorageError), - /// Anything else we didn’t anticipate. + /// Anything else we didn't anticipate. #[error("Unknown error: {0}")] Other(String), } diff --git a/bin_efo/src/main.rs b/bin_efo/src/main.rs index 018696c..8977290 100644 --- a/bin_efo/src/main.rs +++ b/bin_efo/src/main.rs @@ -1,16 +1,16 @@ //! # `efo` //! -//! The **command‑line interface** for `epoch_forge`. It exposes a single -//! binary `efo` that supports the following sub‑commands: +//! The **command-line interface** for `epoch_forge`. It exposes a single +//! binary `efo` that supports the following sub-commands: //! -//! - `epoch` – switch / advance time -//! - `event` – add / remove events -//! - `org` – add / remove organisations -//! - `chr` – add / remove characters -//! - `town` – add / remove towns -//! - `link` – add / remove links (alliances, wars, roads, etc.) +//! - `epoch` - switch / advance time +//! - `event` - add / remove events +//! - `org` - add / remove organisations +//! - `chr` - add / remove characters +//! - `town` - add / remove towns +//! - `link` - add / remove links (alliances, wars, roads, etc.) //! -//! Each sub‑command is implemented in its own module under `commands/`. +//! Each sub-command is implemented in its own module under `commands/`. //! The `main.rs` file simply parses arguments with `clap` and dispatches //! to the appropriate handler. The handlers share a common `World` //! instance that they load from / persist to disk. @@ -32,13 +32,13 @@ mod commands; mod error; mod success; -/// The root command‑line parser for the `efo` binary. +/// The root command-line parser for the `efo` binary. /// -/// It uses `clap` to parse the top‑level sub‑commands (`init`, `epoch`, …) +/// It uses `clap` to parse the top-level sub-commands (`init`, `epoch`, …) /// and stores them in the `command` field. #[derive(Parser, Debug)] #[command(name = "efo")] -#[command(about = "Epoch Forge – manage organisations over time")] +#[command(about = "Epoch Forge - manage organisations over time")] struct Cli { /// The level of verbosity #[arg(short, long, action = ArgAction::Count, global = true)] @@ -49,9 +49,9 @@ struct Cli { command: TopLevelCmd, } -/// Enumeration of the top‑level sub‑commands that `efo` accepts. +/// Enumeration of the top-level sub-commands that `efo` accepts. /// -/// Each variant corresponds to a single sub‑command and holds its own +/// Each variant corresponds to a single sub-command and holds its own /// argument structure. #[derive(Subcommand, Debug)] enum TopLevelCmd { @@ -69,8 +69,8 @@ enum TopLevelCmd { /// Program entry point. /// -/// Parses the command‑line arguments and dispatches to the selected -/// sub‑command. Errors returned by the sub‑command handlers are shown +/// Parses the command-line arguments and dispatches to the selected +/// sub-command. Errors returned by the sub-command handlers are shown /// in stdout and returned as a `miette::Result<()>`. #[allow(clippy::unwrap_used)] fn main() -> miette::Result<()> { @@ -98,11 +98,11 @@ fn main() -> miette::Result<()> { /// Dispatches the parsed command to the appropriate handler. /// /// # Arguments -/// * `cli` – The parsed command‑line options. +/// * `cli` - The parsed command-line options. /// /// # Returns /// * `Ok(())` on success. -/// * `Err(AppError)` if the chosen sub‑command handler fails. +/// * `Err(AppError)` if the chosen sub-command handler fails. /// /// The function matches on the `TopLevelCmd` variant and calls the /// corresponding handler in the `commands` module. Any error is diff --git a/bin_efo/src/success.rs b/bin_efo/src/success.rs index 440e218..60ffc71 100644 --- a/bin_efo/src/success.rs +++ b/bin_efo/src/success.rs @@ -9,7 +9,7 @@ pub enum SuccessMessages { #[display("Switched to epoch {_0}")] EpochSwitchSuccess(lib_efo::epoch::EpochId), - #[display("All future events deleted – back to epoch {_0}")] + #[display("All future events deleted - back to epoch {_0}")] DeletedAllFutureEvents(lib_efo::epoch::EpochId), #[display("The folder was initialized as an epoch folder")] diff --git a/lib_efo/naming.json b/lib_efo/naming.json index ebcba9f..9402d35 100644 --- a/lib_efo/naming.json +++ b/lib_efo/naming.json @@ -374,15 +374,15 @@ "the Harvester", "the Seeker", "the Whisperer", - "the Tempest‑born", - "the Iron‑clad", + "the Tempest-born", + "the Iron-clad", "the Moonlit", - "the Sun‑scarred", - "the Bone‑choked", - "the Frost‑kissed", + "the Sun-scarred", + "the Bone-choked", + "the Frost-kissed", "the Ashen", "the Shattered", - "the Echo‑bound", + "the Echo-bound", "the Vile", "the Harsh", "the Unseen", @@ -540,7 +540,7 @@ }, { "name": "city_corruption_scandal", - "description": "A high‑ranking magistrate is discovered embezzling city funds, sparking public outrage and a demand for accountability.", + "description": "A high-ranking magistrate is discovered embezzling city funds, sparking public outrage and a demand for accountability.", "stats": [ { "stat": "Economy", "value": -9 }, { "stat": "Bureaucracy", "value": -7 }, @@ -585,7 +585,7 @@ }, { "name": "city_guild_suppression", - "description": "The council cracks down on the city’s merchant guilds, confiscating goods and driving merchants underground.", + "description": "The council cracks down on the city's merchant guilds, confiscating goods and driving merchants underground.", "stats": [ { "stat": "Trade", "value": -11 }, { "stat": "Crime", "value": 6 }, @@ -603,7 +603,7 @@ }, { "name": "city_public_health_crisis", - "description": "A mysterious disease spreads through the city’s crowded streets, overwhelming the local infirmaries.", + "description": "A mysterious disease spreads through the city's crowded streets, overwhelming the local infirmaries.", "stats": [ { "stat": "Health", "value": -16 }, { "stat": "Population", "value": -8 }, @@ -612,7 +612,7 @@ }, { "name": "city_transport_infrastructure_fail", - "description": "The city’s main aqueduct collapses, cutting off water supply to half the districts.", + "description": "The city's main aqueduct collapses, cutting off water supply to half the districts.", "stats": [ { "stat": "Infrastructure", "value": -15 }, { "stat": "Population", "value": -4 }, @@ -693,7 +693,7 @@ }, { "name": "currency_devaluation", - "description": "The city’s coinage is devalued by a sudden policy shift, causing imported goods to skyrocket in price.", + "description": "The city's coinage is devalued by a sudden policy shift, causing imported goods to skyrocket in price.", "stats": [ { "stat": "Economy", "value": -13 }, { "stat": "Trade", "value": -9 }, @@ -711,7 +711,7 @@ }, { "name": "resource_piracy", - "description": "Sea‑borne raiders seize a shipment of precious stones destined for the city, flooding the market with counterfeit goods.", + "description": "Sea-borne raiders seize a shipment of precious stones destined for the city, flooding the market with counterfeit goods.", "stats": [ { "stat": "Trade", "value": -12 }, { "stat": "Economy", "value": -7 }, @@ -720,7 +720,7 @@ }, { "name": "steel_furnace_overheat", - "description": "A critical failure in the city’s primary steel furnace sparks an uncontrollable fire, destroying production lines.", + "description": "A critical failure in the city's primary steel furnace sparks an uncontrollable fire, destroying production lines.", "stats": [ { "stat": "Industry", "value": -17 }, { "stat": "Economy", "value": -10 }, @@ -747,7 +747,7 @@ }, { "name": "foreign_factory_purchase", - "description": "A foreign conglomerate purchases the city’s largest textile mill, imposing new quotas that reduce local employment.", + "description": "A foreign conglomerate purchases the city's largest textile mill, imposing new quotas that reduce local employment.", "stats": [ { "stat": "Industry", "value": -9 }, { "stat": "Economy", "value": -7 }, @@ -774,7 +774,7 @@ }, { "name": "bottleneck_transportation", - "description": "The city’s main rail line is seized by gangsters, disrupting the flow of raw materials to factories.", + "description": "The city's main rail line is seized by gangsters, disrupting the flow of raw materials to factories.", "stats": [ { "stat": "Infrastructure", "value": -8 }, { "stat": "Industry", "value": -6 }, @@ -819,7 +819,7 @@ }, { "name": "naval_battle_victory", - "description": "The city’s navy defeats a hostile threat, securing coastal trade routes and striking a blow to the enemy’s threat level.", + "description": "The city's navy defeats a hostile threat, securing coastal trade routes and striking a blow to the enemy's threat level.", "stats": [ { "stat": "Military", "value": 12 }, { "stat": "Threat", "value": -9 }, @@ -846,7 +846,7 @@ }, { "name": "training_expedition", - "description": "A focused military academy expedition hones the troops’ skills, raising overall strength at the cost of a temporary manpower drain.", + "description": "A focused military academy expedition hones the troops' skills, raising overall strength at the cost of a temporary manpower drain.", "stats": [ { "stat": "Strength", "value": 11 }, { "stat": "Army", "value": -6 }, @@ -891,7 +891,7 @@ }, { "name": "peace_council", - "description": "A diplomatic summit ends a long‑standing border conflict, reducing threat levels and fostering cultural exchange.", + "description": "A diplomatic summit ends a long-standing border conflict, reducing threat levels and fostering cultural exchange.", "stats": [ { "stat": "Trade", "value": 10 }, { "stat": "Culture", "value": 7 }, @@ -927,7 +927,7 @@ }, { "name": "military_training_expedition", - "description": "An intensive training expedition sharpens the army’s tactics, increasing overall strength without cost.", + "description": "An intensive training expedition sharpens the army's tactics, increasing overall strength without cost.", "stats": [ { "stat": "Strength", "value": 12 }, { "stat": "Army", "value": 3 }, @@ -982,7 +982,7 @@ }, { "name": "plague_of_scorpion", - "description": "A deadly disease spreads through the populace, turning citizens into venom‑infused monsters.", + "description": "A deadly disease spreads through the populace, turning citizens into venom-infused monsters.", "stats": [ { "stat": "Health", "value": -22 }, { "stat": "Population", "value": -16 }, @@ -991,7 +991,7 @@ }, { "name": "oil_fire_in_barnyard", - "description": "An oil storage depot explodes, sending a wave of fire over the city that reduces the army’s morale and strength.", + "description": "An oil storage depot explodes, sending a wave of fire over the city that reduces the army's morale and strength.", "stats": [ { "stat": "Industry", "value": -19 }, { "stat": "Military", "value": -12 }, @@ -1000,7 +1000,7 @@ }, { "name": "fire_of_sacred_temple", - "description": "The city’s most revered temple is consumed by a supernatural inferno, spilling holy ash into the streets and igniting widespread panic.", + "description": "The city's most revered temple is consumed by a supernatural inferno, spilling holy ash into the streets and igniting widespread panic.", "stats": [ { "stat": "Culture", "value": -15 }, { "stat": "Threat", "value": 12 }, @@ -1018,7 +1018,7 @@ }, { "name": "massive_barricade_breach", - "description": "A minor calamity overpowers the city’s fortifications, unleashing a wave of slaughter and chaos.", + "description": "A minor calamity overpowers the city's fortifications, unleashing a wave of slaughter and chaos.", "stats": [ { "stat": "Fortification", "value": -19 }, { "stat": "Threat", "value": 20 }, diff --git a/lib_efo/src/epoch.rs b/lib_efo/src/epoch.rs index 7cc3713..ad61733 100644 --- a/lib_efo/src/epoch.rs +++ b/lib_efo/src/epoch.rs @@ -4,12 +4,12 @@ //! structures so that the binary can quickly read/write its “current //! position” without pulling the whole world into memory. //! -//! * `EpochConfig` – lives in `.epochconfig`. It only remembers +//! * `EpochConfig` - lives in `.epochconfig`. It only remembers //! which epoch folder should be considered “current” and a few //! convenience fields (tags, path). It never holds any event or //! world data. //! -//! * `EpochInfo` – stored inside `epoch//.epochinfo`. +//! * `EpochInfo` - stored inside `epoch//.epochinfo`. //! This file contains the *metadata* for that particular epoch //! (seed, selected events, parent link, etc.). Again, it does **not** //! hold the full world; that is handled elsewhere in the engine. @@ -119,8 +119,8 @@ impl std::ops::Deref for EpochId { } } -/// A flexible identifier for *any* epoch – the world may be -/// addressed by a numeric ID or by a friendly tag (e.g. `"winter‑b"`). +/// A flexible identifier for *any* epoch - the world may be +/// addressed by a numeric ID or by a friendly tag (e.g. `"winter-b"`). /// /// The enum is `untagged` so that serialising/deserialising does /// **not** add a wrapper field, e.g. `{"Tag":"foo"}`. @@ -128,7 +128,7 @@ impl std::ops::Deref for EpochId { /// * `"42"` → `EpochIdentifier::Id(EpochId::new(42))` /// * `"foo"` → `EpochIdentifier::Tag("foo".into())` #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, Hash)] -#[serde(untagged)] // <‑‑ no “type” wrapper is written to JSON +#[serde(untagged)] // <-- no “type” wrapper is written to JSON pub enum EpochIdentifier { /// A textual tag that maps to a numeric epoch ID in `EpochConfig::tags`. Tag(String), @@ -140,7 +140,7 @@ pub enum EpochIdentifier { impl FromStr for EpochIdentifier { type Err = clap::Error; // any `std::error::Error` works - /// Try to parse either a decimal number (-> `Id`) or any non‑empty + /// Try to parse either a decimal number (-> `Id`) or any non-empty /// string (-> `Tag`). /// /// Errors are converted to a Clap error so that the CLI shows a diff --git a/lib_efo/src/epoch/epoch_config.rs b/lib_efo/src/epoch/epoch_config.rs index 27117a0..9987432 100644 --- a/lib_efo/src/epoch/epoch_config.rs +++ b/lib_efo/src/epoch/epoch_config.rs @@ -1,10 +1,10 @@ -//! Management of the *current‑epoch* configuration. +//! Management of the *current-epoch* configuration. //! //! The configuration is stored in a file named `.epoch` and contains only //! the lightweight information needed for the CLI to switch between epochs //! quickly: //! * the numeric ID of the current epoch, -//! * a map of human‑friendly tags to epoch IDs, +//! * a map of human-friendly tags to epoch IDs, //! * a map of known epoch IDs to unloaded metadata (`EpochInfo`). //! //! The world data and all event logs belong to the individual epoch @@ -30,16 +30,16 @@ use crate::{epoch::epoch_traits::Prettiable, error::EpochError, io_err_with_help /// /// Only the minimal information needed for fast switches is stored: /// * the numeric identifier of the selected epoch, -/// * a list of human‑readable tags, -/// * the absolute path to the epoch’s directory. +/// * a list of human-readable tags, +/// * the absolute path to the epoch's directory. /// -/// No world or event data lives here – it is purely a lightweight pointer. +/// No world or event data lives here - it is purely a lightweight pointer. #[derive(Debug, Clone, Serialize, Deserialize)] pub struct EpochConfig { /// The epoch ID that the binary should consider “current”. pub epoch_id: EpochId, - /// Optional human‑friendly tags (e.g. `"winter‑B"`, `"post‑war"`). + /// Optional human-friendly tags (e.g. `"winter-B"`, `"post-war"`). pub tags: HashMap, // TODO[6]: Can become important // #[serde(skip)] @@ -102,7 +102,7 @@ impl EpochConfig { Ok(self) } - /// Loads the metadata for an epoch from disk into the in‑memory cache. + /// Loads the metadata for an epoch from disk into the in-memory cache. /// /// The epoch identified by `epoch_id` must exist in `list_existing_epochs`. /// The JSON file on disk is read, deserialized into an `EpochInfo`, and @@ -216,12 +216,12 @@ impl EpochConfig { /// Insert a new epoch into the configuration and persist it. /// - /// The function creates the epoch’s directory, writes its metadata, + /// The function creates the epoch's directory, writes its metadata, /// updates the internal maps, and finally writes the updated /// configuration to disk. /// /// # Returns - /// * `Ok(())` – the epoch was added and the configuration was saved. + /// * `Ok(())` - the epoch was added and the configuration was saved. /// * `Err(EpochError::EpochAlreadyExists(..))` if an epoch with the same ID already exists. pub fn insert_and_save( &mut self, @@ -247,7 +247,7 @@ impl EpochConfig { /// Load and display the metadata for a list of epoch IDs. /// - /// The function first ensures that each requested epoch’s metadata is + /// The function first ensures that each requested epoch's metadata is /// loaded into memory, then displays a formatted log for each one. pub fn log_elements(&mut self, list_ids: &[EpochId]) -> Result<(), EpochError> { let mut items_to_log = Vec::with_capacity(list_ids.len()); diff --git a/lib_efo/src/epoch/epoch_info.rs b/lib_efo/src/epoch/epoch_info.rs index b7fb7f1..1dceeec 100644 --- a/lib_efo/src/epoch/epoch_info.rs +++ b/lib_efo/src/epoch/epoch_info.rs @@ -3,7 +3,7 @@ //! The `EpochInfo` struct holds all information that the engine needs to //! reconstruct a particular epoch. //! It is persisted to `epoch//.epochinfo`. The file contains the epoch ID, the RNG -//! seed that produced the world, any optional tags, and a human‑readable +//! seed that produced the world, any optional tags, and a human-readable //! summary. World data itself is stored separately (e.g. in `world.json`). use cli_table::Table; @@ -32,7 +32,7 @@ use crate::{ "Epoch ({epoch_id:>5}) | seed ({rng_seed:<10}) | tags ({tags:<10}) | summary ({summary:<20})" )] pub struct EpochInfo { - /// The ID of this epoch – should match the directory name. + /// The ID of this epoch - should match the directory name. #[table(title = "ID")] pub epoch_id: EpochId, @@ -46,11 +46,11 @@ pub struct EpochInfo { // /// The engine uses this to replay the world from the // /// parent epoch to the current one. // pub selected_events: Vec, - /// Optional tags that help identify the epoch (e.g. `"Winter‑B"`). + /// Optional tags that help identify the epoch (e.g. `"Winter-B"`). #[table(title = "Tags")] pub tags: TagList, - /// Human‑readable description or summary, useful for the `log` command. + /// Human-readable description or summary, useful for the `log` command. #[table(title = "Summary")] pub summary: String, } diff --git a/lib_efo/src/epoch/epoch_traits.rs b/lib_efo/src/epoch/epoch_traits.rs index ac7ec34..55a25bf 100644 --- a/lib_efo/src/epoch/epoch_traits.rs +++ b/lib_efo/src/epoch/epoch_traits.rs @@ -2,7 +2,7 @@ //! //! All traits used by the `lib_efo` library. //! These traits are marker traits that describe behaviour -//! common to many of the library’s element types. +//! common to many of the library's element types. #![warn(clippy::missing_docs_in_private_items)] use cli_table::{Style, Table, WithTitle}; @@ -20,10 +20,10 @@ pub trait Applyable {} /// Elements that can advance to a next state over time. /// /// Implementors usually provide a `.next()` method that returns the -/// element’s state after a time step (e.g., fading or diminishing). +/// element's state after a time step (e.g., fading or diminishing). pub trait Nextable {} -/// Elements that can be rendered into a pretty, human‑readable form. +/// Elements that can be rendered into a pretty, human-readable form. pub trait Prettiable: Display { /// Shows many items as a table. /// @@ -65,7 +65,7 @@ pub trait ConfigWritable: Serialize { /// * `action` - A description of the action for error reporting. /// /// # Returns - /// * `Ok(String)` containing the pretty‑printed JSON. + /// * `Ok(String)` containing the pretty-printed JSON. /// * `Err(EpochError::Serde)` if serialisation fails. fn as_json(&self, action: String) -> Result { serde_json::to_string_pretty(self).map_err(|e| EpochError::Serde { @@ -83,8 +83,8 @@ pub trait ConfigWritable: Serialize { /// file already exists. /// /// # Arguments - /// * `action_description` – A human‑readable description used in error messages. - /// * `do_not_erase` – Determines whether to overwrite an existing file. + /// * `action_description` - A human-readable description used in error messages. + /// * `do_not_erase` - Determines whether to overwrite an existing file. /// /// # Returns /// * `Ok(())` on success. diff --git a/lib_efo/src/error.rs b/lib_efo/src/error.rs index f03e8ee..6c3a287 100644 --- a/lib_efo/src/error.rs +++ b/lib_efo/src/error.rs @@ -1,7 +1,7 @@ //! Error types that arise when interacting with the storage layer. //! //! These are the only errors emitted by the `Storage` abstraction. They are -//! lightweight, strongly‑typed, and can be converted to the top‑level +//! lightweight, strongly-typed, and can be converted to the top-level //! `AppError` via `thiserror`. //! //! The public items below are all lightweight error types that can be @@ -19,7 +19,7 @@ use miette::Diagnostic; /// Errors that can be returned by the storage layer. /// -/// The variants are intentionally small – each one carries all the +/// The variants are intentionally small - each one carries all the /// information required to surface a helpful message to the user. // TODO[2]: Remove or rethink these errors #[derive(Debug, Error, Diagnostic)] @@ -43,9 +43,9 @@ pub enum StorageError { /// All errors that can occur while working with epochs. /// -/// The enum is deliberately _small_ – each variant is self‑contained and +/// The enum is deliberately _small_ - each variant is self-contained and /// carries the information you need to surface a friendly message -/// to the user (and to the test‑suite). +/// to the user (and to the test-suite). // TODO[2]: Split effectively user errors to avoid the usage of advice and such #[derive(Error, Debug, Diagnostic)] pub enum EpochError { @@ -136,12 +136,12 @@ pub enum EpochError { EpochAlreadyExists(EpochId), /// Attempt to switch to an epoch that has already been advanced past. - #[error("Cannot switch to epoch `{0}` – the world has already advanced beyond it")] + #[error("Cannot switch to epoch `{0}` - the world has already advanced beyond it")] #[diagnostic(code(EpochError::SwitchPastEpoch))] SwitchPastEpoch(EpochId), /// The supplied epoch id is out of bounds (negative, zero or too large). - #[error("Invalid epoch id `{0}` – must be a positive, non‑overflowing integer")] + #[error("Invalid epoch id `{0}` - must be a positive, non-overflowing integer")] #[diagnostic(code(EpochError::InvalidEpochId))] InvalidEpochId(EpochId), @@ -155,7 +155,7 @@ pub enum EpochError { #[diagnostic(code(EpochError::ParentEpochMissing))] ParentEpochMissing(EpochId, EpochId), - /// Generic I/O errors that bubble up from other sub‑tasks. + /// Generic I/O errors that bubble up from other sub-tasks. #[error("I/O error")] #[diagnostic(code(EpochError::GenericIO))] Io { @@ -219,7 +219,7 @@ pub enum EpochError { UserError(#[help] UserErrors), } -/// A small enum of explicit user‑facing error messages. +/// A small enum of explicit user-facing error messages. /// /// The variants are deliberately simple; each one is rendered with a /// clear message via `derive_more::Display`. diff --git a/lib_efo/src/lib.rs b/lib_efo/src/lib.rs index d46903f..69b561e 100644 --- a/lib_efo/src/lib.rs +++ b/lib_efo/src/lib.rs @@ -3,15 +3,15 @@ //! The **engine** that drives *Epoch Forge*. It contains a pure, representation of a fantasy world and all the logic needed to manipulate it. //! //! The crate is split into the following domains, each exposed as a public module: -//! - TODO[1]: `world` – holds the global state (`World`) and a lightweight snapshot (`Context`). -//! - TODO[0]: `epoch` – manages the passage of time and epoch switching. -//! - TODO[1]: `event` – CRUD and evaluation of events that affect the world. -//! - TODO[4]: `org` – organisations, guilds, factions and their history. -//! - TODO[2]: `character` – individual characters, traits and lineage. -//! - TODO[1]: `town` – towns, cities, trade hubs and their populations. -//! - TODO[2]: `link` – relations such as wars, alliances, roads, commerce. -//! - TODO[3]: `storage` – generic persistence layer (`Store`) with JSON/YAML back‑ends. -//! - TODO[4]: `util` – small helpers, ID generation, error types, etc. +//! - TODO[1]: `world` - holds the global state (`World`) and a lightweight snapshot (`Context`). +//! - TODO[0]: `epoch` - manages the passage of time and epoch switching. +//! - TODO[1]: `event` - CRUD and evaluation of events that affect the world. +//! - TODO[4]: `org` - organisations, guilds, factions and their history. +//! - TODO[2]: `character` - individual characters, traits and lineage. +//! - TODO[1]: `town` - towns, cities, trade hubs and their populations. +//! - TODO[2]: `link` - relations such as wars, alliances, roads, commerce. +//! - TODO[3]: `storage` - generic persistence layer (`Store`) with JSON/YAML back-ends. +//! - TODO[4]: `util` - small helpers, ID generation, error types, etc. //! //! All public types implement `serde::Serialize / Deserialize` so that they can //! be persisted easily. The `World` struct also offers a convenient diff --git a/lib_efo/src/stats.rs b/lib_efo/src/stats.rs index 4290d4a..159a06d 100644 --- a/lib_efo/src/stats.rs +++ b/lib_efo/src/stats.rs @@ -4,10 +4,10 @@ //! 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. +//! 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. #![allow(dead_code)] #![deny(clippy::missing_docs_in_private_items)] @@ -32,195 +32,195 @@ 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. + /// **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. 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. + /// **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. pub population: GenericStat, - /// Per‑turn change in population. + /// 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`. + /// **Purpose** - The growth rate of the population. + /// **Effect** - Predicts future needs and signals potential social unrest. + /// **Source** - Derived from `population`, `happiness`, and `stability`. pub growth_rate: GenericStat, - /// Crime level (0–1 scale). + /// 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). + /// **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). pub crime: GenericStat, - /// Base happiness of the population (0–1 scale). + /// 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). + /// **Purpose** - A measure of citizen contentment. + /// **Effect** - Influences productivity, tax compliance, and unrest. + /// **Source** - Output of the happiness function (affected by class, war, infrastructure). 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. + /// **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. 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`. + /// **Purpose** - Amount of consumable resources available. + /// **Effect** - Keeps the population alive and productive. + /// **Source** - `food = farm_yield + tech_level`. pub food: GenericStat, /// Strength of the industry. /// - /// **Purpose** – Industrial production capacity. - /// **Effect** – Drives tax revenue and unit production. - /// **Source** – `industry = factory_output + tech_level`. + /// **Purpose** - Industrial production capacity. + /// **Effect** - Drives tax revenue and unit production. + /// **Source** - `industry = factory_output + tech_level`. 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`. + /// **Purpose** - Rate of research progress. + /// **Effect** - Determines how quickly new technologies are unlocked. + /// **Source** - `science = research_center_output + tech_level`. pub science: GenericStat, /// Trade volume / exports. /// - /// **Purpose** – Measure of export activity. - /// **Effect** – Influences influence and wealth. - /// **Source** – `trade = trade_network_output`. + /// **Purpose** - Measure of export activity. + /// **Effect** - Influences influence and wealth. + /// **Source** - `trade = trade_network_output`. 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. + // /// **Purpose** - Reflects the cultural standing of the entity. + // /// **Effect** - Affects diplomacy and citizen morale. + // /// **Source** - Sum of `culture`, `education`, `tourism`, etc. // 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)`. + // /// **Purpose** - Measure of cultural production. + // /// **Effect** - Drives tourism, prestige, and happiness. + // /// **Source** - `culture = Σ(cultural_building_output)`. // 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)`. + // /// **Purpose** - Measure of the citizenry's knowledge. + // /// **Effect** - Improves productivity, science output, and reduces unrest. + // /// **Source** - `education = Σ(education_building_output)`. // pub education: GenericStat, // /// Tourism revenue. // /// - // /// **Purpose** – Income generated by visitors. - // /// **Effect** – Provides an additional income stream. - // /// **Source** – `tourism = number_of_tourists × price_per_tourist`. + // /// **Purpose** - Income generated by visitors. + // /// **Effect** - Provides an additional income stream. + // /// **Source** - `tourism = number_of_tourists x price_per_tourist`. // 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 × population`. + // /// **Purpose** - Measure of soft power. + // /// **Effect** - Grants diplomatic bonuses and increases sway in the empire. + // /// **Source** - `influence = culture x population`. // 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. + /// **Purpose** - Composite measure of combat capability. + /// **Effect** - Determines defensive and offensive strength. + /// **Source** - Sum of `army`, `strength`, `fortification`, etc. pub military: GenericStat, - /// Number of battle‑ready units. + /// 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. + /// **Purpose** - Size of the active army. + /// **Effect** - Directly dictates defense and attack potential. + /// **Source** - Sum of all trained and equipped units. 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) × tech_bonus × training_bonus`. + /// **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`. pub strength: GenericStat, /// Defensive bonus from fortifications. /// - /// **Purpose** – Wall and tower defenses. - /// **Effect** – Adds a multiplier to overall defense. - /// **Source** – `fortification = Σ(fortification_building_bonus)`. + /// **Purpose** - Wall and tower defenses. + /// **Effect** - Adds a multiplier to overall defense. + /// **Source** - `fortification = Σ(fortification_building_bonus)`. 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`. + /// **Purpose** - Likelihood of being attacked. + /// **Effect** - Triggers early warning alerts and strategic decisions. + /// **Source** - `threat = (enemy_proximity + enemy_strength) / defense`. pub threat: GenericStat, // ──────────────────────── Infrastructure ──────────────────────── /// Total infrastructure power. /// - /// **Purpose** – Overall built‑environment capacity. - /// **Effect** – Supports population size and efficiency. - /// **Source** – Sum of all infrastructure components. + /// **Purpose** - Overall built-environment capacity. + /// **Effect** - Supports population size and efficiency. + /// **Source** - Sum of all infrastructure components. 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)`. + /// **Purpose** - Efficiency of the city's administrative machinery. + /// **Effect** - Improves resource management and policy implementation. + /// **Source** - `bureaucracy = Σ(bureaucracy_building_output)`. pub bureaucracy: GenericStat, /// Transportation level. /// - /// **Purpose** – Availability and quality of transport infrastructure. - /// **Effect** – Impacts logistics, mobility, and trade. - /// **Source** – `transportation = Σ(transport_building_output)`. + /// **Purpose** - Availability and quality of transport infrastructure. + /// **Effect** - Impacts logistics, mobility, and trade. + /// **Source** - `transportation = Σ(transport_building_output)`. pub transportation: GenericStat, /// Sprawl / urban density. /// - /// **Purpose** – Measure of city sprawl and clutter. - /// **Effect** – Affects health, happiness, and infrastructure efficiency. - /// **Source** – `sprawl = Σ(sprawl_factor)`. + /// **Purpose** - Measure of city sprawl and clutter. + /// **Effect** - Affects health, happiness, and infrastructure efficiency. + /// **Source** - `sprawl = Σ(sprawl_factor)`. 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.). + /// **Purpose** - Public health capacity. + /// **Effect** - Affects population health and can generate unrest. + /// **Source** - `health = output_of_health_function` (influenced by sanitation, disease spread, etc.). pub health: GenericStat, } -/// Strategic context and meta‑data for an entity. +/// Strategic context and meta-data for an entity. /// -/// All fields are intentionally simple – the logic that interprets them +/// 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. + /// **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 @@ -228,61 +228,61 @@ pub struct MetaStats { // /// List of nearby resource nodes (mines, forests, farms, etc.). // /// - // /// **Purpose** – Resource map around the entity. - // /// **Effect** – Drives the entity’s specialization and determines + // /// **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)`. + // /// **Source** - `resources = filter(resource_list, distance ≤ detection_radius)`. // pub resources: Vec, - // /// The entity’s chosen specialization tag + // /// 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`. + // /// **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 + /// **Purpose** - Leadership identity. + /// **Effect** - Adds personal bonuses and may modify policies /// or diplomatic stance. - /// **Source** – `governor = selected_leader_uuid`. + /// **Source** - `governor = selected_leader_uuid`. pub governor: CharacterId, - // /// The entity’s classification (capital, trade hub, frontier post, etc.). + // /// The entity's classification (capital, trade hub, frontier post, etc.). // /// - // /// **Purpose** – Functional role within the empire. - // /// **Effect** – Alters base production, tax rates, and + // /// **Purpose** - Functional role within the empire. + // /// **Effect** - Alters base production, tax rates, and // /// certain event probabilities. - // /// **Source** – `role = tag_assigned_by_player_or_ai`. + // /// **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`. + /// **Purpose** - Political affiliation. + /// **Effect** - Determines diplomatic relations, war status, + /// and access to empire-wide bonuses. + /// **Source** - `faction = current_faction_uuid`. pub faction: FactionId, /// UIDs of all entities the entity is linked to (roads, trade routes, /// alliances, war declarations, etc.). /// - /// **Purpose** – Connectivity network. - /// **Effect** – Influences economic, military, and diplomatic + /// **Purpose** - Connectivity network. + /// **Effect** - Influences economic, military, and diplomatic /// interactions. - /// **Source** – `links = Vec` collected from the entity’s + /// **Source** - `links = Vec` collected from the entity's /// network manager. pub links: Vec, /// Prestige / reputation of the entity in the eyes of the empire /// and foreign powers. /// - /// **Purpose** – Social standing metric. - /// **Effect** – Affects diplomatic influence, trade bonuses, + /// **Purpose** - Social standing metric. + /// **Effect** - Affects diplomatic influence, trade bonuses, /// and event outcomes. - /// **Source** – `prestige = calculate_prestige(...)`. + /// **Source** - `prestige = calculate_prestige(...)`. pub prestige: usize, } @@ -380,18 +380,18 @@ thin_newtype!(FactionId, usize); // --- TRAITS --------------------------------------------------------------- /// A stat is a *game value* that can be converted to two different -/// normalised ranges – a 50‑point range for “gaming” logic and a -/// 10‑point range for “roll & UI” logic. The trait also exposes the +/// normalised ranges - a 50-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. + /// Convert the raw integer to a 50-point scale. fn to_50(&self) -> isize { (self.get_value().clamp(0, 70) - 10).min(50) } - /// Convert the raw integer to a 10‑point scale. + /// Convert the raw integer to a 10-point scale. fn to_10(&self) -> isize { self.to_50() / 5 } diff --git a/lib_efo/src/stats/implementations.rs b/lib_efo/src/stats/implementations.rs index b55f8ad..a9b0d0e 100644 --- a/lib_efo/src/stats/implementations.rs +++ b/lib_efo/src/stats/implementations.rs @@ -10,12 +10,12 @@ use crate::stats::ListStats; use crate::stats::OverallStats; use crate::stats::StatPair; -/// Creates a thin, deref‑able wrapper around an inner type. +/// Creates a thin, deref-able wrapper around an inner type. #[macro_export] macro_rules! thin_newtype { ($name:ident, $inner:ty) => { /// Thin wrapper that derefs to the inner type. - /// Ideal for zero‑overhead new‑type patterns. + /// Ideal for zero-overhead new-type patterns. #[repr(transparent)] #[derive( Debug, diff --git a/lib_efo/src/utils.rs b/lib_efo/src/utils.rs index 67aac5b..0f0ecbc 100644 --- a/lib_efo/src/utils.rs +++ b/lib_efo/src/utils.rs @@ -17,7 +17,7 @@ pub fn is_a_epoch_directory(_path: &Path) -> Result<(), EpochError> { todo!() } -/// Validate that the configuration file at `path` is well‑formed. +/// Validate that the configuration file at `path` is well-formed. pub fn is_config_well_formated(_path: &Path) -> Result<(), EpochError> { todo!() } -- 2.45.1 From ac7dd20e031a3f1deab155cbdac8dc1ccf89f83b Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sun, 30 Nov 2025 19:35:19 +0100 Subject: [PATCH 15/22] Adds some more events --- lib_efo/naming.json | 198 +++++++++++++++++++++++++----------------- lib_efo/src/naming.rs | 48 +++++++--- lib_efo/src/stats.rs | 2 +- 3 files changed, 156 insertions(+), 92 deletions(-) diff --git a/lib_efo/naming.json b/lib_efo/naming.json index 9402d35..5fbd840 100644 --- a/lib_efo/naming.json +++ b/lib_efo/naming.json @@ -434,7 +434,10 @@ "name": "earthquake", "description": "A massive quake ripples across the region.", "stats": [ - { "stat": "Infrastructure", "value": -15 }, + { "stat": "Transportation", "value": -9 }, + { "stat": "Sprawl", "value": -5 }, + { "stat": "Health", "value": -3 }, + { "stat": "Industry", "value": -2 }, { "stat": "Population", "value": -10 }, { "stat": "Happiness", "value": -8 } ] @@ -452,9 +455,10 @@ "name": "town_haunted_market", "description": "Spectral merchants appear, selling wares that vanish upon purchase, driving up prices.", "stats": [ - { "stat": "Trade", "value": -9 }, - { "stat": "Economy", "value": -6 }, - { "stat": "Crime", "value": 4 } + { "stat": "Trade", "value": 9 }, + { "stat": "Food", "value": 13 }, + { "stat": "Crime", "value": 4 }, + { "stat": "Threat", "value": 8 } ] }, { @@ -470,7 +474,9 @@ "name": "town_giant_earthworm", "description": "A colossal earthworm burrows beneath the town, destabilizing foundations and causing tremors.", "stats": [ - { "stat": "Infrastructure", "value": -12 }, + { "stat": "Food", "value": -5 }, + { "stat": "Industry", "value": -2 }, + { "stat": "Happiness", "value": -12 }, { "stat": "Fortification", "value": -8 }, { "stat": "Population", "value": -4 } ] @@ -497,7 +503,9 @@ "name": "region_infernal_flood", "description": "Molten rivers run through the region, boiling over cities and devouring forests.", "stats": [ - { "stat": "Infrastructure", "value": -20 }, + { "stat": "Transportation", "value": -4 }, + { "stat": "Sprawl", "value": -5 }, + { "stat": "Happiness", "value": -19 }, { "stat": "Food", "value": -15 }, { "stat": "Population", "value": -12 } ] @@ -506,7 +514,9 @@ "name": "region_sand_vortex", "description": "A vortex of shifting sands sweeps the region, burying entire nations under dunes.", "stats": [ - { "stat": "Infrastructure", "value": -14 }, + { "stat": "Bureaucracy", "value": -14 }, + { "stat": "Transportation", "value": -14 }, + { "stat": "Sprawl", "value": -14 }, { "stat": "Population", "value": -16 }, { "stat": "Trade", "value": -10 } ] @@ -516,7 +526,7 @@ "description": "A relentless gale from the gods tears through the region, scattering armies and wrecking supply lines.", "stats": [ { "stat": "Transportation", "value": -12 }, - { "stat": "Military", "value": -9 }, + { "stat": "Army", "value": -9 }, { "stat": "Population", "value": -3 } ] }, @@ -542,25 +552,31 @@ "name": "city_corruption_scandal", "description": "A high-ranking magistrate is discovered embezzling city funds, sparking public outrage and a demand for accountability.", "stats": [ - { "stat": "Economy", "value": -9 }, + { "stat": "Food", "value": -4 }, + { "stat": "Industry", "value": -3 }, + { "stat": "Science", "value": -3 }, + { "stat": "Trade", "value": -8 }, { "stat": "Bureaucracy", "value": -7 }, - { "stat": "Crime", "value": 5 } + { "stat": "Crime", "value": 7 } ] }, { "name": "city_tax_reform", "description": "The council implements a sweeping tax overhaul that raises revenue but triggers protests among merchants.", "stats": [ - { "stat": "Economy", "value": 12 }, - { "stat": "Population", "value": -4 }, - { "stat": "Crime", "value": 3 } + { "stat": "Food", "value": 9 }, + { "stat": "Industry", "value": 10 }, + { "stat": "Science", "value": 7 }, + { "stat": "Trade", "value": 13 }, + { "stat": "Happiness", "value": -4 }, + { "stat": "Crime", "value": 5 } ] }, { "name": "city_watch_mutiny", "description": "The city guard, disgruntled by unpaid wages, mutinies and seizes control of the main gate.", "stats": [ - { "stat": "Military", "value": -6 }, + { "stat": "Strength", "value": -6 }, { "stat": "Crime", "value": 8 }, { "stat": "Population", "value": -2 } ] @@ -578,9 +594,13 @@ "name": "city_bureaucratic_bureaucracy", "description": "A new procedural reform overhauls city administration, halting projects for months and stalling economic growth.", "stats": [ - { "stat": "Infrastructure", "value": -7 }, - { "stat": "Economy", "value": -5 }, - { "stat": "Bureaucracy", "value": 10 } + { "stat": "Bureaucracy", "value": 14 }, + { "stat": "Sprawl", "value": -9 }, + { "stat": "Health", "value": -7 }, + { "stat": "Food", "value": 3 }, + { "stat": "Industry", "value": 2 }, + { "stat": "Science", "value": 3 }, + { "stat": "Trade", "value": 4 } ] }, { @@ -596,7 +616,7 @@ "name": "city_civic_riot", "description": "An assembly of disgruntled workers erupts into a violent riot, tearing through market stalls and public buildings.", "stats": [ - { "stat": "Infrastructure", "value": -12 }, + { "stat": "Trade", "value": -12 }, { "stat": "Happiness", "value": -9 }, { "stat": "Crime", "value": 10 } ] @@ -614,7 +634,7 @@ "name": "city_transport_infrastructure_fail", "description": "The city's main aqueduct collapses, cutting off water supply to half the districts.", "stats": [ - { "stat": "Infrastructure", "value": -15 }, + { "stat": "Transportation", "value": -15 }, { "stat": "Population", "value": -4 }, { "stat": "Bureaucracy", "value": -2 } ] @@ -632,7 +652,8 @@ "name": "city_gold_exodus", "description": "A sudden discovery of gold in the hinterlands draws merchants away, leaving local markets starved of currency.", "stats": [ - { "stat": "Economy", "value": -11 }, + { "stat": "Food", "value": -4 }, + { "stat": "Industry", "value": -4 }, { "stat": "Trade", "value": -8 }, { "stat": "Population", "value": -2 } ] @@ -642,7 +663,7 @@ "description": "An extended dry spell cripples crop yields, driving up food prices and crippling the agrarian economy.", "stats": [ { "stat": "Food", "value": -15 }, - { "stat": "Economy", "value": -9 }, + { "stat": "Trade", "value": -13 }, { "stat": "Happiness", "value": -5 } ] }, @@ -651,15 +672,18 @@ "description": "The city council imposes a high tariff on imported goods to boost local industry, sparking backlash from merchants.", "stats": [ { "stat": "Trade", "value": -10 }, - { "stat": "Economy", "value": 7 }, - { "stat": "Crime", "value": 4 } + { "stat": "Food", "value": -4 }, + { "stat": "Industry", "value": -6 }, + { "stat": "Science", "value": -3 }, + { "stat": "Crime", "value": 15 } ] }, { "name": "market_hoarding", "description": "A powerful merchant cartel hoards staple goods, manipulating prices to inflate profits at the cost of ordinary citizens.", "stats": [ - { "stat": "Economy", "value": -8 }, + { "stat": "Food", "value": -7 }, + { "stat": "Industry", "value": -6 }, { "stat": "Trade", "value": -7 }, { "stat": "Population", "value": -3 } ] @@ -669,7 +693,9 @@ "description": "A catastrophic blast at the main ironworks destroys equipment and halts production for months.", "stats": [ { "stat": "Industry", "value": -18 }, - { "stat": "Economy", "value": -12 }, + { "stat": "Food", "value": -3 }, + { "stat": "Industry", "value": -13 }, + { "stat": "Trade", "value": -7 }, { "stat": "Population", "value": -4 } ] }, @@ -678,7 +704,8 @@ "description": "A foreign dynasty invests heavily in local mining, sparking a surge in jobs and wealth but also widening inequality.", "stats": [ { "stat": "Industry", "value": 12 }, - { "stat": "Economy", "value": 9 }, + { "stat": "Science", "value": 3 }, + { "stat": "Trade", "value": 8 }, { "stat": "Crime", "value": 5 } ] }, @@ -686,7 +713,10 @@ "name": "tax_evasion_scheme", "description": "A sophisticated tax evasion network siphons off a large portion of city revenue, forcing austerity measures.", "stats": [ - { "stat": "Economy", "value": -10 }, + { "stat": "Food", "value": -8 }, + { "stat": "Industry", "value": -7 }, + { "stat": "Trade", "value": -9 }, + { "stat": "Crime", "value": 15 }, { "stat": "Bureaucracy", "value": -6 }, { "stat": "Population", "value": -2 } ] @@ -695,7 +725,8 @@ "name": "currency_devaluation", "description": "The city's coinage is devalued by a sudden policy shift, causing imported goods to skyrocket in price.", "stats": [ - { "stat": "Economy", "value": -13 }, + { "stat": "Food", "value": -8 }, + { "stat": "Industry", "value": -3 }, { "stat": "Trade", "value": -9 }, { "stat": "Health", "value": -4 } ] @@ -705,7 +736,8 @@ "description": "A grand artisan fair attracts wealthy patrons, boosting local crafts and increasing export revenues.", "stats": [ { "stat": "Industry", "value": 8 }, - { "stat": "Economy", "value": 6 }, + { "stat": "Industry", "value": 9 }, + { "stat": "Trade", "value": 9 }, { "stat": "Population", "value": 2 } ] }, @@ -714,8 +746,10 @@ "description": "Sea-borne raiders seize a shipment of precious stones destined for the city, flooding the market with counterfeit goods.", "stats": [ { "stat": "Trade", "value": -12 }, - { "stat": "Economy", "value": -7 }, - { "stat": "Crime", "value": 9 } + { "stat": "Food", "value": -7 }, + { "stat": "Industry", "value": -6 }, + { "stat": "Threat", "value": 3 }, + { "stat": "Crime", "value": 14 } ] }, { @@ -723,7 +757,8 @@ "description": "A critical failure in the city's primary steel furnace sparks an uncontrollable fire, destroying production lines.", "stats": [ { "stat": "Industry", "value": -17 }, - { "stat": "Economy", "value": -10 }, + { "stat": "Trade", "value": -9 }, + { "stat": "Happiness", "value": -2 }, { "stat": "Population", "value": -3 } ] }, @@ -732,7 +767,9 @@ "description": "A guild of master craftsmen invents a new forging technique that doubles output and lowers raw material usage.", "stats": [ { "stat": "Industry", "value": 14 }, - { "stat": "Economy", "value": 8 }, + { "stat": "Industry", "value": 13 }, + { "stat": "Science", "value": 15 }, + { "stat": "Trade", "value": 9 }, { "stat": "Crime", "value": 3 } ] }, @@ -741,7 +778,6 @@ "description": "Covert saboteurs collapse a major coal shaft, halting fuel supply to all local factories for weeks.", "stats": [ { "stat": "Industry", "value": -15 }, - { "stat": "Economy", "value": -9 }, { "stat": "Crime", "value": 6 } ] }, @@ -750,7 +786,6 @@ "description": "A foreign conglomerate purchases the city's largest textile mill, imposing new quotas that reduce local employment.", "stats": [ { "stat": "Industry", "value": -9 }, - { "stat": "Economy", "value": -7 }, { "stat": "Population", "value": -4 } ] }, @@ -759,7 +794,7 @@ "description": "Skilled blacksmiths organize a strike demanding better wages, halting the production of critical weapons.", "stats": [ { "stat": "Industry", "value": -10 }, - { "stat": "Military", "value": -5 }, + { "stat": "Strength", "value": -5 }, { "stat": "Crime", "value": 4 } ] }, @@ -776,27 +811,17 @@ "name": "bottleneck_transportation", "description": "The city's main rail line is seized by gangsters, disrupting the flow of raw materials to factories.", "stats": [ - { "stat": "Infrastructure", "value": -8 }, + { "stat": "Transportation", "value": -8 }, { "stat": "Industry", "value": -6 }, { "stat": "Crime", "value": 7 } ] }, - { - "name": "energy_rationing", - "description": "A sudden spike in electricity prices forces factories to shut down during peak hours, halving output.", - "stats": [ - { "stat": "Industry", "value": -13 }, - { "stat": "Economy", "value": -8 }, - { "stat": "Population", "value": -2 } - ] - }, { "name": "export_tariff_relief", "description": "An unexpected removal of export tariffs on metal goods opens new markets, boosting production rates.", "stats": [ { "stat": "Industry", "value": 12 }, - { "stat": "Trade", "value": 9 }, - { "stat": "Economy", "value": 6 } + { "stat": "Trade", "value": 9 } ] }, { @@ -812,18 +837,16 @@ "name": "frontline_betrayal", "description": "A key vanguard commander secretly defects, scattering a significant portion of the army and boosting enemy threat.", "stats": [ - { "stat": "Army", "value": -10 }, - { "stat": "Military", "value": -6 }, - { "stat": "Threat", "value": 8 } + { "stat": "Strength", "value": -6 }, + { "stat": "Threat", "value": 11 } ] }, { "name": "naval_battle_victory", "description": "The city's navy defeats a hostile threat, securing coastal trade routes and striking a blow to the enemy's threat level.", "stats": [ - { "stat": "Military", "value": 12 }, - { "stat": "Threat", "value": -9 }, - { "stat": "Economy", "value": 4 } + { "stat": "Strength", "value": 12 }, + { "stat": "Threat", "value": -9 } ] }, { @@ -832,7 +855,7 @@ "stats": [ { "stat": "Army", "value": -14 }, { "stat": "Health", "value": -10 }, - { "stat": "Military", "value": -5 } + { "stat": "Strength", "value": -5 } ] }, { @@ -841,7 +864,7 @@ "stats": [ { "stat": "Army", "value": 8 }, { "stat": "Strength", "value": -9 }, - { "stat": "Military", "value": -3 } + { "stat": "Threat", "value": 3 } ] }, { @@ -850,7 +873,7 @@ "stats": [ { "stat": "Strength", "value": 11 }, { "stat": "Army", "value": -6 }, - { "stat": "Military", "value": 4 } + { "stat": "Threat", "value": -5 } ] }, { @@ -858,7 +881,7 @@ "description": "A covert spy network uncovers threats around, reducing the threat level and providing a tactical advantage.", "stats": [ { "stat": "Threat", "value": -10 }, - { "stat": "Military", "value": 3 }, + { "stat": "Influence", "value": 3 }, { "stat": "Strength", "value": 4 } ] }, @@ -866,9 +889,12 @@ "name": "war_taxes_harsh", "description": "The council imposes severe war taxes to fund the army, inflating military budgets but cracking public happiness.", "stats": [ - { "stat": "Military", "value": 9 }, + { "stat": "Strength", "value": 9 }, { "stat": "Happiness", "value": -8 }, - { "stat": "Economy", "value": -5 } + { "stat": "Food", "value": -3 }, + { "stat": "Industry", "value": -3 }, + { "stat": "Science", "value": -3 }, + { "stat": "Trade", "value": -3 } ] }, { @@ -876,8 +902,7 @@ "description": "A revolutionary tactic is adopted on the front lines, dramatically boosting army strength and lowering enemy threat.", "stats": [ { "stat": "Strength", "value": 13 }, - { "stat": "Threat", "value": -8 }, - { "stat": "Military", "value": 2 } + { "stat": "Threat", "value": -8 } ] }, { @@ -885,7 +910,10 @@ "description": "The city brokered a favorable trade pact with a neighboring realm, opening new markets for local goods.", "stats": [ { "stat": "Trade", "value": 12 }, - { "stat": "Economy", "value": 8 }, + { "stat": "Food", "value": 3 }, + { "stat": "Industry", "value": 3 }, + { "stat": "Science", "value": 3 }, + { "stat": "Trade", "value": 3 }, { "stat": "Population", "value": 3 } ] }, @@ -913,7 +941,8 @@ "stats": [ { "stat": "Science", "value": 15 }, { "stat": "Industry", "value": 6 }, - { "stat": "Economy", "value": 5 } + { "stat": "Food", "value": 3 }, + { "stat": "Trade", "value": 3 } ] }, { @@ -921,7 +950,10 @@ "description": "A grand festival draws wealthy merchants and foreign dignitaries, boosting tourism and local pride.", "stats": [ { "stat": "Tourism", "value": 13 }, - { "stat": "Economy", "value": 7 }, + { "stat": "Science", "value": 3 }, + { "stat": "Trade", "value": 3 }, + { "stat": "Culture", "value": 3 }, + { "stat": "Influence", "value": 3 }, { "stat": "Happiness", "value": 6 } ] }, @@ -931,7 +963,7 @@ "stats": [ { "stat": "Strength", "value": 12 }, { "stat": "Army", "value": 3 }, - { "stat": "Military", "value": 4 } + { "stat": "Threat", "value": -5 } ] }, { @@ -948,7 +980,8 @@ "description": "A gathering of master artisans leads to the sharing of techniques that double production efficiency.", "stats": [ { "stat": "Industry", "value": 14 }, - { "stat": "Economy", "value": 6 }, + { "stat": "Science", "value": 8 }, + { "stat": "Trade", "value": 3 }, { "stat": "Population", "value": 2 } ] }, @@ -956,9 +989,13 @@ "name": "infrastructure_repair", "description": "A massive repair drive restores crumbling roads and bridges, slashing travel time and boosting trade.", "stats": [ - { "stat": "Infrastructure", "value": 15 }, - { "stat": "Trade", "value": 5 }, - { "stat": "Economy", "value": 3 } + { "stat": "Sprawl", "value": 10 }, + { "stat": "Transportation", "value": 9 }, + { "stat": "Health", "value": 7 }, + { "stat": "Industry", "value": 7 }, + { "stat": "Trade", "value": 7 }, + { "stat": "Food", "value": 5 }, + { "stat": "Trade", "value": 4 } ] }, { @@ -975,7 +1012,7 @@ "name": "great_earthquake", "description": "A massive quake rips through the city, shattering buildings, collapsing bridges, and killing thousands.", "stats": [ - { "stat": "Infrastructure", "value": -20 }, + { "stat": "Health", "value": -19 }, { "stat": "Population", "value": -18 }, { "stat": "Happiness", "value": -15 } ] @@ -984,8 +1021,8 @@ "name": "plague_of_scorpion", "description": "A deadly disease spreads through the populace, turning citizens into venom-infused monsters.", "stats": [ - { "stat": "Health", "value": -22 }, - { "stat": "Population", "value": -16 }, + { "stat": "Health", "value": -14 }, + { "stat": "Population", "value": -10 }, { "stat": "Crime", "value": 8 } ] }, @@ -993,8 +1030,8 @@ "name": "oil_fire_in_barnyard", "description": "An oil storage depot explodes, sending a wave of fire over the city that reduces the army's morale and strength.", "stats": [ - { "stat": "Industry", "value": -19 }, - { "stat": "Military", "value": -12 }, + { "stat": "Industry", "value": -9 }, + { "stat": "Happiness", "value": -4 }, { "stat": "Threat", "value": 10 } ] }, @@ -1011,8 +1048,9 @@ "name": "cursed_great_flood", "description": "An unseasonal deluge swallows the city, flooding every district, destroying crops, and causing widespread disease.", "stats": [ - { "stat": "Food", "value": -20 }, - { "stat": "Economy", "value": -17 }, + { "stat": "Food", "value": -13 }, + { "stat": "Industry", "value": -6 }, + { "stat": "Trade", "value": -8 }, { "stat": "Threat", "value": 13 } ] }, @@ -1021,15 +1059,15 @@ "description": "A minor calamity overpowers the city's fortifications, unleashing a wave of slaughter and chaos.", "stats": [ { "stat": "Fortification", "value": -19 }, - { "stat": "Threat", "value": 20 }, + { "stat": "Threat", "value": 19 }, { "stat": "Happiness", "value": -12 } ] }, { "name": "invasion_of_the_undead", - "description": "A horde of reanimated skeletons breaks through the gates, attacking citizens and military alike.", + "description": "A horde of reanimated civilians under the influence of a calamity attack citizens and military alike.", "stats": [ - { "stat": "Threat", "value": 25 }, + { "stat": "Threat", "value": 14 }, { "stat": "Crime", "value": -10 }, { "stat": "Population", "value": -12 } ] diff --git a/lib_efo/src/naming.rs b/lib_efo/src/naming.rs index 02aa54c..9687453 100644 --- a/lib_efo/src/naming.rs +++ b/lib_efo/src/naming.rs @@ -149,15 +149,8 @@ pub static NAMING: Lazy = Lazy::new(|| { #[cfg(test)] mod tests { use super::*; - // use std::fs::{self, File}; - // use std::io::Write; - // use std::path::PathBuf; - - /// Helper that deserialises the embedded default JSON so we can compare against it. - fn default_data() -> NamingData { - serde_json::from_str::(DEFAULT_JSON_STR) - .expect("DEFAULT_JSON_STR should be a valid JSON") - } + use crate::stats::ListStats; + use std::collections::HashMap; #[test] fn try_load() {} @@ -172,7 +165,40 @@ mod tests { println!("Town: {}", town); // 3. Pick an event idea - let event = NAMING.generate_long_character_name(); - println!("Event idea: {}", event); + let character = NAMING.generate_long_character_name(); + println!("Event idea: {}", character); + + let _ = NAMING.random_event_idea(); + } + + #[test] + // TODO[Work]: Add this to a recap function + fn test_all_events() { + let mut values: HashMap = HashMap::new(); + for event in &NAMING.event_ideas { + println!("Testing event: {:?}", event); + assert!(event.stats.len() > 1); + + for stat in &event.stats { + if let s @ (ListStats::Demographics + | ListStats::Military + | ListStats::Economy + | ListStats::Social + | ListStats::Infrastructure) = stat.stat + { + panic!("Bad stat used {s:?}") + }; + match stat.value.abs() { + 0..5 => (), + 5..10 => (), + 10..20 => println!("Big stat"), + s => panic!("The event has a stat that is way too big {s}"), + } + let base_value = values.get(&stat.stat).unwrap_or(&0); + values.insert(stat.stat, base_value + 1); + } + } + println!("{values:#?}"); + // panic!() } } diff --git a/lib_efo/src/stats.rs b/lib_efo/src/stats.rs index 159a06d..60a9f6b 100644 --- a/lib_efo/src/stats.rs +++ b/lib_efo/src/stats.rs @@ -286,7 +286,7 @@ pub struct MetaStats { pub prestige: usize, } -/// A generic stat pair with (stat, value), used mainly for clap +/// 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) -- 2.45.1 From 9761978ad9f86e183a888f7e1b61d7416c6fee24 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sun, 30 Nov 2025 22:22:12 +0100 Subject: [PATCH 16/22] Updating events --- lib_efo/naming.json | 438 ++++++++++++++++++++++++++++++++++-------- lib_efo/src/entity.rs | 111 ++++++++++- lib_efo/src/naming.rs | 15 +- lib_efo/src/stats.rs | 2 +- 4 files changed, 474 insertions(+), 92 deletions(-) diff --git a/lib_efo/naming.json b/lib_efo/naming.json index 5fbd840..e52ffc5 100644 --- a/lib_efo/naming.json +++ b/lib_efo/naming.json @@ -428,7 +428,11 @@ "stats": [ { "stat": "Population", "value": -5 }, { "stat": "Food", "value": -12 } - ] + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 10, "max": 70 }, + "strength": 20 }, { "name": "earthquake", @@ -440,8 +444,13 @@ { "stat": "Industry", "value": -2 }, { "stat": "Population", "value": -10 }, { "stat": "Happiness", "value": -8 } - ] + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 10, "max": 110 }, + "strength": 80 }, + { "name": "region_blood_monsoon", "description": "A crimson rain falls over the region, poisoning crops and water sources.", @@ -449,27 +458,43 @@ { "stat": "Food", "value": -18 }, { "stat": "Health", "value": -12 }, { "stat": "Population", "value": -7 } - ] + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 10, "max": 110 }, + "strength": 70 }, + { "name": "town_haunted_market", - "description": "Spectral merchants appear, selling wares that vanish upon purchase, driving up prices.", + "description": "Spectral merchants appear, selling cryptic ware from a bygone era.", "stats": [ { "stat": "Trade", "value": 9 }, + { "stat": "Science", "value": 9 }, { "stat": "Food", "value": 13 }, - { "stat": "Crime", "value": 4 }, - { "stat": "Threat", "value": 8 } - ] + { "stat": "Crime", "value": 7 }, + { "stat": "Threat", "value": 11 } + ], + "duration": { "Duration": 3 }, + "application": "WhenPresent", + "effect_bounds": { "min": 10, "max": 80 }, + "strength": 60 }, + { "name": "region_darkening_sun", - "description": "The sky is forever shrouded in an unnatural pallid dusk, lowering morale and crop yields.", + "description": "The sky is shrouded in an unnatural pallid dusk, lowering morale and crop yields.", "stats": [ { "stat": "Happiness", "value": -14 }, { "stat": "Food", "value": -10 }, { "stat": "Culture", "value": -5 } - ] + ], + "duration": { "Duration": 6 }, + "application": "WhenPresent", + "effect_bounds": { "min": 20, "max": 90 }, + "strength": 75 }, + { "name": "town_giant_earthworm", "description": "A colossal earthworm burrows beneath the town, destabilizing foundations and causing tremors.", @@ -479,7 +504,11 @@ { "stat": "Happiness", "value": -12 }, { "stat": "Fortification", "value": -8 }, { "stat": "Population", "value": -4 } - ] + ], + "duration": { "Duration": 4 }, + "application": "WhenPresent", + "effect_bounds": { "min": 30, "max": 70 }, + "strength": 65 }, { "name": "region_arcane_surge", @@ -488,7 +517,11 @@ { "stat": "Science", "value": 12 }, { "stat": "Education", "value": 8 }, { "stat": "Population", "value": -6 } - ] + ], + "duration": { "Duration": 6 }, + "application": "WhenPresent", + "effect_bounds": { "min": 30, "max": 70 }, + "strength": 80 }, { "name": "town_mushroom_meteor", @@ -497,7 +530,11 @@ { "stat": "Health", "value": -10 }, { "stat": "Crime", "value": 6 }, { "stat": "Population", "value": -3 } - ] + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 20, "max": 90 }, + "strength": 60 }, { "name": "region_infernal_flood", @@ -508,7 +545,11 @@ { "stat": "Happiness", "value": -19 }, { "stat": "Food", "value": -15 }, { "stat": "Population", "value": -12 } - ] + ], + "duration": { "Duration": 5 }, + "application": "WhenPresent", + "effect_bounds": { "min": 20, "max": 90 }, + "strength": 70 }, { "name": "region_sand_vortex", @@ -519,7 +560,11 @@ { "stat": "Sprawl", "value": -14 }, { "stat": "Population", "value": -16 }, { "stat": "Trade", "value": -10 } - ] + ], + "duration": { "Duration": 5 }, + "application": "WhenPresent", + "effect_bounds": { "min": 20, "max": 90 }, + "strength": 65 }, { "name": "region_wind_of_gods", @@ -528,7 +573,11 @@ { "stat": "Transportation", "value": -12 }, { "stat": "Army", "value": -9 }, { "stat": "Population", "value": -3 } - ] + ], + "duration": { "Duration": 8 }, + "application": "WhenPresent", + "effect_bounds": { "min": 20, "max": 90 }, + "strength": 75 }, { "name": "region_ancient_sunrise", @@ -537,7 +586,11 @@ { "stat": "Crime", "value": 9 }, { "stat": "Happiness", "value": -8 }, { "stat": "Influence", "value": -5 } - ] + ], + "duration": { "Duration": 7 }, + "application": "WhenPresent", + "effect_bounds": { "min": 20, "max": 90 }, + "strength": 70 }, { "name": "town_forest_of_eyes", @@ -545,12 +598,17 @@ "stats": [ { "stat": "Health", "value": -10 }, { "stat": "Crime", "value": 7 }, - { "stat": "Population", "value": -5 } - ] + { "stat": "Happiness", "value": 7 }, + { "stat": "Population", "value": -14 } + ], + "duration": { "Duration": 8 }, + "application": "WhenPresent", + "effect_bounds": { "min": 20, "max": 90 }, + "strength": 80 }, { "name": "city_corruption_scandal", - "description": "A high-ranking magistrate is discovered embezzling city funds, sparking public outrage and a demand for accountability.", + "description": "A high‑ranking magistrate is discovered embezzling city funds, sparking public outrage and a demand for accountability.", "stats": [ { "stat": "Food", "value": -4 }, { "stat": "Industry", "value": -3 }, @@ -558,7 +616,11 @@ { "stat": "Trade", "value": -8 }, { "stat": "Bureaucracy", "value": -7 }, { "stat": "Crime", "value": 7 } - ] + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 22, "max": 86 }, + "strength": 78 }, { "name": "city_tax_reform", @@ -570,16 +632,24 @@ { "stat": "Trade", "value": 13 }, { "stat": "Happiness", "value": -4 }, { "stat": "Crime", "value": 5 } - ] + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 25, "max": 92 }, + "strength": 94 }, { "name": "city_watch_mutiny", - "description": "The city guard, disgruntled by unpaid wages, mutinies and seizes control of the main gate.", + "description": "The city guard, disgruntled by unpaid wages, mutinies turns bandits.", "stats": [ { "stat": "Strength", "value": -6 }, { "stat": "Crime", "value": 8 }, { "stat": "Population", "value": -2 } - ] + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 18, "max": 80 }, + "strength": 66 }, { "name": "city_water_contamination", @@ -588,7 +658,11 @@ { "stat": "Health", "value": -14 }, { "stat": "Population", "value": -5 }, { "stat": "Bureaucracy", "value": -3 } - ] + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 21, "max": 88 }, + "strength": 87 }, { "name": "city_bureaucratic_bureaucracy", @@ -601,7 +675,11 @@ { "stat": "Industry", "value": 2 }, { "stat": "Science", "value": 3 }, { "stat": "Trade", "value": 4 } - ] + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 23, "max": 90 }, + "strength": 82 }, { "name": "city_guild_suppression", @@ -610,7 +688,11 @@ { "stat": "Trade", "value": -11 }, { "stat": "Crime", "value": 6 }, { "stat": "Population", "value": -3 } - ] + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 19, "max": 83 }, + "strength": 68 }, { "name": "city_civic_riot", @@ -619,16 +701,24 @@ { "stat": "Trade", "value": -12 }, { "stat": "Happiness", "value": -9 }, { "stat": "Crime", "value": 10 } - ] + ], + "duration": { "Duration": 2 }, + "application": "WhenPresent", + "effect_bounds": { "min": 25, "max": 95 }, + "strength": 78 }, { "name": "city_public_health_crisis", "description": "A mysterious disease spreads through the city's crowded streets, overwhelming the local infirmaries.", "stats": [ - { "stat": "Health", "value": -16 }, - { "stat": "Population", "value": -8 }, - { "stat": "Happiness", "value": -7 } - ] + { "stat": "Health", "value": -3 }, + { "stat": "Population", "value": -3 }, + { "stat": "Happiness", "value": -2 } + ], + "duration": { "Duration": 6 }, + "application": "Recurring", + "effect_bounds": { "min": 20, "max": 95 }, + "strength": 71 }, { "name": "city_transport_infrastructure_fail", @@ -637,7 +727,11 @@ { "stat": "Transportation", "value": -15 }, { "stat": "Population", "value": -4 }, { "stat": "Bureaucracy", "value": -2 } - ] + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 20, "max": 90 }, + "strength": 70 }, { "name": "city_festival_corruption", @@ -646,7 +740,11 @@ { "stat": "Bureaucracy", "value": -8 }, { "stat": "Crime", "value": 4 }, { "stat": "Happiness", "value": -3 } - ] + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 20, "max": 90 }, + "strength": 70 }, { "name": "city_gold_exodus", @@ -656,7 +754,11 @@ { "stat": "Industry", "value": -4 }, { "stat": "Trade", "value": -8 }, { "stat": "Population", "value": -2 } - ] + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 20, "max": 90 }, + "strength": 70 }, { "name": "regional_drought", @@ -665,7 +767,11 @@ { "stat": "Food", "value": -15 }, { "stat": "Trade", "value": -13 }, { "stat": "Happiness", "value": -5 } - ] + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 20, "max": 90 }, + "strength": 70 }, { "name": "city_tariff_levy", @@ -676,7 +782,11 @@ { "stat": "Industry", "value": -6 }, { "stat": "Science", "value": -3 }, { "stat": "Crime", "value": 15 } - ] + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 20, "max": 90 }, + "strength": 70 }, { "name": "market_hoarding", @@ -686,18 +796,26 @@ { "stat": "Industry", "value": -6 }, { "stat": "Trade", "value": -7 }, { "stat": "Population", "value": -3 } - ] + ], + "duration": { "Duration": 7 }, + "application": "WhenPresent", + "effect_bounds": { "min": 20, "max": 90 }, + "strength": 70 }, + { "name": "industrial_explosion", "description": "A catastrophic blast at the main ironworks destroys equipment and halts production for months.", "stats": [ - { "stat": "Industry", "value": -18 }, + { "stat": "Industry", "value": -19 }, { "stat": "Food", "value": -3 }, - { "stat": "Industry", "value": -13 }, { "stat": "Trade", "value": -7 }, { "stat": "Population", "value": -4 } - ] + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 20, "max": 90 }, + "strength": 70 }, { "name": "foreign_investment_boom", @@ -707,7 +825,11 @@ { "stat": "Science", "value": 3 }, { "stat": "Trade", "value": 8 }, { "stat": "Crime", "value": 5 } - ] + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 20, "max": 90 }, + "strength": 70 }, { "name": "tax_evasion_scheme", @@ -719,7 +841,11 @@ { "stat": "Crime", "value": 15 }, { "stat": "Bureaucracy", "value": -6 }, { "stat": "Population", "value": -2 } - ] + ], + "duration": { "Duration": 6 }, + "application": "WhenPresent", + "effect_bounds": { "min": 25, "max": 95 }, + "strength": 81 }, { "name": "currency_devaluation", @@ -729,7 +855,11 @@ { "stat": "Industry", "value": -3 }, { "stat": "Trade", "value": -9 }, { "stat": "Health", "value": -4 } - ] + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 23, "max": 95 }, + "strength": 76 }, { "name": "artisan_fair_success", @@ -739,18 +869,26 @@ { "stat": "Industry", "value": 9 }, { "stat": "Trade", "value": 9 }, { "stat": "Population", "value": 2 } - ] + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 23, "max": 95 }, + "strength": 77 }, { "name": "resource_piracy", - "description": "Sea-borne raiders seize a shipment of precious stones destined for the city, flooding the market with counterfeit goods.", + "description": "Sea‑borne raiders seize a shipment of precious stones destined for the city, flooding the market with counterfeit goods.", "stats": [ { "stat": "Trade", "value": -12 }, { "stat": "Food", "value": -7 }, { "stat": "Industry", "value": -6 }, { "stat": "Threat", "value": 3 }, { "stat": "Crime", "value": 14 } - ] + ], + "duration": { "Duration": 4 }, + "application": "WhenPresent", + "effect_bounds": { "min": 25, "max": 95 }, + "strength": 80 }, { "name": "steel_furnace_overheat", @@ -760,7 +898,11 @@ { "stat": "Trade", "value": -9 }, { "stat": "Happiness", "value": -2 }, { "stat": "Population", "value": -3 } - ] + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 24, "max": 95 }, + "strength": 77 }, { "name": "artisan_tech_innovation", @@ -771,7 +913,11 @@ { "stat": "Science", "value": 15 }, { "stat": "Trade", "value": 9 }, { "stat": "Crime", "value": 3 } - ] + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 26, "max": 95 }, + "strength": 83 }, { "name": "coal_mine_sabotage", @@ -779,7 +925,11 @@ "stats": [ { "stat": "Industry", "value": -15 }, { "stat": "Crime", "value": 6 } - ] + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 23, "max": 95 }, + "strength": 75 }, { "name": "foreign_factory_purchase", @@ -787,7 +937,11 @@ "stats": [ { "stat": "Industry", "value": -9 }, { "stat": "Population", "value": -4 } - ] + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 22, "max": 95 }, + "strength": 73 }, { "name": "blacksmiths_rebel", @@ -796,7 +950,11 @@ { "stat": "Industry", "value": -10 }, { "stat": "Strength", "value": -5 }, { "stat": "Crime", "value": 4 } - ] + ], + "duration": { "Duration": 6 }, + "application": "WhenPresent", + "effect_bounds": { "min": 22, "max": 95 }, + "strength": 74 }, { "name": "machine_revolution", @@ -805,16 +963,24 @@ { "stat": "Industry", "value": 11 }, { "stat": "Population", "value": -5 }, { "stat": "Crime", "value": 3 } - ] + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 22, "max": 95 }, + "strength": 74 }, { "name": "bottleneck_transportation", - "description": "The city's main rail line is seized by gangsters, disrupting the flow of raw materials to factories.", + "description": "The city's main mean of transportation is seized by gangsters, disrupting the flow of raw materials to factories.", "stats": [ { "stat": "Transportation", "value": -8 }, { "stat": "Industry", "value": -6 }, { "stat": "Crime", "value": 7 } - ] + ], + "duration": { "Duration": 3 }, + "application": "WhenPresent", + "effect_bounds": { "min": 23, "max": 95 }, + "strength": 75 }, { "name": "export_tariff_relief", @@ -822,7 +988,11 @@ "stats": [ { "stat": "Industry", "value": 12 }, { "stat": "Trade", "value": 9 } - ] + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 23, "max": 95 }, + "strength": 75 }, { "name": "smelter_piracy", @@ -831,7 +1001,11 @@ { "stat": "Industry", "value": -11 }, { "stat": "Trade", "value": -7 }, { "stat": "Crime", "value": 10 } - ] + ], + "duration": { "Duration": 4 }, + "application": "WhenPresent", + "effect_bounds": { "min": 23, "max": 95 }, + "strength": 77 }, { "name": "frontline_betrayal", @@ -839,7 +1013,11 @@ "stats": [ { "stat": "Strength", "value": -6 }, { "stat": "Threat", "value": 11 } - ] + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 22, "max": 95 }, + "strength": 74 }, { "name": "naval_battle_victory", @@ -847,7 +1025,11 @@ "stats": [ { "stat": "Strength", "value": 12 }, { "stat": "Threat", "value": -9 } - ] + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 23, "max": 95 }, + "strength": 75 }, { "name": "disease_in_soldiers", @@ -856,7 +1038,11 @@ { "stat": "Army", "value": -14 }, { "stat": "Health", "value": -10 }, { "stat": "Strength", "value": -5 } - ] + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 23, "max": 95 }, + "strength": 77 }, { "name": "recruitment_panic", @@ -865,7 +1051,11 @@ { "stat": "Army", "value": 8 }, { "stat": "Strength", "value": -9 }, { "stat": "Threat", "value": 3 } - ] + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 23, "max": 95 }, + "strength": 75 }, { "name": "training_expedition", @@ -874,7 +1064,11 @@ { "stat": "Strength", "value": 11 }, { "stat": "Army", "value": -6 }, { "stat": "Threat", "value": -5 } - ] + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 23, "max": 95 }, + "strength": 75 }, { "name": "spy_operation_success", @@ -883,7 +1077,11 @@ { "stat": "Threat", "value": -10 }, { "stat": "Influence", "value": 3 }, { "stat": "Strength", "value": 4 } - ] + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 23, "max": 95 }, + "strength": 75 }, { "name": "war_taxes_harsh", @@ -895,7 +1093,11 @@ { "stat": "Industry", "value": -3 }, { "stat": "Science", "value": -3 }, { "stat": "Trade", "value": -3 } - ] + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 23, "max": 95 }, + "strength": 75 }, { "name": "battlefield_innovation", @@ -903,7 +1105,11 @@ "stats": [ { "stat": "Strength", "value": 13 }, { "stat": "Threat", "value": -8 } - ] + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 23, "max": 95 }, + "strength": 75 }, { "name": "trade_agreement", @@ -915,7 +1121,11 @@ { "stat": "Science", "value": 3 }, { "stat": "Trade", "value": 3 }, { "stat": "Population", "value": 3 } - ] + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 23, "max": 95 }, + "strength": 76 }, { "name": "peace_council", @@ -924,7 +1134,11 @@ { "stat": "Trade", "value": 10 }, { "stat": "Culture", "value": 7 }, { "stat": "Happiness", "value": 5 } - ] + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 22, "max": 95 }, + "strength": 76 }, { "name": "bounty_hunt_success", @@ -933,7 +1147,11 @@ { "stat": "Crime", "value": -12 }, { "stat": "Threat", "value": -8 }, { "stat": "Happiness", "value": 4 } - ] + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 23, "max": 95 }, + "strength": 75 }, { "name": "technological_breakthrough", @@ -943,7 +1161,11 @@ { "stat": "Industry", "value": 6 }, { "stat": "Food", "value": 3 }, { "stat": "Trade", "value": 3 } - ] + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 21, "max": 95 }, + "strength": 78 }, { "name": "festival_of_luxury", @@ -955,7 +1177,11 @@ { "stat": "Culture", "value": 3 }, { "stat": "Influence", "value": 3 }, { "stat": "Happiness", "value": 6 } - ] + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 22, "max": 95 }, + "strength": 77 }, { "name": "military_training_expedition", @@ -964,7 +1190,11 @@ { "stat": "Strength", "value": 12 }, { "stat": "Army", "value": 3 }, { "stat": "Threat", "value": -5 } - ] + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 21, "max": 95 }, + "strength": 77 }, { "name": "health_initiative", @@ -973,7 +1203,11 @@ { "stat": "Health", "value": 16 }, { "stat": "Population", "value": 4 }, { "stat": "Happiness", "value": 5 } - ] + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 23, "max": 95 }, + "strength": 79 }, { "name": "artisan_summit", @@ -983,7 +1217,11 @@ { "stat": "Science", "value": 8 }, { "stat": "Trade", "value": 3 }, { "stat": "Population", "value": 2 } - ] + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 21, "max": 95 }, + "strength": 77 }, { "name": "infrastructure_repair", @@ -996,7 +1234,11 @@ { "stat": "Trade", "value": 7 }, { "stat": "Food", "value": 5 }, { "stat": "Trade", "value": 4 } - ] + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 24, "max": 95 }, + "strength": 79 }, { "name": "cultural_exposition", @@ -1006,7 +1248,11 @@ { "stat": "Tourism", "value": 10 }, { "stat": "Happiness", "value": 4 }, { "stat": "Influence", "value": 4 } - ] + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 23, "max": 95 }, + "strength": 78 }, { "name": "great_earthquake", @@ -1015,16 +1261,24 @@ { "stat": "Health", "value": -19 }, { "stat": "Population", "value": -18 }, { "stat": "Happiness", "value": -15 } - ] + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 26, "max": 95 }, + "strength": 81 }, { "name": "plague_of_scorpion", - "description": "A deadly disease spreads through the populace, turning citizens into venom-infused monsters.", + "description": "A deadly disease spreads through the populace, turning citizens into venom‑infused monsters.", "stats": [ { "stat": "Health", "value": -14 }, { "stat": "Population", "value": -10 }, { "stat": "Crime", "value": 8 } - ] + ], + "duration": { "Duration": 14 }, + "application": "WhenPresent", + "effect_bounds": { "min": 23, "max": 95 }, + "strength": 79 }, { "name": "oil_fire_in_barnyard", @@ -1033,7 +1287,11 @@ { "stat": "Industry", "value": -9 }, { "stat": "Happiness", "value": -4 }, { "stat": "Threat", "value": 10 } - ] + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 22, "max": 95 }, + "strength": 73 }, { "name": "fire_of_sacred_temple", @@ -1042,7 +1300,11 @@ { "stat": "Culture", "value": -15 }, { "stat": "Threat", "value": 12 }, { "stat": "Happiness", "value": -6 } - ] + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 24, "max": 95 }, + "strength": 77 }, { "name": "cursed_great_flood", @@ -1052,7 +1314,11 @@ { "stat": "Industry", "value": -6 }, { "stat": "Trade", "value": -8 }, { "stat": "Threat", "value": 13 } - ] + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 25, "max": 95 }, + "strength": 81 }, { "name": "massive_barricade_breach", @@ -1061,7 +1327,11 @@ { "stat": "Fortification", "value": -19 }, { "stat": "Threat", "value": 19 }, { "stat": "Happiness", "value": -12 } - ] + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 24, "max": 95 }, + "strength": 81 }, { "name": "invasion_of_the_undead", @@ -1070,7 +1340,11 @@ { "stat": "Threat", "value": 14 }, { "stat": "Crime", "value": -10 }, { "stat": "Population", "value": -12 } - ] + ], + "duration": { "Duration": 5 }, + "application": "WhenPresent", + "effect_bounds": { "min": 23, "max": 95 }, + "strength": 78 } ] } diff --git a/lib_efo/src/entity.rs b/lib_efo/src/entity.rs index d841042..e9baa81 100644 --- a/lib_efo/src/entity.rs +++ b/lib_efo/src/entity.rs @@ -1,19 +1,114 @@ -//! All the structs and logic surrounding entities +//! # 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 serde::{Deserialize, Serialize}; use crate::stats::{EntityType, MetaStats, OverallStats}; -/// Fundamentaly everything is an entity, this can be error prone but the reduction of code duplication makes it worth it right now -/// Traits and thin structs could solve this but this will be added later and will be greatly simplified by the existence of the sub structs holding all the logic -#[derive(Serialize, Deserialize)] +/// 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)] pub struct Entity { - /// The stats of the entity, holding all the logic + /// 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, - /// Meta information + + /// 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. + temp_stats: 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, - /// Enum listing all entity types, this is bound to disapear in favor Typed Etities lateer + + /// 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. 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, +} + +/// 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)] +#[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)] +pub enum EffectApplication { + /// Repeatedly applied every turn while the entity is present. + /// Use with caution, as this can produce catastrophic results + /// (e.g., an ever‑erupting terrain). + Recurring, + + /// Modifies the attached entity’s stats only while present. + /// Removed when the entity is removed. Common for leaders, + /// temporary events, or terrain. + WhenPresent, + + /// Permanently modifies stats; the change persists after + /// the event ends. + PermanentEffectToApply, + + /// Indicates that a permanent effect has already been applied. + /// Useful for bookkeeping when a long‑lasting event applies + /// its effect only once. + PermanentEffectApplied, +} + +/// Represents how long an entity remains active in the world. +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)] +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. + Done, } diff --git a/lib_efo/src/naming.rs b/lib_efo/src/naming.rs index 9687453..e382255 100644 --- a/lib_efo/src/naming.rs +++ b/lib_efo/src/naming.rs @@ -7,6 +7,9 @@ use std::fs; use std::io; use std::path::{Path, PathBuf}; +use crate::entity::EffectApplication; +use crate::entity::EffectBounds; +use crate::entity::EntityDuration; use crate::stats::StatPair; /// The structure that holds everything we need for name generation. @@ -39,8 +42,18 @@ pub struct EventDescription { /// A short description of the event pub description: String, - /// The stats affected by the event, and how much (-20 to +20) (100 being the maximum of a stat, event a change of -10 is meaningful) + /// The stats affected by the event, and how much (-20 to +20) + /// (100 being the maximum of a stat, event a change of -10 is meaningful) pub stats: Vec, + + /// The nature of the event duration + pub duration: EntityDuration, + + /// How the event will be (re)applied + pub application: EffectApplication, + + /// The maximum bounds of the event + pub effect_bounds: EffectBounds, } impl NamingData { diff --git a/lib_efo/src/stats.rs b/lib_efo/src/stats.rs index 60a9f6b..7b01785 100644 --- a/lib_efo/src/stats.rs +++ b/lib_efo/src/stats.rs @@ -362,7 +362,7 @@ pub enum ListStats { /// The list of all types of entities #[allow(missing_docs)] -#[derive(Serialize, Deserialize)] +#[derive(Serialize, Deserialize, Debug, Clone)] pub enum EntityType { Character, Player, -- 2.45.1 From 6865de9e8c1279259fe01b702612698ce19c04c2 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sun, 30 Nov 2025 23:56:33 +0100 Subject: [PATCH 17/22] Starts work on the diplayable trait --- bin_efo/src/main.rs | 17 ++--- lib_efo/src/entity.rs | 13 +++- lib_efo/src/entity/implementations.rs | 104 ++++++++++++++++++++++++++ lib_efo/src/lib.rs | 54 +++++++++++++ lib_efo/src/stats.rs | 3 +- 5 files changed, 175 insertions(+), 16 deletions(-) create mode 100644 lib_efo/src/entity/implementations.rs diff --git a/bin_efo/src/main.rs b/bin_efo/src/main.rs index 8977290..8122c30 100644 --- a/bin_efo/src/main.rs +++ b/bin_efo/src/main.rs @@ -24,7 +24,6 @@ #![deny(clippy::unwrap_used)] use clap::{ArgAction, Parser, Subcommand}; -use lib_efo::naming::NAMING; use crate::commands::init::InitCmd; use crate::{commands::epoch::cli_epoch::EpochCmd, error::AppError}; @@ -75,17 +74,13 @@ enum TopLevelCmd { #[allow(clippy::unwrap_used)] fn main() -> miette::Result<()> { env_logger::init(); - // 1. Generate a character name - let character = NAMING.generate_character_name(); - println!("Character: {}", character); - // 2. Generate a town name - let town = NAMING.generate_town_name(); - println!("Town: {}", town); - - // 3. Pick an event idea - let event = NAMING.generate_long_character_name(); - println!("Event idea: {}", event); + // let e = Entity::default(); + // println!("{e:#?}"); + // println!("{}", e.oneline_display()); + // e.print_short(); + // e.print_full(); + // println!("{}", e.to_pretty_tree()); let cli = Cli::parse(); if let Err(e) = exec_dispatch(cli) { diff --git a/lib_efo/src/entity.rs b/lib_efo/src/entity.rs index e9baa81..21e658b 100644 --- a/lib_efo/src/entity.rs +++ b/lib_efo/src/entity.rs @@ -13,13 +13,16 @@ use serde::{Deserialize, Serialize}; use crate::stats::{EntityType, MetaStats, OverallStats}; +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)] +#[derive(Serialize, Deserialize, Debug, Clone, Default)] pub struct Entity { + /// The name of the entity + name: String, /// Runtime statistics that determine the entity’s behaviour. /// /// These values are updated by the game loop and reflect the @@ -67,14 +70,14 @@ pub struct Entity { /// been calculated to keep stats within a sane range. /// /// `min` and `max` are inclusive. -#[derive(Debug, Serialize, Deserialize, Clone)] +#[derive(Debug, Serialize, Deserialize, Clone, Default)] #[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)] +#[derive(Debug, Serialize, Deserialize, Clone, Default)] pub enum EffectApplication { /// Repeatedly applied every turn while the entity is present. /// Use with caution, as this can produce catastrophic results @@ -88,6 +91,7 @@ pub enum EffectApplication { /// Permanently modifies stats; the change persists after /// the event ends. + #[default] PermanentEffectToApply, /// Indicates that a permanent effect has already been applied. @@ -97,7 +101,7 @@ pub enum EffectApplication { } /// Represents how long an entity remains active in the world. -#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)] +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Default)] pub enum EntityDuration { /// The entity persists until it is explicitly destroyed. Permanent, @@ -110,5 +114,6 @@ pub enum EntityDuration { /// 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, } diff --git a/lib_efo/src/entity/implementations.rs b/lib_efo/src/entity/implementations.rs new file mode 100644 index 0000000..053a500 --- /dev/null +++ b/lib_efo/src/entity/implementations.rs @@ -0,0 +1,104 @@ +//! Implementation of all needed traits for the Entity struct +use cli_table::{Style, WithTitle, print_stdout}; +use colored::*; // [3] – colored‑rs examples + +use crate::Displayable; +use crate::entity::Entity; + +// ---------- Implementation ---------- +impl Displayable for Entity { + // Detailed multi‑line view (used e.g. in logs) + fn print_full(&self) { + println!( + "{:?}\n{}", + self.metadata.position, // Display + format!( + "{} | {} | {} | {:?} | {}", + self.metadata.capital, + self.metadata.governor, + self.metadata.faction, + self.metadata.links, + self.metadata.prestige + ) + .blue() // colour the whole line (you can tweak colours per field) + ); + let meta_ext = format!( + "{:?} | {:?} | {:?} | {:?}", + self.duration, self.effect_nature, self.effect_bounds, self.entity_type + ) + .green(); // another colour + println!("{meta_ext}"); + print_stdout(vec![&self.stats, &self.temp_stats].with_title().bold(true)).expect(""); + } + + // Short, single‑line representation + fn print_short(&self) { + println!( + "{} | {:?} | {:?} | {:?} | {:?} | {:?} | {:?}", + self.name, + self.metadata.position, + self.duration, + self.effect_nature, + self.effect_bounds, + self.entity_type, + self.metadata.prestige + ); + print_stdout(vec![&self.stats].with_title().bold(true)).expect("") + } + + // One‑liner used for auto‑generation of Vec displays + fn oneline_display(&self) -> String { + format!( + "{} | {:?} | {:?} | {:?} | {:?} | {:?} | {:?} | {:?}", + self.name, + self.metadata.position, + self.duration, + self.effect_nature, + self.effect_bounds, + self.entity_type, + self.metadata.capital, + self.metadata.prestige + ) + } +} + +impl Entity { + /// Just show a pretty tree + pub fn to_pretty_tree(&self) -> String { + // Helper that indents a line + let indent = |level: usize, s: &str| -> String { format!("{}{}", " |".repeat(level), s) }; + + let mut out = String::new(); + + out.push_str(&indent(0, "self\n")); + out.push_str(&indent(1, &format!("├─ name: {}\n", self.name))); + out.push_str(&indent(1, "├─ metadata\n")); + out.push_str(&indent( + 2, + &format!("├─ position: {:?}\n", self.metadata.position), + )); + out.push_str(&indent( + 2, + &format!("├─ capital: {:?}\n", self.metadata.capital), + )); + out.push_str(&indent( + 2, + &format!("└─ prestige: {:?}\n", self.metadata.prestige), + )); + out.push_str(&indent(1, &format!("├─ duration: {:?}\n", self.duration))); + out.push_str(&indent( + 1, + &format!("├─ effect_nature: {:?}\n", self.effect_nature), + )); + out.push_str(&indent( + 1, + &format!("├─ effect_bounds: {:?}\n", self.effect_bounds), + )); + out.push_str(&indent( + 1, + &format!("└─ entity_type: {:?}\n", self.entity_type), + )); + + out + } +} diff --git a/lib_efo/src/lib.rs b/lib_efo/src/lib.rs index 69b561e..b1b10ff 100644 --- a/lib_efo/src/lib.rs +++ b/lib_efo/src/lib.rs @@ -55,3 +55,57 @@ where /// List all ids known to this store. fn list_ids(&self) -> IoResult>; } +/// A trait for types that can be displayed in a command‑line tool. +/// +/// Implementors should provide three levels of representation: +/// 1. **Full** – a detailed view suitable for a long‑running command. +/// 2. **Short** – a concise, user‑friendly view that fits on a single line. +/// 3. **Oneline** – a compact, machine‑friendly string that can be embedded +/// inside a `Vec` representation. +/// +/// ## `Vec` support +/// +/// The trait is implemented generically for `Vec` as long as `T: Displayable`. +/// This allows you to call `full_display`, `short_display` or `oneline_display` +/// directly on a vector of displayable items. +pub trait Displayable { + /// Return a fully‑described string representation. + fn print_full(&self); + + /// Return a short, user‑friendly string. + fn print_short(&self); + + /// Return a one‑liner string, suitable for embedding in a collection + /// representation (e.g. a `Vec`). Implementations should avoid + /// new‑lines to keep the output usable in a single line context. + fn oneline_display(&self) -> String; + + /// Print oneline + fn print_oneline(&self) { + println!("{}", self.oneline_display()) + } +} + +/// Implement `Displayable` for vectors of displayable items. +/// +/// The implementation simply delegates to the underlying `T::oneline_display` +/// method and joins the results with a comma. It works for any `T` that +/// already implements `Displayable`. This is a **blanket implementation**, +/// so you do not need to write a manual impl for each concrete type +impl Displayable for Vec { + fn print_full(&self) { + self.iter().for_each(|e| e.print_full()); + } + + fn print_short(&self) { + self.iter().for_each(|e| e.print_short()); + } + + fn oneline_display(&self) -> String { + // No brackets – just a flat, comma‑separated list. + self.iter() + .map(|x| x.oneline_display()) + .collect::>() + .join(",") + } +} diff --git a/lib_efo/src/stats.rs b/lib_efo/src/stats.rs index 7b01785..3f82e7a 100644 --- a/lib_efo/src/stats.rs +++ b/lib_efo/src/stats.rs @@ -362,13 +362,14 @@ pub enum ListStats { /// The list of all types of entities #[allow(missing_docs)] -#[derive(Serialize, Deserialize, Debug, Clone)] +#[derive(Serialize, Deserialize, Debug, Clone, Default)] pub enum EntityType { Character, Player, Town, Monster, Blocker, + #[default] Event, } -- 2.45.1 From 5c737635a64c1d455d9efdbbf8296829493b2578 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Mon, 1 Dec 2025 19:19:47 +0100 Subject: [PATCH 18/22] Work on the display --- bin_efo/src/main.rs | 14 ++++++++------ lib_efo/src/entity/implementations.rs | 21 +++++++-------------- lib_efo/src/stats.rs | 26 ++++++++++++++++++++++++++ 3 files changed, 41 insertions(+), 20 deletions(-) diff --git a/bin_efo/src/main.rs b/bin_efo/src/main.rs index 8122c30..f6087b1 100644 --- a/bin_efo/src/main.rs +++ b/bin_efo/src/main.rs @@ -24,6 +24,8 @@ #![deny(clippy::unwrap_used)] use clap::{ArgAction, Parser, Subcommand}; +use lib_efo::Displayable; +use lib_efo::entity::Entity; use crate::commands::init::InitCmd; use crate::{commands::epoch::cli_epoch::EpochCmd, error::AppError}; @@ -75,12 +77,12 @@ enum TopLevelCmd { fn main() -> miette::Result<()> { env_logger::init(); - // let e = Entity::default(); - // println!("{e:#?}"); - // println!("{}", e.oneline_display()); - // e.print_short(); - // e.print_full(); - // println!("{}", e.to_pretty_tree()); + let e = Entity::default(); + println!("{e:#?}"); + println!("{}", e.oneline_display()); + e.print_short(); + e.print_full(); + println!("{}", e.to_pretty_tree()); let cli = Cli::parse(); if let Err(e) = exec_dispatch(cli) { diff --git a/lib_efo/src/entity/implementations.rs b/lib_efo/src/entity/implementations.rs index 053a500..a1b9119 100644 --- a/lib_efo/src/entity/implementations.rs +++ b/lib_efo/src/entity/implementations.rs @@ -33,23 +33,14 @@ impl Displayable for Entity { // Short, single‑line representation fn print_short(&self) { - println!( - "{} | {:?} | {:?} | {:?} | {:?} | {:?} | {:?}", - self.name, - self.metadata.position, - self.duration, - self.effect_nature, - self.effect_bounds, - self.entity_type, - self.metadata.prestige - ); + println!("{}", self.to_pretty_tree()); print_stdout(vec![&self.stats].with_title().bold(true)).expect("") } // One‑liner used for auto‑generation of Vec displays fn oneline_display(&self) -> String { format!( - "{} | {:?} | {:?} | {:?} | {:?} | {:?} | {:?} | {:?}", + "> {} | {:?} | {:?} | {:?} | {:?} | {:?} | {:?} | {:?}", self.name, self.metadata.position, self.duration, @@ -66,12 +57,14 @@ impl Entity { /// Just show a pretty tree pub fn to_pretty_tree(&self) -> String { // Helper that indents a line - let indent = |level: usize, s: &str| -> String { format!("{}{}", " |".repeat(level), s) }; + let indent = |level: usize, s: &str| -> String { + format!(" {}{}", "│ ".repeat(level.saturating_sub(1)), s) + }; let mut out = String::new(); - out.push_str(&indent(0, "self\n")); - out.push_str(&indent(1, &format!("├─ name: {}\n", self.name))); + // out.push_str(&indent(0, "self\n")); + out.push_str(&indent(0, &format!("name: {}\n", self.name))); out.push_str(&indent(1, "├─ metadata\n")); out.push_str(&indent( 2, diff --git a/lib_efo/src/stats.rs b/lib_efo/src/stats.rs index 3f82e7a..cf40bfc 100644 --- a/lib_efo/src/stats.rs +++ b/lib_efo/src/stats.rs @@ -12,6 +12,7 @@ #![allow(dead_code)] #![deny(clippy::missing_docs_in_private_items)] +use cli_table::Color; use cli_table::Table; use colored::Colorize; use derive_more::Display; @@ -35,12 +36,14 @@ pub struct OverallStats { /// **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", color = "Color::Blue", bold)] 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")] pub population: GenericStat, /// Per-turn change in population. @@ -48,6 +51,7 @@ pub struct OverallStats { /// **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")] pub growth_rate: GenericStat, /// Crime level (0-1 scale). @@ -55,6 +59,7 @@ pub struct OverallStats { /// **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")] pub crime: GenericStat, /// Base happiness of the population (0-1 scale). @@ -62,6 +67,7 @@ pub struct OverallStats { /// **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")] pub happiness: GenericStat, // ──────────────────────── Economy ──────────────────────── @@ -70,6 +76,7 @@ pub struct OverallStats { /// **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", color = "Color::Blue", bold)] pub economy: GenericStat, /// Food produced by the entity. @@ -77,6 +84,7 @@ pub struct OverallStats { /// **Purpose** - Amount of consumable resources available. /// **Effect** - Keeps the population alive and productive. /// **Source** - `food = farm_yield + tech_level`. + #[table(title = "FOD")] pub food: GenericStat, /// Strength of the industry. @@ -84,6 +92,7 @@ pub struct OverallStats { /// **Purpose** - Industrial production capacity. /// **Effect** - Drives tax revenue and unit production. /// **Source** - `industry = factory_output + tech_level`. + #[table(title = "IND")] pub industry: GenericStat, /// Scientific output. @@ -91,6 +100,7 @@ pub struct OverallStats { /// **Purpose** - Rate of research progress. /// **Effect** - Determines how quickly new technologies are unlocked. /// **Source** - `science = research_center_output + tech_level`. + #[table(title = "SCI")] pub science: GenericStat, /// Trade volume / exports. @@ -98,6 +108,7 @@ pub struct OverallStats { /// **Purpose** - Measure of export activity. /// **Effect** - Influences influence and wealth. /// **Source** - `trade = trade_network_output`. + #[table(title = "TRD")] pub trade: GenericStat, // // ──────────────────────── Social ──────────────────────── // /// Overall social prestige. @@ -105,6 +116,7 @@ pub struct OverallStats { // /// **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)] // pub social: GenericStat, // /// Cultural output from arts, theatres, museums, etc. @@ -112,6 +124,7 @@ pub struct OverallStats { // /// **Purpose** - Measure of cultural production. // /// **Effect** - Drives tourism, prestige, and happiness. // /// **Source** - `culture = Σ(cultural_building_output)`. + // #[table(title = "CLU")] // pub culture: GenericStat, // /// Level of education/literacy. @@ -119,6 +132,7 @@ pub struct OverallStats { // /// **Purpose** - Measure of the citizenry's knowledge. // /// **Effect** - Improves productivity, science output, and reduces unrest. // /// **Source** - `education = Σ(education_building_output)`. + // #[table(title = "EDU")] // pub education: GenericStat, // /// Tourism revenue. @@ -126,6 +140,7 @@ pub struct OverallStats { // /// **Purpose** - Income generated by visitors. // /// **Effect** - Provides an additional income stream. // /// **Source** - `tourism = number_of_tourists x price_per_tourist`. + // #[table(title = "TOR")] // pub tourism: GenericStat, // /// Cultural influence over the region. @@ -133,6 +148,7 @@ pub struct OverallStats { // /// **Purpose** - Measure of soft power. // /// **Effect** - Grants diplomatic bonuses and increases sway in the empire. // /// **Source** - `influence = culture x population`. + // #[table(title = "INF")] // pub influence: GenericStat, // ──────────────────────── Military ──────────────────────── @@ -141,6 +157,7 @@ pub struct OverallStats { /// **Purpose** - Composite measure of combat capability. /// **Effect** - Determines defensive and offensive strength. /// **Source** - Sum of `army`, `strength`, `fortification`, etc. + #[table(title = "MIL", color = "Color::Blue", bold)] pub military: GenericStat, /// Number of battle-ready units. @@ -148,6 +165,7 @@ pub struct OverallStats { /// **Purpose** - Size of the active army. /// **Effect** - Directly dictates defense and attack potential. /// **Source** - Sum of all trained and equipped units. + #[table(title = "ARM")] pub army: GenericStat, /// Composite strength of the army. @@ -155,6 +173,7 @@ pub struct OverallStats { /// **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")] pub strength: GenericStat, /// Defensive bonus from fortifications. @@ -162,6 +181,7 @@ pub struct OverallStats { /// **Purpose** - Wall and tower defenses. /// **Effect** - Adds a multiplier to overall defense. /// **Source** - `fortification = Σ(fortification_building_bonus)`. + #[table(title = "FRT")] pub fortification: GenericStat, /// Threat level facing the entity. @@ -169,6 +189,7 @@ pub struct OverallStats { /// **Purpose** - Likelihood of being attacked. /// **Effect** - Triggers early warning alerts and strategic decisions. /// **Source** - `threat = (enemy_proximity + enemy_strength) / defense`. + #[table(title = "THR")] pub threat: GenericStat, // ──────────────────────── Infrastructure ──────────────────────── @@ -177,6 +198,7 @@ pub struct OverallStats { /// **Purpose** - Overall built-environment capacity. /// **Effect** - Supports population size and efficiency. /// **Source** - Sum of all infrastructure components. + #[table(title = "IFR", color = "Color::Blue", bold)] pub infrastructure: GenericStat, /// Bureaucratic power. @@ -184,6 +206,7 @@ pub struct OverallStats { /// **Purpose** - Efficiency of the city's administrative machinery. /// **Effect** - Improves resource management and policy implementation. /// **Source** - `bureaucracy = Σ(bureaucracy_building_output)`. + #[table(title = "BUR")] pub bureaucracy: GenericStat, /// Transportation level. @@ -191,6 +214,7 @@ pub struct OverallStats { /// **Purpose** - Availability and quality of transport infrastructure. /// **Effect** - Impacts logistics, mobility, and trade. /// **Source** - `transportation = Σ(transport_building_output)`. + #[table(title = "TRP")] pub transportation: GenericStat, /// Sprawl / urban density. @@ -198,6 +222,7 @@ pub struct OverallStats { /// **Purpose** - Measure of city sprawl and clutter. /// **Effect** - Affects health, happiness, and infrastructure efficiency. /// **Source** - `sprawl = Σ(sprawl_factor)`. + #[table(title = "SPR")] pub sprawl: GenericStat, /// Health infrastructure quality. @@ -205,6 +230,7 @@ pub struct OverallStats { /// **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")] pub health: GenericStat, } -- 2.45.1 From 7ec26229590fb13796f906be15d4ab5a8b70790b Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Tue, 2 Dec 2025 16:45:34 +0100 Subject: [PATCH 19/22] Some work on the display --- bin_efo/src/main.rs | 14 +- lib_efo/src/entity/implementations.rs | 59 ++++- lib_efo/src/stats.rs | 44 +++- lib_efo/src/stats/implementations.rs | 265 +++++----------------- lib_efo/src/stats/implementations/test.rs | 209 +++++++++++++++++ 5 files changed, 357 insertions(+), 234 deletions(-) create mode 100644 lib_efo/src/stats/implementations/test.rs diff --git a/bin_efo/src/main.rs b/bin_efo/src/main.rs index f6087b1..e5e66f1 100644 --- a/bin_efo/src/main.rs +++ b/bin_efo/src/main.rs @@ -78,11 +78,17 @@ fn main() -> miette::Result<()> { env_logger::init(); let e = Entity::default(); - println!("{e:#?}"); + // println!("{e:#?}"); println!("{}", e.oneline_display()); - e.print_short(); - e.print_full(); - println!("{}", e.to_pretty_tree()); + println!("{}", e.oneline_display()); + println!("{}", e.oneline_display()); + println!("{}", e.oneline_display()); + println!("{}", e.oneline_display()); + println!("{}", e.oneline_display()); + println!("{}", e.oneline_display()); + // e.print_short(); + // e.print_full(); + // println!("{}", e.to_pretty_tree()); let cli = Cli::parse(); if let Err(e) = exec_dispatch(cli) { diff --git a/lib_efo/src/entity/implementations.rs b/lib_efo/src/entity/implementations.rs index a1b9119..4362a70 100644 --- a/lib_efo/src/entity/implementations.rs +++ b/lib_efo/src/entity/implementations.rs @@ -4,6 +4,7 @@ use colored::*; // [3] – colored‑rs examples use crate::Displayable; use crate::entity::Entity; +use crate::stats::Symbols; // ---------- Implementation ---------- impl Displayable for Entity { @@ -13,7 +14,7 @@ impl Displayable for Entity { "{:?}\n{}", self.metadata.position, // Display format!( - "{} | {} | {} | {:?} | {}", + "{:?} | {:?} | {} | {:?} | {}", self.metadata.capital, self.metadata.governor, self.metadata.faction, @@ -37,19 +38,53 @@ impl Displayable for Entity { print_stdout(vec![&self.stats].with_title().bold(true)).expect("") } - // One‑liner used for auto‑generation of Vec displays + /// One‑liner used for auto‑generation of Vec displays fn oneline_display(&self) -> String { - format!( - "> {} | {:?} | {:?} | {:?} | {:?} | {:?} | {:?} | {:?}", + let capital = self + .metadata + .capital + .as_ref() + .map(|c| format!(" | 💰 {}", c)) + .unwrap_or_default(); + + let governor = self + .metadata + .governor + .as_ref() + .map(|g| format!(" | 👑 {}", g)) + .unwrap_or_default(); + + let prestige = if self.metadata.prestige > 0 { + format!(" | 📈 {}", self.metadata.prestige) + } else { + String::new() + }; + + // ---- build the two lines ---- + let line1 = format!( + "├─ {} {} ──────> {} {}", self.name, - self.metadata.position, - self.duration, - self.effect_nature, - self.effect_bounds, - self.entity_type, - self.metadata.capital, - self.metadata.prestige - ) + self.entity_type.to_symbol(), + self.metadata.position.to_symbol(), + self.duration.to_symbol() + ); + + let line2 = format!( + "│ └─ Faction: {}{}{}{} │ Effect: {} {}, Stats: 👥 {} | 💰 {} | 🛡️ {} | 🏗️ {}{}", + self.metadata.faction, + capital, + governor, + prestige, + self.effect_nature.to_symbol(), + self.effect_bounds.to_symbol(), + self.stats.demographics, + self.stats.economy, + self.stats.military, + self.stats.infrastructure, + " " + ); + + format!("{}\n{}", line1, line2) } } diff --git a/lib_efo/src/stats.rs b/lib_efo/src/stats.rs index cf40bfc..124c159 100644 --- a/lib_efo/src/stats.rs +++ b/lib_efo/src/stats.rs @@ -12,13 +12,12 @@ #![allow(dead_code)] #![deny(clippy::missing_docs_in_private_items)] +use crate::thin_newtype; use cli_table::Color; use cli_table::Table; use colored::Colorize; use derive_more::Display; use serde::{Deserialize, Serialize}; - -use crate::thin_newtype; mod implementations; /// Aggregated statistics for a single entity. @@ -250,7 +249,7 @@ pub struct MetaStats { pub position: Position, /// Identifier for the capital - pub capital: TownId, + pub capital: Option, // /// List of nearby resource nodes (mines, forests, farms, etc.). // /// @@ -275,7 +274,7 @@ pub struct MetaStats { /// **Effect** - Adds personal bonuses and may modify policies /// or diplomatic stance. /// **Source** - `governor = selected_leader_uuid`. - pub governor: CharacterId, + pub governor: Option, // /// The entity's classification (capital, trade hub, frontier post, etc.). // /// @@ -355,7 +354,20 @@ pub struct SummaryStats { infrastructure: GenericStat, } +impl From 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 { @@ -399,6 +411,22 @@ pub enum EntityType { 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 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); thin_newtype!(TownId, usize); @@ -407,20 +435,20 @@ thin_newtype!(FactionId, usize); // --- TRAITS --------------------------------------------------------------- /// A stat is a *game value* that can be converted to two different -/// normalised ranges - a 50-point range for “gaming” logic and a +/// 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_50(&self) -> isize { - (self.get_value().clamp(0, 70) - 10).min(50) + 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_50() / 5 + self.to_100() / 10 } /// As a colored delta (when the stat is used as a delta) diff --git a/lib_efo/src/stats/implementations.rs b/lib_efo/src/stats/implementations.rs index a9b0d0e..d0e022c 100644 --- a/lib_efo/src/stats/implementations.rs +++ b/lib_efo/src/stats/implementations.rs @@ -2,13 +2,19 @@ use std::str::FromStr; +use crate::entity::EffectApplication; +use crate::entity::EffectBounds; +use crate::entity::EntityDuration; use crate::error::EpochError; use crate::stats; +use crate::stats::EntityType; use crate::stats::GameStat; use crate::stats::GenericStat; use crate::stats::ListStats; use crate::stats::OverallStats; +use crate::stats::Position; use crate::stats::StatPair; +use crate::stats::Symbols; /// Creates a thin, deref-able wrapper around an inner type. #[macro_export] @@ -233,215 +239,54 @@ impl FromStr for StatPair { } } -#[cfg(test)] -pub(crate) mod test { - #![allow(clippy::unwrap_used)] - use super::*; - use crate::stats::GameStat; - use crate::stats::GenericStat; - use std::str::FromStr; - - struct Person { - name: GenericStat, - age: GenericStat, - email: GenericStat, - } - - /// Helper that asserts that a string parses to the expected ListStats variant. - fn assert_stat_ok(input: &str, expected: ListStats) { - let parsed = ListStats::from_str(input).expect("should parse"); - assert_eq!(parsed, expected, "input `{}` parsed incorrectly", input); - } - - field_accessor!(Person { name, age, email }); - - #[test] - fn test_field_accessors() { - let person = Person { - name: GenericStat(10), - age: GenericStat(20), - email: GenericStat(70), - }; - let name = person.get_field("name").unwrap(); - let email = person.get_field("email").unwrap(); - let age = person.get_field("age").unwrap(); - assert_eq!(name.to_50(), 0); - assert_eq!(age.to_50(), 10); - assert_eq!(email.to_50(), 50); - } - - #[test] - fn test_clap_serialisation() {} - /// Helper that asserts that a stat pair string parses to the expected `StatPair`. - fn assert_pair_ok(input: &str, expected_stat: ListStats, expected_val: isize) { - let pair = StatPair::from_str(input).expect("should parse"); - assert_eq!(pair.stat, expected_stat, "stat mismatch"); - assert_eq!(pair.value.0, expected_val, "value mismatch"); - } - #[test] - fn test_stat_pair_parsing() { - // Colon syntax - assert_pair_ok("cri:10", ListStats::Crime, 10); - assert_pair_ok("POP:-5", ListStats::Population, -5); - assert_pair_ok("growth:0", ListStats::Growthrate, 0); - - // Space syntax (clap concatenates two separate args into one string) - assert_pair_ok("cri 10", ListStats::Crime, 10); - assert_pair_ok("Pop -5", ListStats::Population, -5); - assert_pair_ok("grow 0", ListStats::Growthrate, 0); - } - #[test] - fn test_list_stats_all_aliases() { - let stats = OverallStats::default(); - // Demographics - assert_stat_ok("dem", ListStats::Demographics); - assert_stat_ok("Demog", ListStats::Demographics); - assert_stat_ok("DEMOGRAPHICS", ListStats::Demographics); - assert_stat_ok("Demo", ListStats::Demographics); - stats.get_field(ListStats::Demographics.into()); - // Population - assert_stat_ok("pop", ListStats::Population); - assert_stat_ok("Popul", ListStats::Population); - assert_stat_ok("POPULATIONS", ListStats::Population); - stats.get_field(ListStats::Population.into()); - - // Growthrate - assert_stat_ok("grow", ListStats::Growthrate); - assert_stat_ok("GRW", ListStats::Growthrate); - assert_stat_ok("Growth", ListStats::Growthrate); - stats.get_field(ListStats::Growthrate.into()); - - // Crime - assert_stat_ok("cri", ListStats::Crime); - assert_stat_ok("CRIM", ListStats::Crime); - assert_stat_ok("Crimes", ListStats::Crime); - stats.get_field(ListStats::Crime.into()); - - // Happiness - assert_stat_ok("hapn", ListStats::Happiness); - assert_stat_ok("HAPPINES", ListStats::Happiness); - assert_stat_ok("hap", ListStats::Happiness); - stats.get_field(ListStats::Happiness.into()); - - // Economy - assert_stat_ok("eco", ListStats::Economy); - assert_stat_ok("Economy", ListStats::Economy); - assert_stat_ok("econ", ListStats::Economy); - stats.get_field(ListStats::Economy.into()); - - // Food - assert_stat_ok("food", ListStats::Food); - assert_stat_ok("fo", ListStats::Food); - assert_stat_ok("agr", ListStats::Food); - assert_stat_ok("agri", ListStats::Food); - stats.get_field(ListStats::Food.into()); - - // Industry - assert_stat_ok("industry", ListStats::Industry); - assert_stat_ok("Indus", ListStats::Industry); - assert_stat_ok("ind", ListStats::Industry); - stats.get_field(ListStats::Industry.into()); - - // Science - assert_stat_ok("science", ListStats::Science); - assert_stat_ok("sci", ListStats::Science); - assert_stat_ok("sc", ListStats::Science); - stats.get_field(ListStats::Science.into()); - - // Trade - assert_stat_ok("trade", ListStats::Trade); - assert_stat_ok("trd", ListStats::Trade); - assert_stat_ok("tr", ListStats::Trade); - stats.get_field(ListStats::Trade.into()); - - // Social - assert_stat_ok("social", ListStats::Social); - assert_stat_ok("soc", ListStats::Social); - assert_stat_ok("sl", ListStats::Social); - stats.get_field(ListStats::Social.into()); - - // Culture - assert_stat_ok("culture", ListStats::Culture); - assert_stat_ok("cul", ListStats::Culture); - assert_stat_ok("cl", ListStats::Culture); - stats.get_field(ListStats::Culture.into()); - - // Education - assert_stat_ok("education", ListStats::Education); - assert_stat_ok("edu", ListStats::Education); - assert_stat_ok("ed", ListStats::Education); - stats.get_field(ListStats::Education.into()); - - // Tourism - assert_stat_ok("tourism", ListStats::Tourism); - assert_stat_ok("tour", ListStats::Tourism); - assert_stat_ok("tm", ListStats::Tourism); - stats.get_field(ListStats::Tourism.into()); - - // Influence - assert_stat_ok("influence", ListStats::Influence); - assert_stat_ok("infl", ListStats::Influence); - assert_stat_ok("influ", ListStats::Influence); - stats.get_field(ListStats::Influence.into()); - - // Military - assert_stat_ok("military", ListStats::Military); - assert_stat_ok("mil", ListStats::Military); - assert_stat_ok("mt", ListStats::Military); - stats.get_field(ListStats::Military.into()); - - // Army - assert_stat_ok("army", ListStats::Army); - assert_stat_ok("arm", ListStats::Army); - assert_stat_ok("ar", ListStats::Army); - stats.get_field(ListStats::Army.into()); - - // Strength - assert_stat_ok("strength", ListStats::Strength); - assert_stat_ok("str", ListStats::Strength); - assert_stat_ok("st", ListStats::Strength); - stats.get_field(ListStats::Strength.into()); - - // Fortification - assert_stat_ok("fortification", ListStats::Fortification); - assert_stat_ok("fort", ListStats::Fortification); - assert_stat_ok("ft", ListStats::Fortification); - stats.get_field(ListStats::Fortification.into()); - - // Threat - assert_stat_ok("threat", ListStats::Threat); - assert_stat_ok("thr", ListStats::Threat); - assert_stat_ok("th", ListStats::Threat); - stats.get_field(ListStats::Threat.into()); - - // Infrastructure - assert_stat_ok("infrastructure", ListStats::Infrastructure); - assert_stat_ok("infra", ListStats::Infrastructure); - assert_stat_ok("infr", ListStats::Infrastructure); - stats.get_field(ListStats::Infrastructure.into()); - - // Bureaucracy - assert_stat_ok("bureaucracy", ListStats::Bureaucracy); - assert_stat_ok("bureau", ListStats::Bureaucracy); - assert_stat_ok("bur", ListStats::Bureaucracy); - stats.get_field(ListStats::Bureaucracy.into()); - - // Transportation - assert_stat_ok("transportation", ListStats::Transportation); - assert_stat_ok("trans", ListStats::Transportation); - assert_stat_ok("trns", ListStats::Transportation); - stats.get_field(ListStats::Transportation.into()); - - // Sprawl - assert_stat_ok("sprawl", ListStats::Sprawl); - assert_stat_ok("spr", ListStats::Sprawl); - assert_stat_ok("spra", ListStats::Sprawl); - stats.get_field(ListStats::Sprawl.into()); - - // Health - assert_stat_ok("health", ListStats::Health); - assert_stat_ok("hlth", ListStats::Health); - assert_stat_ok("hlt", ListStats::Health); - stats.get_field(ListStats::Health.into()); +impl Symbols for EntityType { + fn to_symbol(&self) -> String { + match self { + EntityType::Character => "[C]".to_string(), + EntityType::Player => "[P]".to_string(), + EntityType::Town => "[T]".to_string(), + EntityType::Monster => "[M]".to_string(), + EntityType::Blocker => "[B]".to_string(), + EntityType::Event => "[E]".to_string(), + } } } + +impl Symbols for EffectApplication { + fn to_symbol(&self) -> String { + match self { + EffectApplication::Recurring => "⟳".to_string(), + EffectApplication::WhenPresent => "⥯".to_string(), + EffectApplication::PermanentEffectToApply => "☈".to_string(), + EffectApplication::PermanentEffectApplied => "✓".to_string(), + } + } +} + +impl Symbols for Position { + fn to_symbol(&self) -> String { + format!("⚓({},{})", self.0, self.1) + } + fn to_shortest(&self) -> String { + format!("{},{}", self.0, self.1) + } +} + +impl Symbols for EntityDuration { + fn to_symbol(&self) -> String { + match self { + EntityDuration::Permanent => "∞".to_string(), + EntityDuration::Duration(t) => format!("⧗{}", t), + EntityDuration::Done => "✔".to_string(), + } + } +} + +impl Symbols for EffectBounds { + fn to_symbol(&self) -> String { + format!("({}⭾{})", self.min, self.max) + } +} + +#[cfg(test)] +pub(crate) mod test; diff --git a/lib_efo/src/stats/implementations/test.rs b/lib_efo/src/stats/implementations/test.rs new file mode 100644 index 0000000..abc882e --- /dev/null +++ b/lib_efo/src/stats/implementations/test.rs @@ -0,0 +1,209 @@ +#![allow(clippy::unwrap_used)] +use super::*; +use crate::stats::GameStat; +use crate::stats::GenericStat; +use std::str::FromStr; + +struct Person { + name: GenericStat, + age: GenericStat, + email: GenericStat, +} + +/// Helper that asserts that a string parses to the expected ListStats variant. +fn assert_stat_ok(input: &str, expected: ListStats) { + let parsed = ListStats::from_str(input).expect("should parse"); + assert_eq!(parsed, expected, "input `{}` parsed incorrectly", input); +} + +field_accessor!(Person { name, age, email }); + +#[test] +fn test_field_accessors() { + let person = Person { + name: GenericStat(10), + age: GenericStat(20), + email: GenericStat(120), + }; + let name = person.get_field("name").unwrap(); + let email = person.get_field("email").unwrap(); + let age = person.get_field("age").unwrap(); + assert_eq!(name.to_100(), 0); + assert_eq!(age.to_100(), 10); + assert_eq!(email.to_100(), 100); +} + +#[test] +fn test_clap_serialisation() {} +/// Helper that asserts that a stat pair string parses to the expected `StatPair`. +fn assert_pair_ok(input: &str, expected_stat: ListStats, expected_val: isize) { + let pair = StatPair::from_str(input).expect("should parse"); + assert_eq!(pair.stat, expected_stat, "stat mismatch"); + assert_eq!(pair.value.0, expected_val, "value mismatch"); +} +#[test] +fn test_stat_pair_parsing() { + // Colon syntax + assert_pair_ok("cri:10", ListStats::Crime, 10); + assert_pair_ok("POP:-5", ListStats::Population, -5); + assert_pair_ok("growth:0", ListStats::Growthrate, 0); + + // Space syntax (clap concatenates two separate args into one string) + assert_pair_ok("cri 10", ListStats::Crime, 10); + assert_pair_ok("Pop -5", ListStats::Population, -5); + assert_pair_ok("grow 0", ListStats::Growthrate, 0); +} +#[test] +fn test_list_stats_all_aliases() { + let stats = OverallStats::default(); + // Demographics + assert_stat_ok("dem", ListStats::Demographics); + assert_stat_ok("Demog", ListStats::Demographics); + assert_stat_ok("DEMOGRAPHICS", ListStats::Demographics); + assert_stat_ok("Demo", ListStats::Demographics); + stats.get_field(ListStats::Demographics.into()); + // Population + assert_stat_ok("pop", ListStats::Population); + assert_stat_ok("Popul", ListStats::Population); + assert_stat_ok("POPULATIONS", ListStats::Population); + stats.get_field(ListStats::Population.into()); + + // Growthrate + assert_stat_ok("grow", ListStats::Growthrate); + assert_stat_ok("GRW", ListStats::Growthrate); + assert_stat_ok("Growth", ListStats::Growthrate); + stats.get_field(ListStats::Growthrate.into()); + + // Crime + assert_stat_ok("cri", ListStats::Crime); + assert_stat_ok("CRIM", ListStats::Crime); + assert_stat_ok("Crimes", ListStats::Crime); + stats.get_field(ListStats::Crime.into()); + + // Happiness + assert_stat_ok("hapn", ListStats::Happiness); + assert_stat_ok("HAPPINES", ListStats::Happiness); + assert_stat_ok("hap", ListStats::Happiness); + stats.get_field(ListStats::Happiness.into()); + + // Economy + assert_stat_ok("eco", ListStats::Economy); + assert_stat_ok("Economy", ListStats::Economy); + assert_stat_ok("econ", ListStats::Economy); + stats.get_field(ListStats::Economy.into()); + + // Food + assert_stat_ok("food", ListStats::Food); + assert_stat_ok("fo", ListStats::Food); + assert_stat_ok("agr", ListStats::Food); + assert_stat_ok("agri", ListStats::Food); + stats.get_field(ListStats::Food.into()); + + // Industry + assert_stat_ok("industry", ListStats::Industry); + assert_stat_ok("Indus", ListStats::Industry); + assert_stat_ok("ind", ListStats::Industry); + stats.get_field(ListStats::Industry.into()); + + // Science + assert_stat_ok("science", ListStats::Science); + assert_stat_ok("sci", ListStats::Science); + assert_stat_ok("sc", ListStats::Science); + stats.get_field(ListStats::Science.into()); + + // Trade + assert_stat_ok("trade", ListStats::Trade); + assert_stat_ok("trd", ListStats::Trade); + assert_stat_ok("tr", ListStats::Trade); + stats.get_field(ListStats::Trade.into()); + + // Social + assert_stat_ok("social", ListStats::Social); + assert_stat_ok("soc", ListStats::Social); + assert_stat_ok("sl", ListStats::Social); + stats.get_field(ListStats::Social.into()); + + // Culture + assert_stat_ok("culture", ListStats::Culture); + assert_stat_ok("cul", ListStats::Culture); + assert_stat_ok("cl", ListStats::Culture); + stats.get_field(ListStats::Culture.into()); + + // Education + assert_stat_ok("education", ListStats::Education); + assert_stat_ok("edu", ListStats::Education); + assert_stat_ok("ed", ListStats::Education); + stats.get_field(ListStats::Education.into()); + + // Tourism + assert_stat_ok("tourism", ListStats::Tourism); + assert_stat_ok("tour", ListStats::Tourism); + assert_stat_ok("tm", ListStats::Tourism); + stats.get_field(ListStats::Tourism.into()); + + // Influence + assert_stat_ok("influence", ListStats::Influence); + assert_stat_ok("infl", ListStats::Influence); + assert_stat_ok("influ", ListStats::Influence); + stats.get_field(ListStats::Influence.into()); + + // Military + assert_stat_ok("military", ListStats::Military); + assert_stat_ok("mil", ListStats::Military); + assert_stat_ok("mt", ListStats::Military); + stats.get_field(ListStats::Military.into()); + + // Army + assert_stat_ok("army", ListStats::Army); + assert_stat_ok("arm", ListStats::Army); + assert_stat_ok("ar", ListStats::Army); + stats.get_field(ListStats::Army.into()); + + // Strength + assert_stat_ok("strength", ListStats::Strength); + assert_stat_ok("str", ListStats::Strength); + assert_stat_ok("st", ListStats::Strength); + stats.get_field(ListStats::Strength.into()); + + // Fortification + assert_stat_ok("fortification", ListStats::Fortification); + assert_stat_ok("fort", ListStats::Fortification); + assert_stat_ok("ft", ListStats::Fortification); + stats.get_field(ListStats::Fortification.into()); + + // Threat + assert_stat_ok("threat", ListStats::Threat); + assert_stat_ok("thr", ListStats::Threat); + assert_stat_ok("th", ListStats::Threat); + stats.get_field(ListStats::Threat.into()); + + // Infrastructure + assert_stat_ok("infrastructure", ListStats::Infrastructure); + assert_stat_ok("infra", ListStats::Infrastructure); + assert_stat_ok("infr", ListStats::Infrastructure); + stats.get_field(ListStats::Infrastructure.into()); + + // Bureaucracy + assert_stat_ok("bureaucracy", ListStats::Bureaucracy); + assert_stat_ok("bureau", ListStats::Bureaucracy); + assert_stat_ok("bur", ListStats::Bureaucracy); + stats.get_field(ListStats::Bureaucracy.into()); + + // Transportation + assert_stat_ok("transportation", ListStats::Transportation); + assert_stat_ok("trans", ListStats::Transportation); + assert_stat_ok("trns", ListStats::Transportation); + stats.get_field(ListStats::Transportation.into()); + + // Sprawl + assert_stat_ok("sprawl", ListStats::Sprawl); + assert_stat_ok("spr", ListStats::Sprawl); + assert_stat_ok("spra", ListStats::Sprawl); + stats.get_field(ListStats::Sprawl.into()); + + // Health + assert_stat_ok("health", ListStats::Health); + assert_stat_ok("hlth", ListStats::Health); + assert_stat_ok("hlt", ListStats::Health); + stats.get_field(ListStats::Health.into()); +} -- 2.45.1 From f121f12eb150d94e299164272c65ccaf164144fc Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Tue, 2 Dec 2025 20:31:57 +0100 Subject: [PATCH 20/22] More on show --- bin_efo/src/commands.rs | 1 + bin_efo/src/commands/epoch.rs | 23 +- bin_efo/src/commands/show.rs | 38 + bin_efo/src/main.rs | 37 +- lib_efo/src/entity.rs | 2 +- naming.json | 2360 +++++++++++++++++++++++++++++++++ 6 files changed, 2426 insertions(+), 35 deletions(-) create mode 100644 bin_efo/src/commands/show.rs create mode 100644 naming.json diff --git a/bin_efo/src/commands.rs b/bin_efo/src/commands.rs index 2b3f2e9..1e8a1e0 100644 --- a/bin_efo/src/commands.rs +++ b/bin_efo/src/commands.rs @@ -10,6 +10,7 @@ pub mod epoch; pub mod init; +pub mod show; // pub mod diff; // pub mod utils; // pub mod event; diff --git a/bin_efo/src/commands/epoch.rs b/bin_efo/src/commands/epoch.rs index d260bfd..930d1a7 100644 --- a/bin_efo/src/commands/epoch.rs +++ b/bin_efo/src/commands/epoch.rs @@ -38,7 +38,7 @@ pub mod cli_epoch; /// /// The function never panics under normal operation. All errors are /// reported via the returned `Result`. -pub fn handle_cmd(cmd: cli_epoch::EpochCmd) -> Result<(), AppError> { +pub fn handle_cmd(cmd: &cli_epoch::EpochCmd) -> Result<(), AppError> { let mut main_epoch = EpochConfig::new_from_path(None)?; // // TODO[2]: Remove this debug debug!("The main epoch befor any action is {:#?}", main_epoch); @@ -66,14 +66,17 @@ pub fn handle_cmd(cmd: cli_epoch::EpochCmd) -> Result<(), AppError> { /// /// This helper is internal to the `epoch` sub-command and is not part /// of the public API. -fn handle_summary(args: cli_epoch::Summary, main_epoch: &mut EpochConfig) -> Result<(), AppError> { +fn handle_summary(args: &cli_epoch::Summary, main_epoch: &mut EpochConfig) -> Result<(), AppError> { let epoch_id = main_epoch.epoch_id; main_epoch.try_load(&epoch_id)?; #[allow(clippy::unwrap_used)] // The epoch_id must exists at this point if let Some(epoch) = main_epoch.list_existing_epochs.get_mut(&epoch_id).unwrap() { epoch.summary = args.summary.clone(); epoch.save_with_context("Saving new summary", &lib_efo::epoch::SaveMode::Erase)?; - display_success(&SuccessMessages::ChangedSummary(epoch_id, args.summary)); + display_success(&SuccessMessages::ChangedSummary( + epoch_id, + args.summary.clone(), + )); } Ok(()) @@ -86,7 +89,7 @@ fn handle_summary(args: cli_epoch::Summary, main_epoch: &mut EpochConfig) -> Res /// /// This helper is internal to the `epoch` sub-command and is not part /// of the public API. -fn handle_diff(args: cli_epoch::Diff) -> Result<(), AppError> { +fn handle_diff(args: &cli_epoch::Diff) -> Result<(), AppError> { let _ = args; unimplemented!("Blocker: There is actually no way to diff the world yet") } @@ -100,7 +103,7 @@ fn handle_diff(args: cli_epoch::Diff) -> Result<(), AppError> { /// underlying `EpochConfig::log_elements` implementation. /// /// This helper is internal to the `epoch` sub-command. -fn handle_log(args: cli_epoch::Log, main_epoch: &mut EpochConfig) -> Result<(), AppError> { +fn handle_log(args: &cli_epoch::Log, main_epoch: &mut EpochConfig) -> Result<(), AppError> { let limit = args.limit; let start_id = &main_epoch.epoch_id; @@ -122,7 +125,7 @@ fn handle_log(args: cli_epoch::Log, main_epoch: &mut EpochConfig) -> Result<(), /// success message via `display_success`. /// /// This helper is internal to the `epoch` sub-command. -fn handle_switch(args: cli_epoch::Switch, main_epoch: &mut EpochConfig) -> Result<(), AppError> { +fn handle_switch(args: &cli_epoch::Switch, main_epoch: &mut EpochConfig) -> Result<(), AppError> { let target = main_epoch.get(&args.target)?; main_epoch.try_load(&target)?; main_epoch.epoch_id = target; @@ -150,7 +153,7 @@ fn handle_switch(args: cli_epoch::Switch, main_epoch: &mut EpochConfig) -> Resul /// * `Ok(())` if the next epoch was successfully computed. /// * `Err(AppError::Epoch(EpochError::FutureEpochExist))` if there are /// no future epochs to advance to. -fn handle_next(_args: cli_epoch::Next, main_epoch: &mut EpochConfig) -> Result<(), AppError> { +fn handle_next(_args: &cli_epoch::Next, main_epoch: &mut EpochConfig) -> Result<(), AppError> { let current_id = main_epoch.epoch_id; // Check that there are no future epochs @@ -183,7 +186,7 @@ fn handle_next(_args: cli_epoch::Next, main_epoch: &mut EpochConfig) -> Result<( /// # Returns /// * `Ok(())` if all future epochs were successfully removed. /// * `Err(AppError)` if any deletion fails. -fn handle_reset(args: cli_epoch::Reset, main_epoch: &mut EpochConfig) -> Result<(), AppError> { +fn handle_reset(args: &cli_epoch::Reset, main_epoch: &mut EpochConfig) -> Result<(), AppError> { let _ = args; let current_id = main_epoch.epoch_id; // for id in main_epoch @@ -217,7 +220,7 @@ fn handle_reset(args: cli_epoch::Reset, main_epoch: &mut EpochConfig) -> Result< /// already exists in another epoch. /// * `Err(AppError::Epoch(EpochError::Unknown))` if the epoch cannot /// be found or saved. -fn handle_taging(args: cli_epoch::Tag, main_epoch: &mut EpochConfig) -> Result<(), AppError> { +fn handle_taging(args: &cli_epoch::Tag, main_epoch: &mut EpochConfig) -> Result<(), AppError> { // Load into memory the current epoch main_epoch.try_load(&main_epoch.epoch_id.clone())?; @@ -263,7 +266,7 @@ fn handle_taging(args: cli_epoch::Tag, main_epoch: &mut EpochConfig) -> Result<( /// command may also print a diagnostic message to the user. /// /// This helper is internal to the `epoch` sub-command. -fn handle_fsck(args: cli_epoch::Fsck, main_epoch: &mut EpochConfig) -> Result<(), AppError> { +fn handle_fsck(args: &cli_epoch::Fsck, main_epoch: &mut EpochConfig) -> Result<(), AppError> { let _ = main_epoch; let _ = args; unimplemented!() diff --git a/bin_efo/src/commands/show.rs b/bin_efo/src/commands/show.rs new file mode 100644 index 0000000..b00fd59 --- /dev/null +++ b/bin_efo/src/commands/show.rs @@ -0,0 +1,38 @@ +//! The show commands +//! + +use clap::Subcommand; +use lib_efo::{Displayable, entity::Entity, naming::NAMING}; + +use crate::error::AppError; +#[derive(Subcommand, Debug)] +/// Show command +pub enum ShowCmd { + /// Show an event + Event, +} + +/// Handle all show cmds +pub fn handle_show_cmd(cmd: &ShowCmd) -> Result<(), AppError> { + let _ = cmd; + let mut e = Entity::default(); + e.name = NAMING.generate_long_character_name(); + println!("Original Struct: \n{e:#?}"); + println!("\n\n\nONELINES"); + println!("{}", e.oneline_display()); + println!("{}", e.oneline_display()); + println!("{}", e.oneline_display()); + println!("{}", e.oneline_display()); + println!("{}", e.oneline_display()); + println!("{}", e.oneline_display()); + println!("{}", e.oneline_display()); + println!("\n\n\n SHORT"); + e.print_short(); + + println!("\n\n\n LONG"); + e.print_full(); + println!("\n\n\n TREE"); + println!("{}", e.to_pretty_tree()); + + Ok(()) +} diff --git a/bin_efo/src/main.rs b/bin_efo/src/main.rs index e5e66f1..966fdca 100644 --- a/bin_efo/src/main.rs +++ b/bin_efo/src/main.rs @@ -23,12 +23,14 @@ #![warn(missing_docs, clippy::missing_docs_in_private_items)] #![deny(clippy::unwrap_used)] -use clap::{ArgAction, Parser, Subcommand}; -use lib_efo::Displayable; -use lib_efo::entity::Entity; +use std::fmt::Debug; -use crate::commands::init::InitCmd; -use crate::{commands::epoch::cli_epoch::EpochCmd, error::AppError}; +use clap::{ArgAction, Parser, Subcommand}; + +use crate::{ + commands::{epoch::cli_epoch::EpochCmd, init::InitCmd, show::ShowCmd}, + error::AppError, +}; mod commands; mod error; mod success; @@ -61,6 +63,9 @@ enum TopLevelCmd { /// Advance or query the current epoch. #[command(subcommand)] Epoch(EpochCmd), + /// Display some elements + #[command(subcommand)] + Show(ShowCmd), // Event(commands::event::EventCmd), // Org(commands::org::OrgCmd), // Chr(commands::chr::ChrCmd), @@ -77,18 +82,6 @@ enum TopLevelCmd { fn main() -> miette::Result<()> { env_logger::init(); - let e = Entity::default(); - // println!("{e:#?}"); - println!("{}", e.oneline_display()); - println!("{}", e.oneline_display()); - println!("{}", e.oneline_display()); - println!("{}", e.oneline_display()); - println!("{}", e.oneline_display()); - println!("{}", e.oneline_display()); - println!("{}", e.oneline_display()); - // e.print_short(); - // e.print_full(); - // println!("{}", e.to_pretty_tree()); let cli = Cli::parse(); if let Err(e) = exec_dispatch(cli) { @@ -113,12 +106,8 @@ fn main() -> miette::Result<()> { /// stdout and returned as a `miette::Result<()>`. fn exec_dispatch(cli: Cli) -> Result<(), AppError> { match cli.command { - TopLevelCmd::Init(cmd) => { - commands::init::init(&cmd)?; - } - TopLevelCmd::Epoch(cmd) => { - commands::epoch::handle_cmd(cmd)?; - } + TopLevelCmd::Init(cmd) => commands::init::init(&cmd), + TopLevelCmd::Epoch(cmd) => commands::epoch::handle_cmd(&cmd), + TopLevelCmd::Show(cmd) => commands::show::handle_show_cmd(&cmd), } - Ok(()) } diff --git a/lib_efo/src/entity.rs b/lib_efo/src/entity.rs index 21e658b..93bc703 100644 --- a/lib_efo/src/entity.rs +++ b/lib_efo/src/entity.rs @@ -22,7 +22,7 @@ pub mod implementations; #[derive(Serialize, Deserialize, Debug, Clone, Default)] pub struct Entity { /// The name of the entity - name: String, + pub name: String, /// Runtime statistics that determine the entity’s behaviour. /// /// These values are updated by the game loop and reflect the diff --git a/naming.json b/naming.json new file mode 100644 index 0000000..a52eba0 --- /dev/null +++ b/naming.json @@ -0,0 +1,2360 @@ +{ + "first_names": [ + "Aeron", + "Brienne", + "Cedric", + "Darya", + "Eldon", + "Fiora", + "Galen", + "Hela", + "Ivor", + "Juno", + "Aldric", + "Briar", + "Caelum", + "Dorin", + "Elysia", + "Fendrel", + "Gryphon", + "Hector", + "Iseult", + "Kael", + "Lysander", + "Morgath", + "Nyx", + "Odin", + "Riven", + "Sylvan", + "Thorne", + "Valen", + "Wraith", + "Xander", + "Yara", + "Zarek", + "Artemis", + "Baldric", + "Corvin", + "Draven", + "Eira", + "Fenris", + "Gale", + "Helios", + "Ivy", + "Jasper", + "Kara", + "Luna", + "Mira", + "Nimrod", + "Onyx", + "Peregrine", + "Quinn", + "Aegon", + "Brek", + "Calandra", + "Darrion", + "Eryndor", + "Fenn", + "Galax", + "Hestia", + "Ilarion", + "Jareth", + "Kassandra", + "Lyris", + "Maelor", + "Nyssa", + "Oren", + "Phaedra", + "Quillon", + "Rhea", + "Soren", + "Thalia", + "Uther", + "Vesper", + "Wulfric", + "Xara", + "Yoren", + "Zorath", + "Aerith", + "Baldrick", + "Cress", + "Dazai", + "Elara", + "Fira" + ], + "last_names": [ + "Ashwood", + "Blackthorn", + "Cinderglow", + "Dunwynn", + "Everfield", + "Frosthelm", + "Goldleaf", + "Holloway", + "Iverson", + "Jasper", + "Ravencrest", + "Stormblade", + "Nightshade", + "Wraithborne", + "Dreadmoor", + "Ironhart", + "Bloodstone", + "Stonegate", + "Gloomreach", + "Sablewick", + "Rookhaven", + "Ironcrest", + "Bleakmoor", + "Thornshield", + "Wyrmwood", + "Darkwater", + "Stormbreaker", + "Ebonhart", + "Bloodbane", + "Eclipseborne", + "Firethorn", + "Silvershade", + "Blackfrost", + "Sorrowblade", + "Stonehelm", + "Gravelock", + "Voidwalker", + "Nightfall", + "Ashenfall", + "Ashenridge", + "Duskfall", + "Thornhaven", + "Gloombreaker", + "Riftwalker", + "Althmar", + "Brimstone", + "Cinderfall", + "Duskbane", + "Emberforge", + "Frostbane", + "Grimsbane", + "Ironbark", + "Jaggedspire", + "Keldrith", + "Lament", + "Mistveil", + "Nightglow", + "Oathbreaker", + "Palegrave", + "Quicksilver", + "Riftshard", + "Shadowforge", + "Thornbane", + "Umbral", + "Vengeance", + "Wraithbane", + "Xylander", + "Yester", + "Zephyr", + "Blackfire", + "Bloodthorn", + "Crimsonveil", + "Dreadspire", + "Eboncrest", + "Firebrand", + "Grimshard", + "Ironheart", + "Javelin", + "Krait", + "Luminous", + "Marrowbone", + "Nocturne", + "Obsidian", + "Pyre", + "Quagmire", + "Reaver", + "Sableheart", + "Tidebreaker" + ], + "town_prefixes": [ + "Ash", + "Bright", + "Cedar", + "Deep", + "Elder", + "Frost", + "Glen", + "High", + "Iron", + "Jade", + "Ashen", + "Blood", + "Cobalt", + "Dusk", + "Ebon", + "Gloom", + "Ironforge", + "Keen", + "Mourn", + "Raven", + "Storm", + "Void", + "Wraith", + "Night", + "Silvers", + "Black", + "Crimson", + "Fire", + "Grim", + "Briar", + "Obsidian", + "Shade", + "Thorn", + "Sable", + "Rift", + "Dread", + "Sorrow", + "Bleak", + "Eclipse", + "Eternity", + "Glint", + "Gleam", + "Hollow", + "Lament", + "Mire", + "Molt", + "Nocturne", + "Onyx", + "Pale", + "Rook", + "Shimmer", + "Stonem", + "Stone", + "Stonehold", + "Stonekeep", + "Stoneforge", + "Stormfall", + "Stormgate", + "Stormhold", + "Stormreach", + "Stormspire", + "Stormwind", + "Throne", + "Twilight", + "Valiant", + "Valest", + "Valer", + "Vex", + "Vile", + "Warden" + ], + "town_suffixes": [ + "brook", + "dale", + "field", + "haven", + "keep", + "moor", + "port", + "reach", + "stone", + "vale", + "forge", + "shard", + "hollow", + "cove", + "hall", + "watch", + "spire", + "glade", + "cliff", + "glen", + "tower", + "fort", + "hold", + "bastion", + "crypt", + "crossing", + "crown", + "ridge", + "fell", + "breach", + "briar", + "bloom", + "field", + "river", + "canyon", + "fen", + "crag", + "gate", + "bridge", + "watchtower", + "watcher", + "mire", + "waste", + "breach", + "fall", + "crone", + "shadow", + "veil", + "blight", + "soul", + "night", + "storm", + "fire", + "ice", + "iron", + "dark", + "glimmer", + "glare", + "scar", + "scarred", + "spire", + "peak", + "ridge", + "hall", + "hold", + "spire", + "vale", + "vale", + "haven", + "hollow", + "breach", + "crust" + ], + "character_adjectives": [ + "the Blind", + "the Magnificent", + "the Cunning", + "the Swift", + "the Stoic", + "the Fearless", + "the Enigmatic", + "the Shadow", + "the Light", + "the Wanderer", + "the Unbroken", + "the Relentless", + "the Ruthless", + "the Merciless", + "the Devourer", + "the Ancient", + "the Fallen", + "the Immortal", + "the Vengeful", + "the Stormborn", + "the Silent", + "the Bloodied", + "the Corrupt", + "the Darkened", + "the Ember", + "the Crimson", + "the Iron", + "the Sable", + "the Radiant", + "the Tempest", + "the Gloom", + "the Warlord", + "the Titan", + "the Behemoth", + "the Leviathan", + "the Doombringer", + "the Wraith", + "the Sundered", + "the Gloomstalker", + "the Blight", + "the Harbinger", + "the Abyssal", + "the Scourge", + "the Dread", + "the Fury", + "the Specter", + "the Maw", + "the Protector", + "the Guardian", + "the Champion", + "the Savior", + "the Reaper", + "the Harvester", + "the Seeker", + "the Whisperer", + "the Tempest-born", + "the Iron-clad", + "the Moonlit", + "the Sun-scarred", + "the Bone-choked", + "the Frost-kissed", + "the Ashen", + "the Shattered", + "the Echo-bound", + "the Vile", + "the Harsh", + "the Unseen", + "the Unyielding", + "of the North", + "of the South", + "of the East", + "of the West", + "of the Dark", + "of the Light", + "of the Forgotten", + "of the Broken", + "of the Eternal", + "of the Shadowlands", + "of the Burning", + "of the Frozen", + "of the Storm", + "of the Depths", + "of the Maw", + "of the Ashen Sea", + "of the Crimson Dawn" + ], + "character_prefixes": [ + "Sir", + "Lady", + "Mighty", + "Elder", + "Grand", + "Humble", + "Radiant", + "Lord", + "High", + "Royal", + "Ancient", + "Warden", + "Seer", + "Master" + ], + "event_ideas": [ + { + "name": "storm_flood", + "description": "A sudden storm floods the river, threatening the local farms.", + "stats": [ + { + "stat": "Population", + "value": -5 + }, + { + "stat": "Food", + "value": -12 + } + ], + "duration": { + "Duration": 1 + }, + "application": "PermanentEffectToApply", + "effect_bounds": { + "min": 10, + "max": 70 + } + }, + { + "name": "earthquake", + "description": "A massive quake ripples across the region.", + "stats": [ + { + "stat": "Transportation", + "value": -9 + }, + { + "stat": "Sprawl", + "value": -5 + }, + { + "stat": "Health", + "value": -3 + }, + { + "stat": "Industry", + "value": -2 + }, + { + "stat": "Population", + "value": -10 + }, + { + "stat": "Happiness", + "value": -8 + } + ], + "duration": { + "Duration": 1 + }, + "application": "PermanentEffectToApply", + "effect_bounds": { + "min": 10, + "max": 110 + } + }, + { + "name": "region_blood_monsoon", + "description": "A crimson rain falls over the region, poisoning crops and water sources.", + "stats": [ + { + "stat": "Food", + "value": -18 + }, + { + "stat": "Health", + "value": -12 + }, + { + "stat": "Population", + "value": -7 + } + ], + "duration": { + "Duration": 1 + }, + "application": "PermanentEffectToApply", + "effect_bounds": { + "min": 10, + "max": 110 + } + }, + { + "name": "town_haunted_market", + "description": "Spectral merchants appear, selling cryptic ware from a bygone era.", + "stats": [ + { + "stat": "Trade", + "value": 9 + }, + { + "stat": "Science", + "value": 9 + }, + { + "stat": "Food", + "value": 13 + }, + { + "stat": "Crime", + "value": 7 + }, + { + "stat": "Threat", + "value": 11 + } + ], + "duration": { + "Duration": 3 + }, + "application": "WhenPresent", + "effect_bounds": { + "min": 10, + "max": 80 + } + }, + { + "name": "region_darkening_sun", + "description": "The sky is shrouded in an unnatural pallid dusk, lowering morale and crop yields.", + "stats": [ + { + "stat": "Happiness", + "value": -14 + }, + { + "stat": "Food", + "value": -10 + }, + { + "stat": "Culture", + "value": -5 + } + ], + "duration": { + "Duration": 6 + }, + "application": "WhenPresent", + "effect_bounds": { + "min": 20, + "max": 90 + } + }, + { + "name": "town_giant_earthworm", + "description": "A colossal earthworm burrows beneath the town, destabilizing foundations and causing tremors.", + "stats": [ + { + "stat": "Food", + "value": -5 + }, + { + "stat": "Industry", + "value": -2 + }, + { + "stat": "Happiness", + "value": -12 + }, + { + "stat": "Fortification", + "value": -8 + }, + { + "stat": "Population", + "value": -4 + } + ], + "duration": { + "Duration": 4 + }, + "application": "WhenPresent", + "effect_bounds": { + "min": 30, + "max": 70 + } + }, + { + "name": "region_arcane_surge", + "description": "An uncontrollable surge of raw sangressence tears through reality, causing unpredictable effects.", + "stats": [ + { + "stat": "Science", + "value": 12 + }, + { + "stat": "Education", + "value": 8 + }, + { + "stat": "Population", + "value": -6 + } + ], + "duration": { + "Duration": 6 + }, + "application": "WhenPresent", + "effect_bounds": { + "min": 30, + "max": 70 + } + }, + { + "name": "town_mushroom_meteor", + "description": "A meteor of colossal fungi explodes over a town, releasing spores that induce vivid hallucinations.", + "stats": [ + { + "stat": "Health", + "value": -10 + }, + { + "stat": "Crime", + "value": 6 + }, + { + "stat": "Population", + "value": -3 + } + ], + "duration": { + "Duration": 1 + }, + "application": "PermanentEffectToApply", + "effect_bounds": { + "min": 20, + "max": 90 + } + }, + { + "name": "region_infernal_flood", + "description": "Molten rivers run through the region, boiling over cities and devouring forests.", + "stats": [ + { + "stat": "Transportation", + "value": -4 + }, + { + "stat": "Sprawl", + "value": -5 + }, + { + "stat": "Happiness", + "value": -19 + }, + { + "stat": "Food", + "value": -15 + }, + { + "stat": "Population", + "value": -12 + } + ], + "duration": { + "Duration": 5 + }, + "application": "WhenPresent", + "effect_bounds": { + "min": 20, + "max": 90 + } + }, + { + "name": "region_sand_vortex", + "description": "A vortex of shifting sands sweeps the region, burying entire nations under dunes.", + "stats": [ + { + "stat": "Bureaucracy", + "value": -14 + }, + { + "stat": "Transportation", + "value": -14 + }, + { + "stat": "Sprawl", + "value": -14 + }, + { + "stat": "Population", + "value": -16 + }, + { + "stat": "Trade", + "value": -10 + } + ], + "duration": { + "Duration": 5 + }, + "application": "WhenPresent", + "effect_bounds": { + "min": 20, + "max": 90 + } + }, + { + "name": "region_wind_of_gods", + "description": "A relentless gale from the gods tears through the region, scattering armies and wrecking supply lines.", + "stats": [ + { + "stat": "Transportation", + "value": -12 + }, + { + "stat": "Army", + "value": -9 + }, + { + "stat": "Population", + "value": -3 + } + ], + "duration": { + "Duration": 8 + }, + "application": "WhenPresent", + "effect_bounds": { + "min": 20, + "max": 90 + } + }, + { + "name": "region_ancient_sunrise", + "description": "The sun rises in a crimson glow, amplifying the power of all dark cults and spreading fear.", + "stats": [ + { + "stat": "Crime", + "value": 9 + }, + { + "stat": "Happiness", + "value": -8 + }, + { + "stat": "Influence", + "value": -5 + } + ], + "duration": { + "Duration": 7 + }, + "application": "WhenPresent", + "effect_bounds": { + "min": 20, + "max": 90 + } + }, + { + "name": "town_forest_of_eyes", + "description": "A forest that watches every step, slowly siphoning the life force from any who walk through.", + "stats": [ + { + "stat": "Health", + "value": -10 + }, + { + "stat": "Crime", + "value": 7 + }, + { + "stat": "Happiness", + "value": 7 + }, + { + "stat": "Population", + "value": -14 + } + ], + "duration": { + "Duration": 8 + }, + "application": "WhenPresent", + "effect_bounds": { + "min": 20, + "max": 90 + } + }, + { + "name": "city_corruption_scandal", + "description": "A high‑ranking magistrate is discovered embezzling city funds, sparking public outrage and a demand for accountability.", + "stats": [ + { + "stat": "Food", + "value": -4 + }, + { + "stat": "Industry", + "value": -3 + }, + { + "stat": "Science", + "value": -3 + }, + { + "stat": "Trade", + "value": -8 + }, + { + "stat": "Bureaucracy", + "value": -7 + }, + { + "stat": "Crime", + "value": 7 + } + ], + "duration": { + "Duration": 1 + }, + "application": "PermanentEffectToApply", + "effect_bounds": { + "min": 22, + "max": 86 + } + }, + { + "name": "city_tax_reform", + "description": "The council implements a sweeping tax overhaul that raises revenue but triggers protests among merchants.", + "stats": [ + { + "stat": "Food", + "value": 9 + }, + { + "stat": "Industry", + "value": 10 + }, + { + "stat": "Science", + "value": 7 + }, + { + "stat": "Trade", + "value": 13 + }, + { + "stat": "Happiness", + "value": -4 + }, + { + "stat": "Crime", + "value": 5 + } + ], + "duration": { + "Duration": 1 + }, + "application": "PermanentEffectToApply", + "effect_bounds": { + "min": 25, + "max": 92 + } + }, + { + "name": "city_watch_mutiny", + "description": "The city guard, disgruntled by unpaid wages, mutinies turns bandits.", + "stats": [ + { + "stat": "Strength", + "value": -6 + }, + { + "stat": "Crime", + "value": 8 + }, + { + "stat": "Population", + "value": -2 + } + ], + "duration": { + "Duration": 1 + }, + "application": "PermanentEffectToApply", + "effect_bounds": { + "min": 18, + "max": 80 + } + }, + { + "name": "city_water_contamination", + "description": "Tainted water leaks into the municipal supply, causing a sudden spike in illnesses.", + "stats": [ + { + "stat": "Health", + "value": -14 + }, + { + "stat": "Population", + "value": -5 + }, + { + "stat": "Bureaucracy", + "value": -3 + } + ], + "duration": { + "Duration": 1 + }, + "application": "PermanentEffectToApply", + "effect_bounds": { + "min": 21, + "max": 88 + } + }, + { + "name": "city_bureaucratic_bureaucracy", + "description": "A new procedural reform overhauls city administration, halting projects for months and stalling economic growth.", + "stats": [ + { + "stat": "Bureaucracy", + "value": 14 + }, + { + "stat": "Sprawl", + "value": -9 + }, + { + "stat": "Health", + "value": -7 + }, + { + "stat": "Food", + "value": 3 + }, + { + "stat": "Industry", + "value": 2 + }, + { + "stat": "Science", + "value": 3 + }, + { + "stat": "Trade", + "value": 4 + } + ], + "duration": { + "Duration": 1 + }, + "application": "PermanentEffectToApply", + "effect_bounds": { + "min": 23, + "max": 90 + } + }, + { + "name": "city_guild_suppression", + "description": "The council cracks down on the city's merchant guilds, confiscating goods and driving merchants underground.", + "stats": [ + { + "stat": "Trade", + "value": -11 + }, + { + "stat": "Crime", + "value": 6 + }, + { + "stat": "Population", + "value": -3 + } + ], + "duration": { + "Duration": 1 + }, + "application": "PermanentEffectToApply", + "effect_bounds": { + "min": 19, + "max": 83 + } + }, + { + "name": "city_civic_riot", + "description": "An assembly of disgruntled workers erupts into a violent riot, tearing through market stalls and public buildings.", + "stats": [ + { + "stat": "Trade", + "value": -12 + }, + { + "stat": "Happiness", + "value": -9 + }, + { + "stat": "Crime", + "value": 10 + } + ], + "duration": { + "Duration": 2 + }, + "application": "WhenPresent", + "effect_bounds": { + "min": 25, + "max": 95 + } + }, + { + "name": "city_public_health_crisis", + "description": "A mysterious disease spreads through the city's crowded streets, overwhelming the local infirmaries.", + "stats": [ + { + "stat": "Health", + "value": -3 + }, + { + "stat": "Population", + "value": -3 + }, + { + "stat": "Happiness", + "value": -2 + } + ], + "duration": { + "Duration": 6 + }, + "application": "Recurring", + "effect_bounds": { + "min": 20, + "max": 95 + } + }, + { + "name": "city_transport_infrastructure_fail", + "description": "The city's main aqueduct collapses, cutting off water supply to half the districts.", + "stats": [ + { + "stat": "Transportation", + "value": -15 + }, + { + "stat": "Population", + "value": -4 + }, + { + "stat": "Bureaucracy", + "value": -2 + } + ], + "duration": { + "Duration": 1 + }, + "application": "PermanentEffectToApply", + "effect_bounds": { + "min": 20, + "max": 90 + } + }, + { + "name": "city_festival_corruption", + "description": "During a grand city festival, officials accept bribes to award contracts, compromising civic integrity.", + "stats": [ + { + "stat": "Bureaucracy", + "value": -8 + }, + { + "stat": "Crime", + "value": 4 + }, + { + "stat": "Happiness", + "value": -3 + } + ], + "duration": { + "Duration": 1 + }, + "application": "PermanentEffectToApply", + "effect_bounds": { + "min": 20, + "max": 90 + } + }, + { + "name": "city_gold_exodus", + "description": "A sudden discovery of gold in the hinterlands draws merchants away, leaving local markets starved of currency.", + "stats": [ + { + "stat": "Food", + "value": -4 + }, + { + "stat": "Industry", + "value": -4 + }, + { + "stat": "Trade", + "value": -8 + }, + { + "stat": "Population", + "value": -2 + } + ], + "duration": { + "Duration": 1 + }, + "application": "PermanentEffectToApply", + "effect_bounds": { + "min": 20, + "max": 90 + } + }, + { + "name": "regional_drought", + "description": "An extended dry spell cripples crop yields, driving up food prices and crippling the agrarian economy.", + "stats": [ + { + "stat": "Food", + "value": -15 + }, + { + "stat": "Trade", + "value": -13 + }, + { + "stat": "Happiness", + "value": -5 + } + ], + "duration": { + "Duration": 1 + }, + "application": "PermanentEffectToApply", + "effect_bounds": { + "min": 20, + "max": 90 + } + }, + { + "name": "city_tariff_levy", + "description": "The city council imposes a high tariff on imported goods to boost local industry, sparking backlash from merchants.", + "stats": [ + { + "stat": "Trade", + "value": -10 + }, + { + "stat": "Food", + "value": -4 + }, + { + "stat": "Industry", + "value": -6 + }, + { + "stat": "Science", + "value": -3 + }, + { + "stat": "Crime", + "value": 15 + } + ], + "duration": { + "Duration": 1 + }, + "application": "PermanentEffectToApply", + "effect_bounds": { + "min": 20, + "max": 90 + } + }, + { + "name": "market_hoarding", + "description": "A powerful merchant cartel hoards staple goods, manipulating prices to inflate profits at the cost of ordinary citizens.", + "stats": [ + { + "stat": "Food", + "value": -7 + }, + { + "stat": "Industry", + "value": -6 + }, + { + "stat": "Trade", + "value": -7 + }, + { + "stat": "Population", + "value": -3 + } + ], + "duration": { + "Duration": 7 + }, + "application": "WhenPresent", + "effect_bounds": { + "min": 20, + "max": 90 + } + }, + { + "name": "industrial_explosion", + "description": "A catastrophic blast at the main ironworks destroys equipment and halts production for months.", + "stats": [ + { + "stat": "Industry", + "value": -19 + }, + { + "stat": "Food", + "value": -3 + }, + { + "stat": "Trade", + "value": -7 + }, + { + "stat": "Population", + "value": -4 + } + ], + "duration": { + "Duration": 1 + }, + "application": "PermanentEffectToApply", + "effect_bounds": { + "min": 20, + "max": 90 + } + }, + { + "name": "foreign_investment_boom", + "description": "A foreign dynasty invests heavily in local mining, sparking a surge in jobs and wealth but also widening inequality.", + "stats": [ + { + "stat": "Industry", + "value": 12 + }, + { + "stat": "Science", + "value": 3 + }, + { + "stat": "Trade", + "value": 8 + }, + { + "stat": "Crime", + "value": 5 + } + ], + "duration": { + "Duration": 1 + }, + "application": "PermanentEffectToApply", + "effect_bounds": { + "min": 20, + "max": 90 + } + }, + { + "name": "tax_evasion_scheme", + "description": "A sophisticated tax evasion network siphons off a large portion of city revenue, forcing austerity measures.", + "stats": [ + { + "stat": "Food", + "value": -8 + }, + { + "stat": "Industry", + "value": -7 + }, + { + "stat": "Trade", + "value": -9 + }, + { + "stat": "Crime", + "value": 15 + }, + { + "stat": "Bureaucracy", + "value": -6 + }, + { + "stat": "Population", + "value": -2 + } + ], + "duration": { + "Duration": 6 + }, + "application": "WhenPresent", + "effect_bounds": { + "min": 25, + "max": 95 + } + }, + { + "name": "currency_devaluation", + "description": "The city's coinage is devalued by a sudden policy shift, causing imported goods to skyrocket in price.", + "stats": [ + { + "stat": "Food", + "value": -8 + }, + { + "stat": "Industry", + "value": -3 + }, + { + "stat": "Trade", + "value": -9 + }, + { + "stat": "Health", + "value": -4 + } + ], + "duration": { + "Duration": 1 + }, + "application": "PermanentEffectToApply", + "effect_bounds": { + "min": 23, + "max": 95 + } + }, + { + "name": "artisan_fair_success", + "description": "A grand artisan fair attracts wealthy patrons, boosting local crafts and increasing export revenues.", + "stats": [ + { + "stat": "Industry", + "value": 8 + }, + { + "stat": "Industry", + "value": 9 + }, + { + "stat": "Trade", + "value": 9 + }, + { + "stat": "Population", + "value": 2 + } + ], + "duration": { + "Duration": 1 + }, + "application": "PermanentEffectToApply", + "effect_bounds": { + "min": 23, + "max": 95 + } + }, + { + "name": "resource_piracy", + "description": "Sea‑borne raiders seize a shipment of precious stones destined for the city, flooding the market with counterfeit goods.", + "stats": [ + { + "stat": "Trade", + "value": -12 + }, + { + "stat": "Food", + "value": -7 + }, + { + "stat": "Industry", + "value": -6 + }, + { + "stat": "Threat", + "value": 3 + }, + { + "stat": "Crime", + "value": 14 + } + ], + "duration": { + "Duration": 4 + }, + "application": "WhenPresent", + "effect_bounds": { + "min": 25, + "max": 95 + } + }, + { + "name": "steel_furnace_overheat", + "description": "A critical failure in the city's primary steel furnace sparks an uncontrollable fire, destroying production lines.", + "stats": [ + { + "stat": "Industry", + "value": -17 + }, + { + "stat": "Trade", + "value": -9 + }, + { + "stat": "Happiness", + "value": -2 + }, + { + "stat": "Population", + "value": -3 + } + ], + "duration": { + "Duration": 1 + }, + "application": "PermanentEffectToApply", + "effect_bounds": { + "min": 24, + "max": 95 + } + }, + { + "name": "artisan_tech_innovation", + "description": "A guild of master craftsmen invents a new forging technique that doubles output and lowers raw material usage.", + "stats": [ + { + "stat": "Industry", + "value": 14 + }, + { + "stat": "Industry", + "value": 13 + }, + { + "stat": "Science", + "value": 15 + }, + { + "stat": "Trade", + "value": 9 + }, + { + "stat": "Crime", + "value": 3 + } + ], + "duration": { + "Duration": 1 + }, + "application": "PermanentEffectToApply", + "effect_bounds": { + "min": 26, + "max": 95 + } + }, + { + "name": "coal_mine_sabotage", + "description": "Covert saboteurs collapse a major coal shaft, halting fuel supply to all local factories for weeks.", + "stats": [ + { + "stat": "Industry", + "value": -15 + }, + { + "stat": "Crime", + "value": 6 + } + ], + "duration": { + "Duration": 1 + }, + "application": "PermanentEffectToApply", + "effect_bounds": { + "min": 23, + "max": 95 + } + }, + { + "name": "foreign_factory_purchase", + "description": "A foreign conglomerate purchases the city's largest textile mill, imposing new quotas that reduce local employment.", + "stats": [ + { + "stat": "Industry", + "value": -9 + }, + { + "stat": "Population", + "value": -4 + } + ], + "duration": { + "Duration": 1 + }, + "application": "PermanentEffectToApply", + "effect_bounds": { + "min": 22, + "max": 95 + } + }, + { + "name": "blacksmiths_rebel", + "description": "Skilled blacksmiths organize a strike demanding better wages, halting the production of critical weapons.", + "stats": [ + { + "stat": "Industry", + "value": -10 + }, + { + "stat": "Strength", + "value": -5 + }, + { + "stat": "Crime", + "value": 4 + } + ], + "duration": { + "Duration": 6 + }, + "application": "WhenPresent", + "effect_bounds": { + "min": 22, + "max": 95 + } + }, + { + "name": "machine_revolution", + "description": "The introduction of automated presses in the leather works cuts labor costs but renders many artisans obsolete.", + "stats": [ + { + "stat": "Industry", + "value": 11 + }, + { + "stat": "Population", + "value": -5 + }, + { + "stat": "Crime", + "value": 3 + } + ], + "duration": { + "Duration": 1 + }, + "application": "PermanentEffectToApply", + "effect_bounds": { + "min": 22, + "max": 95 + } + }, + { + "name": "bottleneck_transportation", + "description": "The city's main mean of transportation is seized by gangsters, disrupting the flow of raw materials to factories.", + "stats": [ + { + "stat": "Transportation", + "value": -8 + }, + { + "stat": "Industry", + "value": -6 + }, + { + "stat": "Crime", + "value": 7 + } + ], + "duration": { + "Duration": 3 + }, + "application": "WhenPresent", + "effect_bounds": { + "min": 23, + "max": 95 + } + }, + { + "name": "export_tariff_relief", + "description": "An unexpected removal of export tariffs on metal goods opens new markets, boosting production rates.", + "stats": [ + { + "stat": "Industry", + "value": 12 + }, + { + "stat": "Trade", + "value": 9 + } + ], + "duration": { + "Duration": 1 + }, + "application": "PermanentEffectToApply", + "effect_bounds": { + "min": 23, + "max": 95 + } + }, + { + "name": "smelter_piracy", + "description": "A band of raiders captures a shipment of precious ores destined for the city, flooding the market with cheap counterfeit.", + "stats": [ + { + "stat": "Industry", + "value": -11 + }, + { + "stat": "Trade", + "value": -7 + }, + { + "stat": "Crime", + "value": 10 + } + ], + "duration": { + "Duration": 4 + }, + "application": "WhenPresent", + "effect_bounds": { + "min": 23, + "max": 95 + } + }, + { + "name": "frontline_betrayal", + "description": "A key vanguard commander secretly defects, scattering a significant portion of the army and boosting enemy threat.", + "stats": [ + { + "stat": "Strength", + "value": -6 + }, + { + "stat": "Threat", + "value": 11 + } + ], + "duration": { + "Duration": 1 + }, + "application": "PermanentEffectToApply", + "effect_bounds": { + "min": 22, + "max": 95 + } + }, + { + "name": "naval_battle_victory", + "description": "The city's navy defeats a hostile threat, securing coastal trade routes and striking a blow to the enemy's threat level.", + "stats": [ + { + "stat": "Strength", + "value": 12 + }, + { + "stat": "Threat", + "value": -9 + } + ], + "duration": { + "Duration": 1 + }, + "application": "PermanentEffectToApply", + "effect_bounds": { + "min": 23, + "max": 95 + } + }, + { + "name": "disease_in_soldiers", + "description": "A virulent pestilence breaks out among the ranks, lowering army numbers and damaging overall health.", + "stats": [ + { + "stat": "Army", + "value": -14 + }, + { + "stat": "Health", + "value": -10 + }, + { + "stat": "Strength", + "value": -5 + } + ], + "duration": { + "Duration": 1 + }, + "application": "PermanentEffectToApply", + "effect_bounds": { + "min": 23, + "max": 95 + } + }, + { + "name": "recruitment_panic", + "description": "A surge of conscripts floods the army, but poor training causes a sharp drop in combat effectiveness.", + "stats": [ + { + "stat": "Army", + "value": 8 + }, + { + "stat": "Strength", + "value": -9 + }, + { + "stat": "Threat", + "value": 3 + } + ], + "duration": { + "Duration": 1 + }, + "application": "PermanentEffectToApply", + "effect_bounds": { + "min": 23, + "max": 95 + } + }, + { + "name": "training_expedition", + "description": "A focused military academy expedition hones the troops' skills, raising overall strength at the cost of a temporary manpower drain.", + "stats": [ + { + "stat": "Strength", + "value": 11 + }, + { + "stat": "Army", + "value": -6 + }, + { + "stat": "Threat", + "value": -5 + } + ], + "duration": { + "Duration": 1 + }, + "application": "PermanentEffectToApply", + "effect_bounds": { + "min": 23, + "max": 95 + } + }, + { + "name": "spy_operation_success", + "description": "A covert spy network uncovers threats around, reducing the threat level and providing a tactical advantage.", + "stats": [ + { + "stat": "Threat", + "value": -10 + }, + { + "stat": "Influence", + "value": 3 + }, + { + "stat": "Strength", + "value": 4 + } + ], + "duration": { + "Duration": 1 + }, + "application": "PermanentEffectToApply", + "effect_bounds": { + "min": 23, + "max": 95 + } + }, + { + "name": "war_taxes_harsh", + "description": "The council imposes severe war taxes to fund the army, inflating military budgets but cracking public happiness.", + "stats": [ + { + "stat": "Strength", + "value": 9 + }, + { + "stat": "Happiness", + "value": -8 + }, + { + "stat": "Food", + "value": -3 + }, + { + "stat": "Industry", + "value": -3 + }, + { + "stat": "Science", + "value": -3 + }, + { + "stat": "Trade", + "value": -3 + } + ], + "duration": { + "Duration": 1 + }, + "application": "PermanentEffectToApply", + "effect_bounds": { + "min": 23, + "max": 95 + } + }, + { + "name": "battlefield_innovation", + "description": "A revolutionary tactic is adopted on the front lines, dramatically boosting army strength and lowering enemy threat.", + "stats": [ + { + "stat": "Strength", + "value": 13 + }, + { + "stat": "Threat", + "value": -8 + } + ], + "duration": { + "Duration": 1 + }, + "application": "PermanentEffectToApply", + "effect_bounds": { + "min": 23, + "max": 95 + } + }, + { + "name": "trade_agreement", + "description": "The city brokered a favorable trade pact with a neighboring realm, opening new markets for local goods.", + "stats": [ + { + "stat": "Trade", + "value": 12 + }, + { + "stat": "Food", + "value": 3 + }, + { + "stat": "Industry", + "value": 3 + }, + { + "stat": "Science", + "value": 3 + }, + { + "stat": "Trade", + "value": 3 + }, + { + "stat": "Population", + "value": 3 + } + ], + "duration": { + "Duration": 1 + }, + "application": "PermanentEffectToApply", + "effect_bounds": { + "min": 23, + "max": 95 + } + }, + { + "name": "peace_council", + "description": "A diplomatic summit ends a long-standing border conflict, reducing threat levels and fostering cultural exchange.", + "stats": [ + { + "stat": "Trade", + "value": 10 + }, + { + "stat": "Culture", + "value": 7 + }, + { + "stat": "Happiness", + "value": 5 + } + ], + "duration": { + "Duration": 1 + }, + "application": "PermanentEffectToApply", + "effect_bounds": { + "min": 22, + "max": 95 + } + }, + { + "name": "bounty_hunt_success", + "description": "A coordinated hunt eliminates a notorious calamity, restoring safety to nearby villages.", + "stats": [ + { + "stat": "Crime", + "value": -12 + }, + { + "stat": "Threat", + "value": -8 + }, + { + "stat": "Happiness", + "value": 4 + } + ], + "duration": { + "Duration": 1 + }, + "application": "PermanentEffectToApply", + "effect_bounds": { + "min": 23, + "max": 95 + } + }, + { + "name": "technological_breakthrough", + "description": "Inventors in the city unveiled new technologies with huge applications in the industrial field.", + "stats": [ + { + "stat": "Science", + "value": 15 + }, + { + "stat": "Industry", + "value": 6 + }, + { + "stat": "Food", + "value": 3 + }, + { + "stat": "Trade", + "value": 3 + } + ], + "duration": { + "Duration": 1 + }, + "application": "PermanentEffectToApply", + "effect_bounds": { + "min": 21, + "max": 95 + } + }, + { + "name": "festival_of_luxury", + "description": "A grand festival draws wealthy merchants and foreign dignitaries, boosting tourism and local pride.", + "stats": [ + { + "stat": "Tourism", + "value": 13 + }, + { + "stat": "Science", + "value": 3 + }, + { + "stat": "Trade", + "value": 3 + }, + { + "stat": "Culture", + "value": 3 + }, + { + "stat": "Influence", + "value": 3 + }, + { + "stat": "Happiness", + "value": 6 + } + ], + "duration": { + "Duration": 1 + }, + "application": "PermanentEffectToApply", + "effect_bounds": { + "min": 22, + "max": 95 + } + }, + { + "name": "military_training_expedition", + "description": "An intensive training expedition sharpens the army's tactics, increasing overall strength without cost.", + "stats": [ + { + "stat": "Strength", + "value": 12 + }, + { + "stat": "Army", + "value": 3 + }, + { + "stat": "Threat", + "value": -5 + } + ], + "duration": { + "Duration": 1 + }, + "application": "PermanentEffectToApply", + "effect_bounds": { + "min": 21, + "max": 95 + } + }, + { + "name": "health_initiative", + "description": "A citywide vaccination campaign eradicates a deadly plague, dramatically improving public health.", + "stats": [ + { + "stat": "Health", + "value": 16 + }, + { + "stat": "Population", + "value": 4 + }, + { + "stat": "Happiness", + "value": 5 + } + ], + "duration": { + "Duration": 1 + }, + "application": "PermanentEffectToApply", + "effect_bounds": { + "min": 23, + "max": 95 + } + }, + { + "name": "artisan_summit", + "description": "A gathering of master artisans leads to the sharing of techniques that double production efficiency.", + "stats": [ + { + "stat": "Industry", + "value": 14 + }, + { + "stat": "Science", + "value": 8 + }, + { + "stat": "Trade", + "value": 3 + }, + { + "stat": "Population", + "value": 2 + } + ], + "duration": { + "Duration": 1 + }, + "application": "PermanentEffectToApply", + "effect_bounds": { + "min": 21, + "max": 95 + } + }, + { + "name": "infrastructure_repair", + "description": "A massive repair drive restores crumbling roads and bridges, slashing travel time and boosting trade.", + "stats": [ + { + "stat": "Sprawl", + "value": 10 + }, + { + "stat": "Transportation", + "value": 9 + }, + { + "stat": "Health", + "value": 7 + }, + { + "stat": "Industry", + "value": 7 + }, + { + "stat": "Trade", + "value": 7 + }, + { + "stat": "Food", + "value": 5 + }, + { + "stat": "Trade", + "value": 4 + } + ], + "duration": { + "Duration": 1 + }, + "application": "PermanentEffectToApply", + "effect_bounds": { + "min": 24, + "max": 95 + } + }, + { + "name": "cultural_exposition", + "description": "The city hosts an international exposition, showcasing its heritage and attracting scholars and tourists alike.", + "stats": [ + { + "stat": "Culture", + "value": 12 + }, + { + "stat": "Tourism", + "value": 10 + }, + { + "stat": "Happiness", + "value": 4 + }, + { + "stat": "Influence", + "value": 4 + } + ], + "duration": { + "Duration": 1 + }, + "application": "PermanentEffectToApply", + "effect_bounds": { + "min": 23, + "max": 95 + } + }, + { + "name": "great_earthquake", + "description": "A massive quake rips through the city, shattering buildings, collapsing bridges, and killing thousands.", + "stats": [ + { + "stat": "Health", + "value": -19 + }, + { + "stat": "Population", + "value": -18 + }, + { + "stat": "Happiness", + "value": -15 + } + ], + "duration": { + "Duration": 1 + }, + "application": "PermanentEffectToApply", + "effect_bounds": { + "min": 26, + "max": 95 + } + }, + { + "name": "plague_of_scorpion", + "description": "A deadly disease spreads through the populace, turning citizens into venom‑infused monsters.", + "stats": [ + { + "stat": "Health", + "value": -14 + }, + { + "stat": "Population", + "value": -10 + }, + { + "stat": "Crime", + "value": 8 + } + ], + "duration": { + "Duration": 14 + }, + "application": "WhenPresent", + "effect_bounds": { + "min": 23, + "max": 95 + } + }, + { + "name": "oil_fire_in_barnyard", + "description": "An oil storage depot explodes, sending a wave of fire over the city that reduces the army's morale and strength.", + "stats": [ + { + "stat": "Industry", + "value": -9 + }, + { + "stat": "Happiness", + "value": -4 + }, + { + "stat": "Threat", + "value": 10 + } + ], + "duration": { + "Duration": 1 + }, + "application": "PermanentEffectToApply", + "effect_bounds": { + "min": 22, + "max": 95 + } + }, + { + "name": "fire_of_sacred_temple", + "description": "The city's most revered temple is consumed by a supernatural inferno, spilling holy ash into the streets and igniting widespread panic.", + "stats": [ + { + "stat": "Culture", + "value": -15 + }, + { + "stat": "Threat", + "value": 12 + }, + { + "stat": "Happiness", + "value": -6 + } + ], + "duration": { + "Duration": 1 + }, + "application": "PermanentEffectToApply", + "effect_bounds": { + "min": 24, + "max": 95 + } + }, + { + "name": "cursed_great_flood", + "description": "An unseasonal deluge swallows the city, flooding every district, destroying crops, and causing widespread disease.", + "stats": [ + { + "stat": "Food", + "value": -13 + }, + { + "stat": "Industry", + "value": -6 + }, + { + "stat": "Trade", + "value": -8 + }, + { + "stat": "Threat", + "value": 13 + } + ], + "duration": { + "Duration": 1 + }, + "application": "PermanentEffectToApply", + "effect_bounds": { + "min": 25, + "max": 95 + } + }, + { + "name": "massive_barricade_breach", + "description": "A minor calamity overpowers the city's fortifications, unleashing a wave of slaughter and chaos.", + "stats": [ + { + "stat": "Fortification", + "value": -19 + }, + { + "stat": "Threat", + "value": 19 + }, + { + "stat": "Happiness", + "value": -12 + } + ], + "duration": { + "Duration": 1 + }, + "application": "PermanentEffectToApply", + "effect_bounds": { + "min": 24, + "max": 95 + } + }, + { + "name": "invasion_of_the_undead", + "description": "A horde of reanimated civilians under the influence of a calamity attack citizens and military alike.", + "stats": [ + { + "stat": "Threat", + "value": 14 + }, + { + "stat": "Crime", + "value": -10 + }, + { + "stat": "Population", + "value": -12 + } + ], + "duration": { + "Duration": 5 + }, + "application": "WhenPresent", + "effect_bounds": { + "min": 23, + "max": 95 + } + } + ] +} \ No newline at end of file -- 2.45.1 From 417da3d6174c269ec44cb6f04a9f993558e21f41 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sun, 7 Dec 2025 15:23:28 +0100 Subject: [PATCH 21/22] Generate skeleton --- bin_efo/src/commands.rs | 1 + bin_efo/src/commands/generate.rs | 18 ++++++++++++++++++ bin_efo/src/commands/show.rs | 2 +- bin_efo/src/main.rs | 7 +++++-- lib_efo/src/error.rs | 11 +++++++++++ lib_efo/src/naming.rs | 18 ++++++++++++------ 6 files changed, 48 insertions(+), 9 deletions(-) create mode 100644 bin_efo/src/commands/generate.rs diff --git a/bin_efo/src/commands.rs b/bin_efo/src/commands.rs index 1e8a1e0..83357b0 100644 --- a/bin_efo/src/commands.rs +++ b/bin_efo/src/commands.rs @@ -9,6 +9,7 @@ #![warn(missing_docs, clippy::missing_docs_in_private_items)] pub mod epoch; +pub mod generate; pub mod init; pub mod show; // pub mod diff; diff --git a/bin_efo/src/commands/generate.rs b/bin_efo/src/commands/generate.rs new file mode 100644 index 0000000..c878639 --- /dev/null +++ b/bin_efo/src/commands/generate.rs @@ -0,0 +1,18 @@ +//! Subcommand for fast generating ideas and displaying them +//! This module does not add any structure (that would be either the prerogative of the bulk generator or the individual modules) + +use clap::Subcommand; + +use crate::error::AppError; +/// The types of examples to generate +#[derive(Subcommand, Debug)] +pub enum GenCmd { + /// Generate a character + Character, +} + +/// Handle all the generation +pub fn gen_handler(cmd: &GenCmd) -> Result<(), AppError> { + let _ = cmd; + Ok(()) +} diff --git a/bin_efo/src/commands/show.rs b/bin_efo/src/commands/show.rs index b00fd59..39575d0 100644 --- a/bin_efo/src/commands/show.rs +++ b/bin_efo/src/commands/show.rs @@ -1,5 +1,5 @@ //! The show commands -//! +//! Used to display structures with various degree of verbosity use clap::Subcommand; use lib_efo::{Displayable, entity::Entity, naming::NAMING}; diff --git a/bin_efo/src/main.rs b/bin_efo/src/main.rs index 966fdca..e86fc23 100644 --- a/bin_efo/src/main.rs +++ b/bin_efo/src/main.rs @@ -28,7 +28,7 @@ use std::fmt::Debug; use clap::{ArgAction, Parser, Subcommand}; use crate::{ - commands::{epoch::cli_epoch::EpochCmd, init::InitCmd, show::ShowCmd}, + commands::{epoch::cli_epoch::EpochCmd, generate::GenCmd, init::InitCmd, show::ShowCmd}, error::AppError, }; mod commands; @@ -71,6 +71,9 @@ enum TopLevelCmd { // Chr(commands::chr::ChrCmd), // Town(commands::town::TownCmd), // Link(commands::link::LinkCmd), + #[command(subcommand)] + /// Generate random structures and display them + Gen(GenCmd), } /// Program entry point. @@ -78,7 +81,6 @@ enum TopLevelCmd { /// Parses the command-line arguments and dispatches to the selected /// sub-command. Errors returned by the sub-command handlers are shown /// in stdout and returned as a `miette::Result<()>`. -#[allow(clippy::unwrap_used)] fn main() -> miette::Result<()> { env_logger::init(); @@ -109,5 +111,6 @@ fn exec_dispatch(cli: Cli) -> Result<(), AppError> { TopLevelCmd::Init(cmd) => commands::init::init(&cmd), TopLevelCmd::Epoch(cmd) => commands::epoch::handle_cmd(&cmd), TopLevelCmd::Show(cmd) => commands::show::handle_show_cmd(&cmd), + TopLevelCmd::Gen(cmd) => commands::generate::gen_handler(&cmd), } } diff --git a/lib_efo/src/error.rs b/lib_efo/src/error.rs index 6c3a287..b97ce4c 100644 --- a/lib_efo/src/error.rs +++ b/lib_efo/src/error.rs @@ -217,6 +217,17 @@ pub enum EpochError { #[error("An user facing error")] #[diagnostic(code(EpochError::UserError))] UserError(#[help] UserErrors), + + /// An error happened when picking a rng event + #[error("An error happened when trying to pick a rng event for {cause}")] + #[diagnostic(code(EpochError::RNGPickError))] + RNGPickError { + /// The root cause originating the error + cause: String, + #[help] + /// Optionnal help + help: Option, + }, } /// A small enum of explicit user-facing error messages. diff --git a/lib_efo/src/naming.rs b/lib_efo/src/naming.rs index e382255..6ff4d3b 100644 --- a/lib_efo/src/naming.rs +++ b/lib_efo/src/naming.rs @@ -10,6 +10,7 @@ use std::path::{Path, PathBuf}; use crate::entity::EffectApplication; use crate::entity::EffectBounds; use crate::entity::EntityDuration; +use crate::error::EpochError; use crate::stats::StatPair; /// The structure that holds everything we need for name generation. @@ -86,9 +87,9 @@ impl NamingData { pub fn generate_character_name(&self) -> String { let mut rng = rand::rng(); - let binding = "Unnamed".into(); + let binding = "Bobman".into(); let first = self.first_names.choose(&mut rng).unwrap_or(&binding); - let binding = "".into(); + let binding = "McBobintown".into(); let last = self.last_names.choose(&mut rng).unwrap_or(&binding); format!("{} {}", first, last).trim().to_string() } @@ -96,17 +97,22 @@ impl NamingData { /// Generate a random **town** name. pub fn generate_town_name(&self) -> String { let mut rng = rand::rng(); - let binding = "".into(); + let binding = "Bobtown".into(); let prefix = self.town_prefixes.choose(&mut rng).unwrap_or(&binding); let suffix = self.town_suffixes.choose(&mut rng).unwrap_or(&binding); format!("{}{}", prefix, suffix).trim().to_string() } - /// Pick a random event idea (you can reuse this or make a dedicated method). + /// Pick a random event idea #[allow(clippy::unwrap_used)] - pub fn random_event_idea(&self) -> &EventDescription { + pub fn random_event_idea(&self) -> Result<&EventDescription, EpochError> { let mut rng = rand::rng(); - self.event_ideas.choose(&mut rng).unwrap() + self.event_ideas + .choose(&mut rng) + .ok_or(EpochError::RNGPickError { + cause: "Picking a random event".into(), + help: None, + }) } /// Generates something like: -- 2.45.1 From d34d89353d15db85874560b37e4bbd00fb17dec6 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sun, 7 Dec 2025 15:44:00 +0100 Subject: [PATCH 22/22] Purged Mark of AI --- Jenkinsfile | 2 +- config.toml | 7 ++++++ lib_efo/naming.json | 6 ++--- lib_efo/src/entity.rs | 32 +++++++++++++-------------- lib_efo/src/entity/implementations.rs | 8 +++---- lib_efo/src/lib.rs | 18 +++++++-------- 6 files changed, 40 insertions(+), 33 deletions(-) create mode 100644 config.toml diff --git a/Jenkinsfile b/Jenkinsfile index f9e155d..91b40e0 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -29,7 +29,7 @@ pipeline { } else if (env.BRANCH_NAME == 'origin/master' || env.BRANCH_NAME == 'master') { sh 'cargo test' } else { - echo "Unknown branch: ${env.BRANCH_NAME} — skipping build." + echo "Unknown branch: ${env.BRANCH_NAME} - skipping build." } } } diff --git a/config.toml b/config.toml new file mode 100644 index 0000000..ee4de04 --- /dev/null +++ b/config.toml @@ -0,0 +1,7 @@ +[[patterns]] +regex = "\\p{Pd}" +replacement = "-" +[[patterns]] +regex = "[\u2018\u2019\u201A\u201B\u02BC\u02BB\u00B4\uFF40\uFF07]" +replacement = "'" + diff --git a/lib_efo/naming.json b/lib_efo/naming.json index e52ffc5..2bc4de8 100644 --- a/lib_efo/naming.json +++ b/lib_efo/naming.json @@ -608,7 +608,7 @@ }, { "name": "city_corruption_scandal", - "description": "A high‑ranking magistrate is discovered embezzling city funds, sparking public outrage and a demand for accountability.", + "description": "A high-ranking magistrate is discovered embezzling city funds, sparking public outrage and a demand for accountability.", "stats": [ { "stat": "Food", "value": -4 }, { "stat": "Industry", "value": -3 }, @@ -877,7 +877,7 @@ }, { "name": "resource_piracy", - "description": "Sea‑borne raiders seize a shipment of precious stones destined for the city, flooding the market with counterfeit goods.", + "description": "Sea-borne raiders seize a shipment of precious stones destined for the city, flooding the market with counterfeit goods.", "stats": [ { "stat": "Trade", "value": -12 }, { "stat": "Food", "value": -7 }, @@ -1269,7 +1269,7 @@ }, { "name": "plague_of_scorpion", - "description": "A deadly disease spreads through the populace, turning citizens into venom‑infused monsters.", + "description": "A deadly disease spreads through the populace, turning citizens into venom-infused monsters.", "stats": [ { "stat": "Health", "value": -14 }, { "stat": "Population", "value": -10 }, diff --git a/lib_efo/src/entity.rs b/lib_efo/src/entity.rs index 93bc703..6b46781 100644 --- a/lib_efo/src/entity.rs +++ b/lib_efo/src/entity.rs @@ -6,8 +6,8 @@ //! //! 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 +//! 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 serde::{Deserialize, Serialize}; @@ -17,35 +17,35 @@ pub mod implementations; /// An entity that can be present in the game world. /// -/// Entities are mutable only through the entity system’s public API. +/// 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, - /// Runtime statistics that determine the entity’s behaviour. + /// 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). + /// 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. + /// beyond the entity's lifetime. temp_stats: OverallStats, - /// Non‑statistical metadata such as name, rarity, and faction. + /// Non-statistical metadata such as name, rarity, and faction. /// - /// This information is not directly part of the entity’s combat + /// 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 + /// terrain, etc. It will be phased out in favor of a trait-based /// system for greater type safety. entity_type: EntityType, @@ -61,7 +61,7 @@ pub struct Entity { /// persists after the entity is removed. effect_nature: EffectApplication, - /// Limits that clamp any stat changes caused by the entity’s effect. + /// Limits that clamp any stat changes caused by the entity's effect. effect_bounds: EffectBounds, } @@ -76,15 +76,15 @@ pub struct EffectBounds { pub min: usize, pub max: usize, } -/// How the entity’s effect is applied over time. +/// 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. /// Use with caution, as this can produce catastrophic results - /// (e.g., an ever‑erupting terrain). + /// (e.g., an ever-erupting terrain). Recurring, - /// Modifies the attached entity’s stats only while present. + /// Modifies the attached entity's stats only while present. /// Removed when the entity is removed. Common for leaders, /// temporary events, or terrain. WhenPresent, @@ -95,7 +95,7 @@ pub enum EffectApplication { PermanentEffectToApply, /// Indicates that a permanent effect has already been applied. - /// Useful for bookkeeping when a long‑lasting event applies + /// Useful for bookkeeping when a long-lasting event applies /// its effect only once. PermanentEffectApplied, } @@ -111,8 +111,8 @@ pub enum EntityDuration { /// `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 + /// 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, diff --git a/lib_efo/src/entity/implementations.rs b/lib_efo/src/entity/implementations.rs index 4362a70..67f67d7 100644 --- a/lib_efo/src/entity/implementations.rs +++ b/lib_efo/src/entity/implementations.rs @@ -1,6 +1,6 @@ //! Implementation of all needed traits for the Entity struct use cli_table::{Style, WithTitle, print_stdout}; -use colored::*; // [3] – colored‑rs examples +use colored::*; // [3] - colored-rs examples use crate::Displayable; use crate::entity::Entity; @@ -8,7 +8,7 @@ use crate::stats::Symbols; // ---------- Implementation ---------- impl Displayable for Entity { - // Detailed multi‑line view (used e.g. in logs) + // Detailed multi-line view (used e.g. in logs) fn print_full(&self) { println!( "{:?}\n{}", @@ -32,13 +32,13 @@ impl Displayable for Entity { print_stdout(vec![&self.stats, &self.temp_stats].with_title().bold(true)).expect(""); } - // Short, single‑line representation + // Short, single-line representation fn print_short(&self) { println!("{}", self.to_pretty_tree()); print_stdout(vec![&self.stats].with_title().bold(true)).expect("") } - /// One‑liner used for auto‑generation of Vec displays + /// One-liner used for auto-generation of Vec displays fn oneline_display(&self) -> String { let capital = self .metadata diff --git a/lib_efo/src/lib.rs b/lib_efo/src/lib.rs index b1b10ff..ce4cbdc 100644 --- a/lib_efo/src/lib.rs +++ b/lib_efo/src/lib.rs @@ -55,12 +55,12 @@ where /// List all ids known to this store. fn list_ids(&self) -> IoResult>; } -/// A trait for types that can be displayed in a command‑line tool. +/// A trait for types that can be displayed in a command-line tool. /// /// Implementors should provide three levels of representation: -/// 1. **Full** – a detailed view suitable for a long‑running command. -/// 2. **Short** – a concise, user‑friendly view that fits on a single line. -/// 3. **Oneline** – a compact, machine‑friendly string that can be embedded +/// 1. **Full** - a detailed view suitable for a long-running command. +/// 2. **Short** - a concise, user-friendly view that fits on a single line. +/// 3. **Oneline** - a compact, machine-friendly string that can be embedded /// inside a `Vec` representation. /// /// ## `Vec` support @@ -69,15 +69,15 @@ where /// This allows you to call `full_display`, `short_display` or `oneline_display` /// directly on a vector of displayable items. pub trait Displayable { - /// Return a fully‑described string representation. + /// Return a fully-described string representation. fn print_full(&self); - /// Return a short, user‑friendly string. + /// Return a short, user-friendly string. fn print_short(&self); - /// Return a one‑liner string, suitable for embedding in a collection + /// Return a one-liner string, suitable for embedding in a collection /// representation (e.g. a `Vec`). Implementations should avoid - /// new‑lines to keep the output usable in a single line context. + /// new-lines to keep the output usable in a single line context. fn oneline_display(&self) -> String; /// Print oneline @@ -102,7 +102,7 @@ impl Displayable for Vec { } fn oneline_display(&self) -> String { - // No brackets – just a flat, comma‑separated list. + // No brackets - just a flat, comma-separated list. self.iter() .map(|x| x.oneline_display()) .collect::>() -- 2.45.1