diff --git a/.gitmodules b/.gitmodules index 644abda..4fb3f36 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,3 +1,4 @@ [submodule "ravenous_databases"] path = ravenous_databases - url = git@git.dandaedre.com:Ravenous/ravenous_databases.git + # url = git@git.dandaedre.com:Ravenous/ravenous_databases.git + url = https://proxy.dandaedre.com/gitea/Ravenous/ravenous-tools.git diff --git a/Cargo.toml b/Cargo.toml index a79e6ec..44dfdae 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -41,6 +41,7 @@ fast_class = {path = "./crates/fast_class"} formatter = {path = "./crates/formatter"} weaponry = {path = "./crates/weaponry"} more_fields = {path = "./crates/more_fields"} +monsters = {path = "./crates/monsters"} anyhow = "1.0.103" toml = "1.1.3" @@ -55,3 +56,4 @@ glob = "0.3.3" tokio = { version = "1.52.3", features = ["full"] } dynfmt = { version = "0.1.5", features = ["curly"] } pretty_assertions = "^1.4" +indexmap = "2.14.0" diff --git a/crates/cli_parser/src/lib.rs b/crates/cli_parser/src/lib.rs index 1fd3ad2..60266c7 100644 --- a/crates/cli_parser/src/lib.rs +++ b/crates/cli_parser/src/lib.rs @@ -8,7 +8,8 @@ use config::{ fast_tables::FastTableConfig, formatter::FormatterConfig, graph::GraphConfig, - make::{MakeTargets, VerboseLevel, HELP_BLOCK_SELECTION}, + make::{HELP_BLOCK_SELECTION, MakeTargets, VerboseLevel}, + monsters::{MonsterConfig, MonsterMarkup}, statsolver::StatConfig, tablegen::{Craft, TableArgs}, }; @@ -48,6 +49,8 @@ pub enum Commands { Analysis(AnalysisConfig), /// Better Generation BetterGen(FastTableConfig), + /// Monster database handling + Monsters(MonsterConfig), } #[derive(Debug, Args)] @@ -74,6 +77,8 @@ pub struct Config { pub classes: Classes, /// Config for all the tables pub craft: Craft, + /// Config for monster exporting + pub monster: MonsterMarkup, } #[derive(Deserialize)] diff --git a/crates/config/Cargo.toml b/crates/config/Cargo.toml index 8cfcc65..95e276a 100644 --- a/crates/config/Cargo.toml +++ b/crates/config/Cargo.toml @@ -7,3 +7,5 @@ edition = "2024" clap = {workspace = true} serde = {workspace = true} phf = {workspace = true} +indexmap = {workspace = true} +anyhow = {workspace = true} diff --git a/crates/config/src/lib.rs b/crates/config/src/lib.rs index e6b05c2..58c5607 100644 --- a/crates/config/src/lib.rs +++ b/crates/config/src/lib.rs @@ -12,5 +12,6 @@ pub mod fast_tables; pub mod formatter; pub mod graph; pub mod make; +pub mod monsters; pub mod statsolver; pub mod tablegen; diff --git a/crates/config/src/monsters.rs b/crates/config/src/monsters.rs new file mode 100644 index 0000000..663c02b --- /dev/null +++ b/crates/config/src/monsters.rs @@ -0,0 +1,152 @@ +// Workspace: config +// File: config/src/monsters.rs +//! The inner config for monster module +//! +#![allow(dead_code)] + +use anyhow::Result; +use clap::{Args, ValueEnum}; +use indexmap::IndexMap; +use serde::{Deserialize, Deserializer}; + +#[derive(Args, Debug, Clone)] +/// The configuration struct for the Graph +pub struct MonsterConfig { + /// Special target + pub target: MonsterTarget, + + /// Database to load from + #[arg(short, long, default_value = "./ravenous_databases/monsters.db")] + pub database: String, + /// Clean all the artefacts (including generated images) + #[arg(short, long)] + pub all: bool, +} + +#[derive(ValueEnum, Debug, Clone)] +/// The action to execute +pub enum MonsterTarget { + /// Clean the generated monsters directory + Clean, + /// Generate the monster list + Export, + /// Show useful data + Show, +} + +/// Configuration data for generating a monster sheet. +/// +/// The values are plain LaTeX fragments stored in the `[monster]` section of a `.toml` +#[allow(dead_code)] +#[derive(Deserialize)] +pub struct MonsterMarkup { + /// Header of the page (image + basic attributes). + pub intro: String, + + /// Body‑parts section header. + pub body_parts_intro: String, + + /// One row of the body‑parts table. + pub body_parts_row: String, + + /// Body‑parts table footer. + pub body_parts_end: String, + + /// Rewards section header (the table that lists each reward). + pub rewards_row: String, + + /// Rewards table footer. + pub rewards_end: String, + + /// Resists section header. + pub resists_intro: String, + + /// The blood reward template. + pub blood_reward: String, + + /// One line of the resistances table. + pub resists_row: String, + + /// Resists table footer. + pub resists_end: String, + + /// Stats section (movement, initiative, etc.). + pub stats: String, + + /// The row of initiatives (turn 2 onwards) + pub init_rows: String, + + /// The end of the initiatives + pub init_end: String, + + /// Header of the attacks section. + pub attacks_intro: String, + + /// Footer of the attacks section. + pub attacks_end: String, + + /// Row used for each attack’s data (IDs, types, damage, etc.). + pub phase_row: String, + + /// The color of the attack row + pub attack_color: String, + + /// Before attack + pub attack_before_repeat: String, + + /// Row that lists repeatable attacks. + pub attack_repeatable_row: String, + + /// Row that contains additional information for an attack. + pub attack_info_row: String, + + /// The intent table & Battle plan + pub intent_table: String, + + /// Color map + #[serde(deserialize_with = "parse_monster_color")] + pub color_table: MonsterColor, + + /// Default color + pub default_color: String, +} + +/// Ghetto color import +pub struct MonsterColor { + /// Inner color + pub inner: IndexMap, +} + +impl std::ops::Deref for MonsterColor { + type Target = IndexMap; + + fn deref(&self) -> &Self::Target { + &self.inner + } +} + +/// Parse the monster colors from a toml +fn parse_monster_color<'de, D>(deserializer: D) -> Result +where + D: Deserializer<'de>, +{ + let color = String::deserialize(deserializer)?; + Ok(MonsterColor { + inner: color + .lines() + .filter_map(|line| { + let line = line.trim(); + if line.is_empty() { + return None; + } + + // Split at the first ':' only. + let mut parts = line.splitn(2, ':'); + let key = parts.next()?.trim().to_string(); + let value = parts.next().map(|v| v.trim()).ok_or(()).ok()?; + + Some((key, value.to_owned())) + }) + .collect(), + }) +} diff --git a/crates/config/src/tablegen.rs b/crates/config/src/tablegen.rs index 7b54be3..6835e7a 100644 --- a/crates/config/src/tablegen.rs +++ b/crates/config/src/tablegen.rs @@ -31,7 +31,7 @@ pub struct TableArgs { pub filenames: Vec, } -// This config is can contain unconstructed code for compatibility purposes +// This config can contain unconstructed code for compatibility purposes #[allow(dead_code)] #[derive(Deserialize)] /// The Craft configs diff --git a/crates/make/Cargo.toml b/crates/make/Cargo.toml index d4a525d..3308b2b 100644 --- a/crates/make/Cargo.toml +++ b/crates/make/Cargo.toml @@ -12,8 +12,8 @@ serde = {workspace = true} toml = {workspace = true} tokio = {workspace = true} dynfmt = {workspace = true} +indexmap = {workspace = true} indicatif = { version = "0.18.6", features = ["rayon"] } logos = "0.16.1" -indexmap = "2.14.0" console = "0.16.4" diff --git a/crates/monsters/Cargo.toml b/crates/monsters/Cargo.toml new file mode 100644 index 0000000..00213a5 --- /dev/null +++ b/crates/monsters/Cargo.toml @@ -0,0 +1,21 @@ +[package] +name = "monsters" +edition = "2024" +version.workspace = true + +[dependencies] +config = {workspace = true} +cli_parser = {workspace = true} +more_fields = {workspace = true} +anyhow = {workspace = true} +indexmap = {workspace = true} +serde = {workspace = true} +rusqlite = { version = "0.40.1" } # , features = ["bundled"] +serde_rusqlite = "0.43.0" +strum = { version = "0.28.0", features = ["derive"] } +handlebars = "6.4.3" + +[dev-dependencies] +regex = {workspace = true} +pretty_assertions = {workspace = true} +clap = {workspace = true} diff --git a/crates/monsters/src/lib.rs b/crates/monsters/src/lib.rs new file mode 100644 index 0000000..21ae410 --- /dev/null +++ b/crates/monsters/src/lib.rs @@ -0,0 +1,43 @@ +//! # Monsters Module +//! +//! The `monsters` crate orchestrates the processing of *ravenous* monster data. +//! +//! It can: +//! * **Parse** raw monster definitions into ergonomic Rust structs. +//! * Perform **balancing** calculations to keep encounters fair. +//! * **Show** concise, human‑readable summaries in the terminal. +//! * **Export** processed data as LaTeX/TeX for printing or further editing. +//! +//! All functionality is exposed through a single entry point: +//! [`monsters_dispatch`]. The dispatcher interprets command‑line arguments +//! (`MonsterConfig`) and delegates to the appropriate sub‑routine (clean, export or show). +//! + +use crate::monster_export::generate_monsters_tex; + +use anyhow::Context; +mod monster_database; +mod monster_export; +pub mod monster_structs; + +use anyhow::Result; +use cli_parser::Config; +use config::monsters::MonsterConfig; +use rusqlite::Connection; + +/// Dispatches the chosen monster action. +pub fn monsters_dispatch(args: &MonsterConfig, config: &Config) -> Result<()> { + // use config::monsters::MonsterTarget; + + let connection = + Connection::open(&args.database).context(format!("Opening database {}", args.database))?; + + generate_monsters_tex(args, config, connection)?; + // templates + // match args.target { + // MonsterTarget::Clean => todo!("implement cleaning logic"), + // MonsterTarget::Export => todo!("implement export logic"), + // MonsterTarget::Show => todo!("implement show logic"), + // } + Ok(()) +} diff --git a/crates/monsters/src/monster_database.rs b/crates/monsters/src/monster_database.rs new file mode 100644 index 0000000..88e3bda --- /dev/null +++ b/crates/monsters/src/monster_database.rs @@ -0,0 +1,122 @@ +#![allow(dead_code)] + +use crate::monster_structs::{self, CreatureReward}; +use crate::monster_structs::{ + CreatureBodyPart, CreatureData, CreatureListAttacks, CreatureStats, FullMonster, + MonsterSingleAttack, +}; +use anyhow::{Context, anyhow}; +use rusqlite::Connection; +use serde::de::DeserializeOwned; + +/// Deserialise a table row (or rows) into the given type and add a nice context message. +macro_rules! fetch_from { + ($ty:ty, $connection:expr,$name:expr, $table:expr, $cols_opt:expr) => {{ + // `connection` and `creature.name` must be in scope when the macro is expanded + generic_deserialize::<$ty>( + &$connection, + $table, + Some(&format!("creature_id={}", $name.id)), + $cols_opt, + ) + .context(format!("Fetching {} from {}", $table, $name.name))? + }}; +} + +pub(crate) fn fetch_all_data(connection: Connection) -> Result, anyhow::Error> { + let list_creatures = + generic_deserialize::(&connection, "creature", None, Some("id"))?; + let mut finished_creatures = Vec::new(); + for creature in list_creatures.iter() { + // println!("Working on {}@{}", creature.id, creature.name); + let creature_attacks = fetch_from!( + MonsterSingleAttack, + connection, + creature, + "creature_abilities", + Some("phase, attack_group") + ); + let creature_resistances = fetch_from!( + CreatureBodyPart, + connection, + creature, + "creature_body_parts", + Some("body_part_name") + ); + + let creature_stats = + fetch_from!(CreatureStats, connection, creature, "creature_stats", None); + if creature_stats.len() != 1 { + return Err(anyhow!( + "The stat line for the creature {} should be exactly one found {}", + creature.name, + creature_stats.len() + )); + }; + let creature_stats = creature_stats.first().unwrap().clone(); + + let creature_rewards = fetch_from!( + CreatureReward, + connection, + creature, + "creature_rewards", + None + ); + finished_creatures.push(FullMonster { + id: creature.id, + name: creature.name.clone(), + stats: creature_stats, + attacks: CreatureListAttacks { + attacks: creature_attacks, + }, + body_parts: monster_structs::CreatureListBodyParts { + body_parts: creature_resistances, + }, + data: creature.clone(), + rewards: monster_structs::CreatureListRewards { + rewards: creature_rewards, + }, + }); + } + Ok(finished_creatures) +} + +/// A generic Deserialisation from a database +fn generic_deserialize( + connection: &Connection, + table_name: &str, + filter: Option<&str>, + sort: Option<&str>, +) -> Result, anyhow::Error> { + let info = format!( + "Querying data on {} with {} WHERE {:?} ORDER BY {:?}", + table_name, + std::any::type_name::(), + filter, + sort, + ); + let generate_select_query = generate_select_query::(table_name, filter, sort); + // println!("{}", generate_select_query); + let mut r = connection.prepare(&generate_select_query).context(info)?; + let rows = r.query([])?; + let r = serde_rusqlite::from_rows::(rows).collect::, serde_rusqlite::Error>>(); + r.context("No") +} + +fn generate_select_query( + table_name: &str, + filter: Option<&str>, + sort: Option<&str>, +) -> String { + format!( + "SELECT {} FROM {}{}{};", + T::attributes_slice() + .iter() + .map(|(k, _v)| k.to_owned()) + .collect::>() + .join(","), + table_name, + filter.map_or_else(String::default, |j| " WHERE ".to_string() + j), + sort.map_or_else(String::default, |j| " ORDER BY ".to_string() + j) + ) +} diff --git a/crates/monsters/src/monster_export.rs b/crates/monsters/src/monster_export.rs new file mode 100644 index 0000000..c1336a0 --- /dev/null +++ b/crates/monsters/src/monster_export.rs @@ -0,0 +1,210 @@ +//! Monster export module + +use anyhow::{Context, Result}; +use cli_parser::Config; +use config::monsters::MonsterConfig; +use handlebars::Handlebars; +use indexmap::IndexMap; +use rusqlite::Connection; +use serde::Serialize; +use std::fmt::Write; + +use crate::{ + monster_database::fetch_all_data, + monster_structs::{ + MonsterAllAttacks, MonsterFullAttack, MonsterRepetableInitRow, MonsterSingleAttack, + }, +}; + +/// Load a template from a struct field into a `templates` collection. +/// +/// $templates – the variable that holds the template collection +/// $cfg_path – any path (e.g. `config`, `self.cfg`, …) that points to a +/// struct containing the field we want +/// $name – the identifier of the field / template name +macro_rules! template_load { + ($templates:ident, $cfg_path:expr, $name:ident) => {{ + $templates + .register_template_string( + stringify!($name), // "intro" + &$cfg_path.$name, // &config.monster.intro + ) + .context(concat!("Registering ", stringify!($name), " template"))? // ? propagates errors + }}; +} + +pub trait ToTex { + fn export_to_tex(self) -> String; +} + +fn load_templates(config: &Config) -> Result> { + let mut templates = Handlebars::new(); + template_load!(templates, &config.monster, intro); + template_load!(templates, &config.monster, body_parts_row); + template_load!(templates, &config.monster, body_parts_end); + template_load!(templates, &config.monster, blood_reward); + template_load!(templates, &config.monster, rewards_row); + template_load!(templates, &config.monster, init_rows); + template_load!(templates, &config.monster, resists_row); + template_load!(templates, &config.monster, stats); + template_load!(templates, &config.monster, phase_row); + template_load!(templates, &config.monster, attack_color); + template_load!(templates, &config.monster, attack_repeatable_row); + template_load!(templates, &config.monster, attack_info_row); + template_load!(templates, &config.monster, intent_table); + Ok(templates) +} + +// TODO: Create a method on the struct instead of this inane bs +/// Export a tex with the given config and arguments +pub fn generate_monsters_tex( + args: &MonsterConfig, + config: &Config, + connection: Connection, +) -> std::result::Result<(), anyhow::Error> { + let all_monsters = fetch_all_data(connection)?; + let templates = load_templates(config)?; + + let mut out = String::new(); + let creature = &all_monsters[0]; + write!(out, "{}", templates.render("intro", &creature.data)?)?; + write!( + out, + "{}", + templates.render("blood_reward", &creature.stats)? + )?; + for reward in creature.rewards.rewards.iter() { + write!(out, "{}", templates.render("rewards_row", reward)?)?; + } + write!(out, "{}", &config.monster.rewards_end)?; + write!(out, "{}", &config.monster.body_parts_intro)?; + for part in creature.body_parts.body_parts.iter() { + write!(out, "{}", templates.render("body_parts_row", part)?)?; + } + write!( + out, + "{}", + templates.render("body_parts_end", &creature.data)? + )?; + // TODO: Maybe add modularity and not print empty resists + write!(out, "{}", &config.monster.resists_intro)?; + for part in creature.body_parts.body_parts.iter() { + write!(out, "{}", templates.render("resists_row", part)?)?; + } + write!(out, "{}", &config.monster.resists_end)?; + write!(out, "{}", &config.monster.stats)?; + write!(out, "{}", templates.render("stats", &creature.stats)?)?; + for init in MonsterRepetableInitRow::vec_from( + &creature.stats.p1_init, + &creature.stats.p2_init, + &creature.stats.p1_actions, + &creature.stats.p2_actions, + ) + .iter() + .skip(1) + { + write!(out, "{}", templates.render("init_rows", init)?)?; + } + + let all_attacks = MonsterAllAttacks::from_retrieved_data(&creature.attacks.attacks); + println!("{:#?}", all_attacks); + all_attacks.to_tex(&templates, config)?; + write!(out, "{}", &config.monster.attacks_intro)?; + + write!(out, "{}", &config.monster.attacks_end)?; + write!(out, "{}", templates.render("intent_table", &creature.data)?)?; + + // println!("{}", out); + Ok(()) +} +impl MonsterAllAttacks { + pub fn from_retrieved_data(original_data: &[MonsterSingleAttack]) -> MonsterAllAttacks { + let mut initial_phases: IndexMap<&String, Vec<&MonsterSingleAttack>> = IndexMap::new(); + let mut phases: IndexMap> = IndexMap::new(); + // Intermediate split with hashmaps + for atk in original_data { + if let Some(values) = initial_phases.get_mut(&atk.phase) { + values.push(atk); + } else { + initial_phases.insert(&atk.phase, vec![atk]); + } + } + for (phase, phase_atks) in initial_phases.iter() { + let mut grouped_attacks: IndexMap<&Option, Vec<&MonsterSingleAttack>> = + IndexMap::new(); + let phase_name = phase.to_string(); + phases.insert(phase_name.clone(), Vec::new()); + for &atk in phase_atks { + if let Some(values) = grouped_attacks.get_mut(&atk.attack_group) { + values.push(atk); + } else { + grouped_attacks.insert(&atk.attack_group, vec![atk]); + } + } + for (group, atk) in grouped_attacks { + if group.is_some() { + let group_attack = MonsterFullAttack { + attacklist: atk.iter().map(|&v| v.clone()).collect(), + color: atk.first().unwrap().short_name.clone(), + description: atk.first().unwrap().effects.clone(), + }; + phases.get_mut(&phase_name).unwrap().push(group_attack); + } else { + for single_atk in atk { + phases + .get_mut(&phase_name) + .unwrap() + .push(MonsterFullAttack { + attacklist: vec![single_atk.clone()], + color: single_atk.short_name.clone(), + description: single_atk.effects.clone(), + }); + } + }; + } + } + Self { phases } + } +} +#[derive(Serialize)] +struct Coloring<'a> { + color: &'a str, +} +impl MonsterAllAttacks { + pub fn to_tex(&self, templates: &Handlebars<'_>, config: &Config) -> Result { + let mut out = String::new(); + for (phase, list_full_attacks) in &self.phases { + // Print phase name + write!(out, "{}", templates.render("phase_row", phase)?)?; + for attack in list_full_attacks { + write!(out, "{}", config.monster.attack_before_repeat)?; + for sub_attack in &attack.attacklist { + let color = Coloring { + color: config + .monster + .color_table + .inner + .get(&attack.color) + .unwrap_or(&config.monster.default_color), + }; + write!(out, "{}", templates.render("attack_color", &color)?)?; + write!( + out, + "{}", + templates.render("attack_repeatable_row", sub_attack)? + )?; + } + + write!( + out, + "{}", + templates.render("attack_info_row", &list_full_attacks[0])? + )?; + } + // Print all attacks in that phase + + println!("{}", out); + } + Ok(out) + } +} diff --git a/crates/monsters/src/monster_structs.rs b/crates/monsters/src/monster_structs.rs new file mode 100644 index 0000000..c3b2f6a --- /dev/null +++ b/crates/monsters/src/monster_structs.rs @@ -0,0 +1,372 @@ +//! # Monster Structures +//! +//! The `monster_structs` module defines the data model that represents a monster +//! as it is loaded from the database. All structs are intentionally kept +//! +//! ## Overview +//! ```text +//! FullMonster → MonsterStats +//! ↘ MonsterAttacks → Vec +//! ↗ MonsterResistances → Vec +//! ``` +//! +#![allow(dead_code)] + +use indexmap::IndexMap; +use more_fields::FieldsAsSlice; +use serde::{Deserialize, Serialize}; + +/// A monster ready for consumption by other modules. +pub struct FullMonster { + /// Unique identifier, derived when the monster is instantiated. + pub id: i64, + + /// Monster’s name. + pub name: String, + + /// Serialized generic data directly copied from the database table. + pub data: CreatureData, + + /// Collection of attacks, wrapped in a helper that exposes useful functions. + pub attacks: CreatureListAttacks, + + /// Collection of resistances, wrapped in a helper for convenient iteration. + pub body_parts: CreatureListBodyParts, + + /// Collection of all the rewards, wraped in a helper for iteration. + pub rewards: CreatureListRewards, + + /// Serialized stats directly copied from the database table. + pub stats: CreatureStats, +} + +/// One row from the `creature` table. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, FieldsAsSlice)] +pub struct CreatureData { + /// Primary key – auto‑incremented by SQLite. + #[INTEGER] + pub id: i64, // INTEGER primary key + /// Text columns – stored as plain UTF‑8 text in SQLite. + #[TEXT] + pub name: String, + /// The calamity type of the creature + #[TEXT] + pub calamity: String, + /// The image describing the creature + #[TEXT] + pub image: String, + /// The HSE danger level + #[INTEGER] + pub danger_level: i64, + /// Type of habitat + #[TEXT] + pub habitat: String, + /// Wether a dismorphism exists + #[TEXT] + pub dysmorphism: String, + /// Generic color describing the creature + #[TEXT] + pub colors: String, + /// Default reaction to human presence + #[TEXT] + pub default_human_reaction: String, + /// Known variants + #[TEXT] + pub variants: String, + /// General habits + #[TEXT] + pub habits: String, + /// Generic creature description + #[TEXT] + pub description: String, + /// Annotations + #[TEXT] + pub annotations: String, + /// Annotations GM + #[TEXT] + pub annotations_master: Option, + /// The battle plan of the creature + #[TEXT] + pub battle_plan: String, + /// The graph of intents (image) + #[TEXT] + pub intent_graph: String, +} + +/// A helper wrapper around all rewards +pub struct CreatureListRewards { + pub rewards: Vec, +} + +/// One row from the `rewards` table. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, FieldsAsSlice)] +pub struct CreatureReward { + /// The id of the creature that owns the reward (FOREIGN KEY to `creature_data.id`). + #[INTEGER] + pub creature_id: i64, + /// Full name of the reward. + #[TEXT] + pub name: String, + /// Category of the ability + #[TEXT] + pub category: String, + /// Effect of the ability + pub effect: String, +} + +/// A helper wrapper around all attacks belonging to a monster. +/// +/// The inner vector holds individual attack rows (`MonsterSingleAttack`); +/// helper methods on this struct (not shown here) can split or aggregate +/// these rows into more ergonomic data structures. +pub struct CreatureListAttacks { + /// All attack rows for the monster, as read from the database. + pub attacks: Vec, +} + +/// A helper wrapper around all resistances belonging to a monster. +/// +/// The inner vector contains `MonsterSingleResistance` entries; methods +/// on this struct can provide iterators or lookup functions that are +/// easier to consume than raw rows. +pub struct CreatureListBodyParts { + /// All resistance rows for the monster, as read from the database. + pub body_parts: Vec, +} + +/// Represents a single attack entry as deserialized from the database. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, FieldsAsSlice)] +pub struct MonsterSingleAttack { + /// The id of the creature that owns the ability (FOREIGN KEY to `creature_data.id`). + #[INTEGER] + pub creature_id: i64, + /// Full name of the ability. + #[TEXT] + pub name: String, + /// Short trigram used in combat logs, etc. + #[TEXT] + pub short_name: String, + /// Which phase(s) of a turn can the ability be used + #[TEXT] + pub phase: String, + /// Attack grouping, for multiple entries in one attack + #[INTEGER] + pub attack_group: Option, + /// Ability “type” as a trigram + #[TEXT] + pub attack_type: String, + /// How the ability targets opponents (e.g. “single”, “area” …). + #[TEXT] + pub targetting: Option, + /// Fatigue cost for activating the ability. + #[INTEGER] + pub cost_fatigue: Option, + /// Action‑point cost (used in systems where actions and fatigue are separate). + #[INTEGER] + pub cost_action: Option, + /// Element or school that powers the ability. + #[TEXT] + pub element: Option, + /// Damage dealt as a *fatigue* penalty (i.e. non‑instant death). + #[INTEGER] + pub damage_fatigue: Option, + /// Regular textual description + #[TEXT] + pub damage_regular: Option, + /// All “effects” that happen when the ability resolves. + /// The string format is up‑to‑you – many people store JSON or a custom DSL here. + #[TEXT] + pub effects: String, + /// Minimum parry rating required to avoid the ability’s effect. + #[INTEGER] + pub threshold_parry: Option, + /// Minimum dodge rating required to avoid the ability’s effect. + #[INTEGER] + pub threshold_dodge: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, FieldsAsSlice)] +/// All different body parts and their different resists +pub struct CreatureBodyPart { + #[INTEGER] + pub creature_id: i64, + #[TEXT] + pub body_part_name: String, + #[INTEGER] + pub threshold_p1: Option, + #[INTEGER] + pub threshold_p2: Option, + #[INTEGER] + pub protection_p1: Option, + #[INTEGER] + pub protection_p2: Option, + #[INTEGER] + pub integrity_p1: Option, + #[INTEGER] + pub integrity_p2: Option, + #[INTEGER] + pub life_points_p1: Option, + #[INTEGER] + pub life_points_p2: Option, + #[TEXT] + pub slash: Option, + #[TEXT] + pub blunt: Option, + #[TEXT] + pub piercing: Option, + #[TEXT] + pub celestial: Option, + #[TEXT] + pub fire: Option, + #[TEXT] + pub magma: Option, + #[TEXT] + pub earth: Option, + #[TEXT] + pub wood: Option, + #[TEXT] + pub abyssal: Option, + #[TEXT] + pub wind: Option, + #[TEXT] + pub water: Option, + #[TEXT] + pub ice: Option, + #[TEXT] + pub thunder: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, FieldsAsSlice)] +/// All creature stats +pub struct CreatureStats { + #[INTEGER] + pub creature_id: i64, + #[TEXT] + pub p1_init: MonsterInitString, + #[TEXT] + pub p2_init: MonsterInitString, + #[TEXT] + pub p1_actions: MonsterInitString, + #[TEXT] + pub p2_actions: MonsterInitString, + #[INTEGER] + pub strength: i64, + #[INTEGER] + pub perception: i64, + #[INTEGER] + pub willpower: i64, + #[INTEGER] + pub alteration_resistance: i64, + #[INTEGER] + pub torque: i64, + #[INTEGER] + pub awareness: i64, + #[INTEGER] + pub fatigue: i64, + #[INTEGER] + pub mvt_walk: i64, + #[INTEGER] + pub mvt_trot: i64, + #[INTEGER] + pub mvt_run: i64, + #[INTEGER] + pub mvt_flight: Option, + #[INTEGER] + pub blood_base: i64, + #[INTEGER] + pub blood_battle: i64, + #[INTEGER] + pub blood_carve: i64, +} + +// ----------- HERE BE WARCRIMES ------------- + +#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] +#[serde(transparent)] +/// A custom string used to avoid work +pub struct MonsterInitString { + inner: String, +} + +/// A monster init row (entire) +#[derive(Debug, Clone, Deserialize, Serialize)] +pub struct MonsterRepetableInitRow { + pub turn: usize, + pub p1_value: String, + pub p1_actions: String, + pub p2_value: String, + pub p2_actions: String, +} +impl MonsterRepetableInitRow { + pub fn vec_from( + p1_vals: &MonsterInitString, + p2_vals: &MonsterInitString, + p1_acts: &MonsterInitString, + p2_acts: &MonsterInitString, + ) -> Vec { + let p1_vals = MonsterRepetableInitValue::from(p1_vals); + let p2_vals = MonsterRepetableInitValue::from(p2_vals); + let p1_acts = MonsterRepetableInitValue::from(p1_acts); + let p2_acts = MonsterRepetableInitValue::from(p2_acts); + p1_acts + .inner + .iter() + .zip(p2_acts.inner.iter()) + .zip(p1_vals.inner.iter()) + .zip(p2_vals.inner.iter()) + .enumerate() + .map(|(turn, (((p1_actions, p2_actions), p1_value), p2_value))| { + MonsterRepetableInitRow { + p1_value: p1_value.clone(), + p1_actions: p1_actions.clone(), + p2_value: p2_value.clone(), + p2_actions: p2_actions.clone(), + turn: turn + 1, + } + }) + .collect::>() + } +} + +#[derive(Debug, Clone)] +/// A repeteable init string +pub struct MonsterRepetableInitValue { + inner: Vec, +} + +impl From<&MonsterInitString> for MonsterRepetableInitValue { + fn from(value: &MonsterInitString) -> Self { + Self { + inner: value.inner.split(',').map(|s| s.to_string()).collect(), + } + } +} + +impl Serialize for MonsterInitString { + fn serialize(&self, serializer: S) -> Result + where + S: serde::Serializer, + { + let mut c = self.inner.split(','); + serializer.collect_str( + c.next() + .unwrap_or_else(|| panic!("Trying to split {} by ','", self.inner)), + ) + } +} + +/// The full list of all monster attacks +/// +/// Split by phasing +#[derive(Debug)] +pub struct MonsterAllAttacks { + pub phases: IndexMap>, +} +/// A single attack, grouping all sub attacks +/// Also extract extra info to allow easier insertions +#[derive(Serialize, Deserialize, Debug)] +pub struct MonsterFullAttack { + pub attacklist: Vec, + pub color: String, + pub description: String, +} diff --git a/crates/ravenous-tools/Cargo.toml b/crates/ravenous-tools/Cargo.toml index 6044cd9..8fcf3e7 100644 --- a/crates/ravenous-tools/Cargo.toml +++ b/crates/ravenous-tools/Cargo.toml @@ -17,6 +17,7 @@ clap = {workspace = true} tokio = {workspace = true} formatter = {workspace = true} weaponry = {workspace = true} +monsters = {workspace = true} [package.metadata.cargo-machete] ignored = ["tokio"] diff --git a/crates/ravenous-tools/src/main.rs b/crates/ravenous-tools/src/main.rs index 826a1bd..86d8bf1 100644 --- a/crates/ravenous-tools/src/main.rs +++ b/crates/ravenous-tools/src/main.rs @@ -10,6 +10,7 @@ use fast_class::make_better_gen; use formatter::format_file; use graphs::make_graphs; use make::make_pdf; +use monsters::monsters_dispatch; use stats::stat_solver; use tablegen::table_gen; use weaponry::analysis::launch_analysis; @@ -37,6 +38,7 @@ fn main() -> Result<()> { Commands::Format(args) => format_file(&args, &config), Commands::Analysis(args) => Ok(launch_analysis(&args, &config)?), // Not using anyhow but a custom error Commands::BetterGen(args) => make_better_gen(&args, &config), + Commands::Monsters(args) => monsters_dispatch(&args, &config), } } diff --git a/helper_config.toml b/helper_config.toml index cfb250a..8ff4a0c 100644 --- a/helper_config.toml +++ b/helper_config.toml @@ -146,3 +146,151 @@ end_long_side = ''' \hline \end{longtblr} \end{center}\end{landscape}''' end_empty = "" + +[monster] +intro = '''\begin{tblr}{ + vspan=even, hspan=minimal, + colspec={X[-1] X[-1]}, + cell{1}{1}={c=2}{c}, + } + +\includegraphics[height=5cm]{{image}} & \\ +& \\ +Nom & {{name}} \\ +Dénomination & {{denomination}} \\ +Calamité & {{calamity}} \\ +Niveau de danger (HSE) & {{danger_level}} \\ +& \\ +Habitat & \SetCell{font=\footnotesize} {{habitat}} \\ +Dysmorphisme & \SetCell{font=\footnotesize} {{dismorphism}} \\ +Couleurs & \SetCell{font=\footnotesize} {{colors}} \\ +Réaction à l'homme & \SetCell{font=\footnotesize} {{default_human_reaction}} \\ +Variantes & \SetCell{font=\footnotesize} {{variants}}\\ +Mœurs & \SetCell{font=\footnotesize} {{habits}} \\ +\end{tblr} +\vfill +\begin{tblr}{ + colspec={X[-1]}, + hline{2,4,6}, + row{2,4,6}={font=\footnotesize} + } +\textbf{Description} \\ +{{description}} \\ +\textbf{Annotations} \\ +{{annotations}} \\ +\textbf{Récompenses} \\ +\end{tblr} +\begin{tblr}{ + colspec={X[-1] X[-1,c] X[-1,j]}, + vspan=even, hspan=minimal, + row{1-Z}={font=\footnotesize}, + rows={m}, +} +''' +blood_reward=''' + \SetCell[c=2]{j} Sang (base, combat, dépeçage) & & {{blood_base}}, {{blood_battle}}, {{blood_carve}} \\ +''' + +rewards_row=''' {{name}} & {{category}} & {{effect}} \\ +''' +rewards_end='''\end{tblr} +\vfill +''' + +body_parts_intro=''' +\begin{tblr}{ + colspec={X[l,-1] X[-1] X[-1] X[] X[] X[-1] X[-1] X[] X[]}, + rowspec={X[t] X[t,c] X[c,2em] X[c,2em] X[c,2em] X[c,2em] X[c,2em] X[c,2em] X[c,2em] X[c,2em] X[c,2em] X[j,5em]}, + hspan=minimal, + cell{1}{2}={c=4}{c}, + cell{1}{6}={c=4}{c}, + row{2,12}={font=\footnotesize}, + vline{6} = {2-11}{solid}, +} + & P1 & & & & P2 & \\ + & Seuil & Prot & Intégrité & PV & Seuil & Prot & Intégrité & PV\\ +\hline +''' +body_parts_row='''\SetCell{font=\footnotesize} {{body_part_name}} & ${{threshold_p1}}$ & ${{protection_p1}}$ & \SetCell{r,f}\tiny${{integrity_p1}}$ & \SetCell{r,f}\tiny${{life_points_p1}}$ & ${{threshold_p2}}$ & ${{protection_p2}}$ & \SetCell{r,f}\tiny${{integrity_p2}}$ & \SetCell{r,f}\tiny${{life_points_p2}}$\\''' +body_parts_end= ''' \hline +\SetCell[c=9]{j,h} {\textbf{Notes} \\ {{annotations_master}}\\ +\hline +\end{tblr}''' +resists_intro=''' \center{ +\begin{tblr}{ + colspec={Q[3.5em] Q[1.6em] Q[1.6em] Q[1.6em] Q[1.6em] Q[1.6em] Q[1.6em] Q[1.6em] Q[1.6em] Q[1.6em] Q[1.6em] Q[1.6em] Q[1.6em]}, + rowspec={Q[c,f] Q[c,m] Q[c] Q[c] Q[c] Q[c] Q[c] Q[c] Q[c] Q[c] Q[c]}, + row{3-11}={font=\tiny}, +} + & & & & & & & \small{*} & & & & \small{*} & \small{*} & \\ +\SetCell{c} Res & \slash & \pierce & \blunt & \symceleste & \symfire & \symearth & \symwood & \symmagma & \symabyss & \symwater & \symwind & \symice & \symthunder \\ +\hline +''' +resists_row= ''' \SetCell{font=\footnotesize} {{name}} & ${{slash}}$ & ${{pierce}}$ & ${{blunt}}$ & ${{celestial}}$ & ${{fire}}$ & ${{earth}}$ & ${{wood}}$ & ${{magma}}$ & ${{celeste}}$ & ${{water}}$ & ${{wind}}$ & ${{ice}}$ & ${{thunder}}$ \\ +''' +resists_end=' \end{tblr}' + +stats='''\begin{tblr}{ + colspec={c c c c c c c c c c c c c c c c c c c}, + row{2}={font=\footnotesize}, + row{3-6}={font=\tiny}, +} + & \SetCell[c=2]{c} P1 & & \SetCell[c=2]{c} P2 & & & \SetCell[c=7]{c} Stats & & & & & & & & \SetCell[c=4]{c} Mouvement & & & & \\ + \cline{2-3} \cline{4-5} \cline{7-13} \cline{15-18} +\rb{Initiative} & \rb{Valeur} & \rb{Actions} & \rb{Valeur} & \rb{Actions} & & \rb{Force} & \rb{Perception} & \rb{Volonté} & \rb{Res Alt} & \rb{Torque} & \rb{Vigilance} & \rb{Fatigue} & & \rb{Marche} & \rb{Trot} & \rb{Course} & \rb{Vol} \\ +\SetCell{font=\footnotesize}$t_1$ & ${{p1_init}}$ & $4$A & ${{p2_init}}$ & $4$A & & ${{strength}}$ & ${{perception}}$ & ${{willpower}}$ & ${{alteration_resistance}}$ & ${{torque}}$ & ${{awareness}}$ & ${{fatigue}}$ & & ${{mvt_walk}}$ & ${{mvt_trot}}$ & ${{mvt_run}}$ & ${{mvt_flight}}$ \\ +''' +init_rows=''' +\SetCell{font=\footnotesize}$t_{{turn}}$ & ${{p1_value}}$ & {{pt1_actions}} & ${{p2_value}}$ & {{p2_actions}} \\ +''' +init_end= ''' +\end{tblr} +} +\vfill ''' +attacks_intro= '''\scriptsize{ +\begin{tblr}{ + colspec={X[0.05] X[4,l] X[1,c] X[1,c] X[0.3,c] X[0.3,c] X[0.3,c] X[0.3,c] X[0.3,c] X[2,r] X[2,c] X[0.3,c] X[0.3,c]}, + hspan=minimal, + colsep=2pt, + row{2}={font=\tiny}, +} + & & & & & \SetCell[c=2]{c} Coûts & & & \SetCell[c=2]{c} Dégâts & & & \SetCell[c=2]{c} Seuils & \\ +\cline{6-7} \cline{9-10} \cline{12-13} +& \SetCell{c} & {ID} & {Type} & \rb{Ciblage} & \rb{Fatigue} & \rb{Action} & \rb{Élément} & \rb{Fatigue} & \SetCell{c} \rb{Normaux} & {Effets} & \rb{Parade} & \rb{Esquive} \\ +\SetHline{1-13}{solid} +''' +phase_row= ''' +\SetHline{1}{0pt} +\SetCell[c=13]{white} {{phase_name}} & & & & & & & & & & \\ +''' + +attack_before_repeat=' \hline' +attack_color='\SetCell[r=2]{bg={{color}}}' # Very ugly hack, going to bed +attack_repeatable_row= ''' & {{name}} & {{short_name}} & {{atk_type}} & {{targetting}} & {{cost_fatigue}} & {{cost_action}} & {{element}} & {{damage_fatigue}} &{{damage_regular}} & {{effects}} & {{threshold_parry}} & {{threshold_dodge}} \\ +''' +attack_info_row='''& \SetCell[c=12]{j} {{description}} & & & & & & & & & & \\ +\hline +''' +attacks_end= ''' \end{tblr} +} +\vfill +\renewcommand{\rb}{\undefined} +''' + +intent_table=''' \begin{tblr}{ + colspec={X[7] X[3]}, + rowspec={X[c] X[j,h,8cm]}, + vline{2}, + hline{2}, + row{2}={font=\footnotesize}, +} +Plan de combat & Graphique d'intentions \\ +{{battle_plan}} & {{intent_graph}} \\ +\end{tblr} +\vfill +''' +color_table=''' + THB: \ravblue + TBD: \nocolor +''' +default_color='\blu' diff --git a/ravenous_databases b/ravenous_databases index ee3b7ff..211b22d 160000 --- a/ravenous_databases +++ b/ravenous_databases @@ -1 +1 @@ -Subproject commit ee3b7ffd5fa4e3bfbcd13cb5d69b9c0e3e9b06e5 +Subproject commit 211b22dbe327b66f0da9f5c5a780dd6ec00a88d8