From 529f90b93e28176aae97fc0bdcef3f4c83615346 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Wed, 15 Jul 2026 02:12:24 +0200 Subject: [PATCH 1/9] Adds boilerplate for monsters --- Cargo.toml | 1 + crates/cli_parser/src/lib.rs | 5 ++++- crates/config/src/lib.rs | 1 + crates/config/src/monsters.rs | 28 ++++++++++++++++++++++++++++ crates/monsters/Cargo.toml | 25 +++++++++++++++++++++++++ crates/monsters/src/lib.rs | 29 +++++++++++++++++++++++++++++ crates/ravenous-tools/Cargo.toml | 1 + crates/ravenous-tools/src/main.rs | 2 ++ 8 files changed, 91 insertions(+), 1 deletion(-) create mode 100644 crates/config/src/monsters.rs create mode 100644 crates/monsters/Cargo.toml create mode 100644 crates/monsters/src/lib.rs diff --git a/Cargo.toml b/Cargo.toml index a79e6ec..a467453 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" diff --git a/crates/cli_parser/src/lib.rs b/crates/cli_parser/src/lib.rs index 1fd3ad2..ac7820d 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, 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)] 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..4f538fc --- /dev/null +++ b/crates/config/src/monsters.rs @@ -0,0 +1,28 @@ +// Workspace: config +// File: config/src/monsters.rs +//! The inner config for monster module +//! + +use clap::{Args, ValueEnum}; + +#[derive(Args, Debug, Clone)] +/// The configuration struct for the Graph +pub struct MonsterConfig { + /// Special target + pub target: MonsterTarget, + + /// 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, +} diff --git a/crates/monsters/Cargo.toml b/crates/monsters/Cargo.toml new file mode 100644 index 0000000..522d216 --- /dev/null +++ b/crates/monsters/Cargo.toml @@ -0,0 +1,25 @@ +[package] +name = "monsters" +edition = "2024" +version.workspace = true + +[dependencies] +config = {workspace = true} +cli_parser = {workspace = true} +more_fields = {workspace = true} +anyhow = {workspace = true} +# regex = {workspace = true} +# csv = {workspace = true} +# serde = {workspace = true} +# comfy-table = "7.2.2" +# probability = "0.20.3" +rusqlite = { version = "0.40.1" } # , features = ["bundled"] +serde_rusqlite = "0.43.0" +# serde_json = { version = "1.0.150", features = ["alloc"] } +strum = { version = "0.28.0", features = ["derive"] } +# charming = { version = "0.4.0", features = [] } + +[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..b49078d --- /dev/null +++ b/crates/monsters/src/lib.rs @@ -0,0 +1,29 @@ +//! # 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 anyhow::Result; +use cli_parser::Config; +use config::monsters::MonsterConfig; + +/// Dispatches the chosen monster action. +pub fn monsters_dispatch(args: &MonsterConfig, _config: &Config) -> Result<()> { + use config::monsters::MonsterTarget; + + match args.target { + MonsterTarget::Clean => todo!("implement cleaning logic"), + MonsterTarget::Export => todo!("implement export logic"), + MonsterTarget::Show => todo!("implement show logic"), + } +} 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), } } -- 2.45.1 From 1e0c6dfb5344b66289158850b80992a13b286d01 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Wed, 15 Jul 2026 02:32:10 +0200 Subject: [PATCH 2/9] Useful structs --- crates/config/src/monsters.rs | 1 + crates/monsters/src/lib.rs | 2 + crates/monsters/src/monster_structs.rs | 60 ++++++++++++++++++++++++++ 3 files changed, 63 insertions(+) create mode 100644 crates/monsters/src/monster_structs.rs diff --git a/crates/config/src/monsters.rs b/crates/config/src/monsters.rs index 4f538fc..9adb449 100644 --- a/crates/config/src/monsters.rs +++ b/crates/config/src/monsters.rs @@ -2,6 +2,7 @@ // File: config/src/monsters.rs //! The inner config for monster module //! +#![allow(dead_code)] use clap::{Args, ValueEnum}; diff --git a/crates/monsters/src/lib.rs b/crates/monsters/src/lib.rs index b49078d..c9851f4 100644 --- a/crates/monsters/src/lib.rs +++ b/crates/monsters/src/lib.rs @@ -13,6 +13,8 @@ //! (`MonsterConfig`) and delegates to the appropriate sub‑routine (clean, export or show). //! +pub mod monster_structs; + use anyhow::Result; use cli_parser::Config; use config::monsters::MonsterConfig; diff --git a/crates/monsters/src/monster_structs.rs b/crates/monsters/src/monster_structs.rs new file mode 100644 index 0000000..e1ca465 --- /dev/null +++ b/crates/monsters/src/monster_structs.rs @@ -0,0 +1,60 @@ +//! # Monster Structures +//! +//! The `monster_structs` crate 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)] + +/// A monster ready for consumption by other modules. +pub struct FullMonster { + /// Unique identifier, derived when the monster is instantiated. + pub id: usize, + + /// Monster’s name. + pub name: String, + + /// Serialized stats directly copied from the database table. + pub stats: MonsterStats, + + /// Collection of attacks, wrapped in a helper that exposes useful functions. + pub attacks: MonsterAttacks, + + /// Collection of resistances, wrapped in a helper for convenient iteration. + pub resistances: MonsterResistances, +} + +/// Raw stat values deserialized straight from the database. +pub struct MonsterStats {} + +/// 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 MonsterAttacks { + /// 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 MonsterResistances { + /// All resistance rows for the monster, as read from the database. + pub resistances: Vec, +} + +/// Represents a single row of resistance data for a monster. +pub struct MonsterSingleResistance {} + +/// Represents a single attack entry as deserialized from the database. +pub struct MonsterSingleAttack {} -- 2.45.1 From 46b8e3525415dff4b8f7ac53c5cd98b001c4d4ac Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Wed, 15 Jul 2026 19:00:09 +0200 Subject: [PATCH 3/9] Partial commit before a refactor --- crates/config/src/monsters.rs | 3 + crates/monsters/Cargo.toml | 2 +- crates/monsters/src/lib.rs | 136 +++++++++++++- crates/monsters/src/monster_database.rs | 1 + crates/monsters/src/monster_export.rs | 5 + crates/monsters/src/monster_structs.rs | 230 ++++++++++++++++++++++-- ravenous_databases | 2 +- 7 files changed, 360 insertions(+), 19 deletions(-) create mode 100644 crates/monsters/src/monster_database.rs create mode 100644 crates/monsters/src/monster_export.rs diff --git a/crates/config/src/monsters.rs b/crates/config/src/monsters.rs index 9adb449..6bb9bc2 100644 --- a/crates/config/src/monsters.rs +++ b/crates/config/src/monsters.rs @@ -12,6 +12,9 @@ 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, diff --git a/crates/monsters/Cargo.toml b/crates/monsters/Cargo.toml index 522d216..d0c0ebb 100644 --- a/crates/monsters/Cargo.toml +++ b/crates/monsters/Cargo.toml @@ -10,7 +10,7 @@ more_fields = {workspace = true} anyhow = {workspace = true} # regex = {workspace = true} # csv = {workspace = true} -# serde = {workspace = true} +serde = {workspace = true} # comfy-table = "7.2.2" # probability = "0.20.3" rusqlite = { version = "0.40.1" } # , features = ["bundled"] diff --git a/crates/monsters/src/lib.rs b/crates/monsters/src/lib.rs index c9851f4..56e57cf 100644 --- a/crates/monsters/src/lib.rs +++ b/crates/monsters/src/lib.rs @@ -13,19 +13,143 @@ //! (`MonsterConfig`) and delegates to the appropriate sub‑routine (clean, export or show). //! +use anyhow::{Context, anyhow}; +use serde::de::DeserializeOwned; +mod monster_database; +mod monster_export; pub mod monster_structs; use anyhow::Result; use cli_parser::Config; use config::monsters::MonsterConfig; +use rusqlite::Connection; +use crate::monster_structs::{ + CreatureBodyParts, CreatureData, CreatureResistance, CreatureStats, FullMonster, + MonsterAttacks, MonsterSingleAttack, +}; + +/// 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))? + }}; +} /// Dispatches the chosen monster action. pub fn monsters_dispatch(args: &MonsterConfig, _config: &Config) -> Result<()> { - use config::monsters::MonsterTarget; + // use config::monsters::MonsterTarget; - match args.target { - MonsterTarget::Clean => todo!("implement cleaning logic"), - MonsterTarget::Export => todo!("implement export logic"), - MonsterTarget::Show => todo!("implement show logic"), - } + let connection = + Connection::open(&args.database).context(format!("Opening database {}", args.database))?; + + fetch_all_data(connection)?; + // match args.target { + // MonsterTarget::Clean => todo!("implement cleaning logic"), + // MonsterTarget::Export => todo!("implement export logic"), + // MonsterTarget::Show => todo!("implement show logic"), + // } + Ok(()) +} + +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, attack_type, name") + ); + let creature_resistances = fetch_from!( + CreatureResistance, + connection, + creature, + "creature_resistances", + Some("body_part_name") + ); + let creature_body_parts = fetch_from!( + CreatureBodyParts, + 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(); + + finished_creatures.push(FullMonster { + id: creature.id, + name: creature.name.clone(), + stats: creature_stats, + attacks: MonsterAttacks { + attacks: creature_attacks, + }, + creature_body_parts: todo!(), + resistances: monster_structs::MonsterResistances { + resistances: creature_resistances, + }, + data: creature.clone(), + }); + } + 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_database.rs b/crates/monsters/src/monster_database.rs new file mode 100644 index 0000000..f9da2c4 --- /dev/null +++ b/crates/monsters/src/monster_database.rs @@ -0,0 +1 @@ +#![allow(dead_code)] diff --git a/crates/monsters/src/monster_export.rs b/crates/monsters/src/monster_export.rs new file mode 100644 index 0000000..317cfc8 --- /dev/null +++ b/crates/monsters/src/monster_export.rs @@ -0,0 +1,5 @@ +//! Monster export module + +pub trait ToTex { + fn export_to_tex(self) -> String; +} diff --git a/crates/monsters/src/monster_structs.rs b/crates/monsters/src/monster_structs.rs index e1ca465..631a6e0 100644 --- a/crates/monsters/src/monster_structs.rs +++ b/crates/monsters/src/monster_structs.rs @@ -1,6 +1,6 @@ //! # Monster Structures //! -//! The `monster_structs` crate defines the data model that represents a monster +//! 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 @@ -11,27 +11,86 @@ //! ``` //! #![allow(dead_code)] +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: usize, + pub id: i64, /// Monster’s name. pub name: String, - /// Serialized stats directly copied from the database table. - pub stats: MonsterStats, + /// Serialized generic data directly copied from the database table. + pub data: CreatureData, + + /// Creature body parts and their resists + pub creature_body_parts: CreatureBodyParts, /// Collection of attacks, wrapped in a helper that exposes useful functions. pub attacks: MonsterAttacks, /// Collection of resistances, wrapped in a helper for convenient iteration. pub resistances: MonsterResistances, + + /// Serialized stats directly copied from the database table. + pub stats: CreatureStats, } -/// Raw stat values deserialized straight from the database. -pub struct MonsterStats {} +/// 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, + /// The battle plan of the creature + #[TEXT] + pub battle_plan: String, + /// The graph of intents (image) + #[TEXT] + pub intent_graph: String, + /// Problematic list of rewards + // TODO: FIX + #[TEXT] + pub rewards: String, +} /// A helper wrapper around all attacks belonging to a monster. /// @@ -50,11 +109,160 @@ pub struct MonsterAttacks { /// easier to consume than raw rows. pub struct MonsterResistances { /// All resistance rows for the monster, as read from the database. - pub resistances: Vec, + pub resistances: Vec, } -/// Represents a single row of resistance data for a monster. -pub struct MonsterSingleResistance {} - /// Represents a single attack entry as deserialized from the database. -pub struct MonsterSingleAttack {} +#[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)] +pub struct CreatureResistance { + /// The id of the creature that owns these resistances (FOREIGN KEY to `creature_data.id`). + #[INTEGER] + pub creature_id: i64, + /// Full name of the body part (e.g. “Head”, “Arm” …). + #[TEXT] + pub body_part_name: String, + #[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 different body parts and their different resists +pub struct CreatureBodyParts { + #[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, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, FieldsAsSlice)] +/// All creature stats +pub struct CreatureStats { + #[INTEGER] + pub creature_id: i64, + #[TEXT] + pub p1_init: String, + #[TEXT] + pub p2_init: String, + #[TEXT] + pub p1_actions: String, + #[TEXT] + pub p2_actions: String, + #[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, +} diff --git a/ravenous_databases b/ravenous_databases index ee3b7ff..9667d60 160000 --- a/ravenous_databases +++ b/ravenous_databases @@ -1 +1 @@ -Subproject commit ee3b7ffd5fa4e3bfbcd13cb5d69b9c0e3e9b06e5 +Subproject commit 9667d600d45589b7ece90114d99862bb4f14c58c -- 2.45.1 From 37a6531ae48562cfd597e825d854eb5d17874973 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Wed, 15 Jul 2026 19:10:44 +0200 Subject: [PATCH 4/9] Merged both tables for resist & bp --- crates/monsters/src/lib.rs | 17 ++------ crates/monsters/src/monster_structs.rs | 55 ++++++++++---------------- 2 files changed, 25 insertions(+), 47 deletions(-) diff --git a/crates/monsters/src/lib.rs b/crates/monsters/src/lib.rs index 56e57cf..08a0ab9 100644 --- a/crates/monsters/src/lib.rs +++ b/crates/monsters/src/lib.rs @@ -25,8 +25,7 @@ use config::monsters::MonsterConfig; use rusqlite::Connection; use crate::monster_structs::{ - CreatureBodyParts, CreatureData, CreatureResistance, CreatureStats, FullMonster, - MonsterAttacks, MonsterSingleAttack, + CreatureBodyPart, CreatureData, CreatureStats, FullMonster, MonsterAttacks, MonsterSingleAttack, }; /// Deserialise a table row (or rows) into the given type and add a nice context message. @@ -72,14 +71,7 @@ fn fetch_all_data(connection: Connection) -> Result, anyhow::Er Some("phase, attack_group, attack_type, name") ); let creature_resistances = fetch_from!( - CreatureResistance, - connection, - creature, - "creature_resistances", - Some("body_part_name") - ); - let creature_body_parts = fetch_from!( - CreatureBodyParts, + CreatureBodyPart, connection, creature, "creature_body_parts", @@ -104,9 +96,8 @@ fn fetch_all_data(connection: Connection) -> Result, anyhow::Er attacks: MonsterAttacks { attacks: creature_attacks, }, - creature_body_parts: todo!(), - resistances: monster_structs::MonsterResistances { - resistances: creature_resistances, + body_parts: monster_structs::CreatureBodyParts { + body_parts: creature_resistances, }, data: creature.clone(), }); diff --git a/crates/monsters/src/monster_structs.rs b/crates/monsters/src/monster_structs.rs index 631a6e0..99d72d4 100644 --- a/crates/monsters/src/monster_structs.rs +++ b/crates/monsters/src/monster_structs.rs @@ -25,14 +25,11 @@ pub struct FullMonster { /// Serialized generic data directly copied from the database table. pub data: CreatureData, - /// Creature body parts and their resists - pub creature_body_parts: CreatureBodyParts, - /// Collection of attacks, wrapped in a helper that exposes useful functions. pub attacks: MonsterAttacks, /// Collection of resistances, wrapped in a helper for convenient iteration. - pub resistances: MonsterResistances, + pub body_parts: CreatureBodyParts, /// Serialized stats directly copied from the database table. pub stats: CreatureStats, @@ -107,9 +104,9 @@ pub struct MonsterAttacks { /// 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 MonsterResistances { +pub struct CreatureBodyParts { /// All resistance rows for the monster, as read from the database. - pub resistances: Vec, + pub body_parts: Vec, } /// Represents a single attack entry as deserialized from the database. @@ -164,13 +161,28 @@ pub struct MonsterSingleAttack { } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, FieldsAsSlice)] -pub struct CreatureResistance { - /// The id of the creature that owns these resistances (FOREIGN KEY to `creature_data.id`). +/// All different body parts and their different resists +pub struct CreatureBodyPart { #[INTEGER] pub creature_id: i64, - /// Full name of the body part (e.g. “Head”, “Arm” …). #[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] @@ -199,31 +211,6 @@ pub struct CreatureResistance { pub thunder: Option, } -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, FieldsAsSlice)] -/// All different body parts and their different resists -pub struct CreatureBodyParts { - #[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, -} - #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, FieldsAsSlice)] /// All creature stats pub struct CreatureStats { -- 2.45.1 From 006ebe9a0b450da42832798177cf0215f1aaf31a Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Wed, 15 Jul 2026 20:22:40 +0200 Subject: [PATCH 5/9] Working on the template --- crates/cli_parser/src/lib.rs | 4 +- crates/config/src/monsters.rs | 43 ++++++++ crates/config/src/tablegen.rs | 2 +- crates/monsters/Cargo.toml | 1 + crates/monsters/src/lib.rs | 128 ++++------------------ crates/monsters/src/monster_database.rs | 110 +++++++++++++++++++ crates/monsters/src/monster_export.rs | 1 + helper_config.toml | 135 ++++++++++++++++++++++++ ravenous_databases | 2 +- 9 files changed, 314 insertions(+), 112 deletions(-) diff --git a/crates/cli_parser/src/lib.rs b/crates/cli_parser/src/lib.rs index ac7820d..60266c7 100644 --- a/crates/cli_parser/src/lib.rs +++ b/crates/cli_parser/src/lib.rs @@ -9,7 +9,7 @@ use config::{ formatter::FormatterConfig, graph::GraphConfig, make::{HELP_BLOCK_SELECTION, MakeTargets, VerboseLevel}, - monsters::MonsterConfig, + monsters::{MonsterConfig, MonsterMarkup}, statsolver::StatConfig, tablegen::{Craft, TableArgs}, }; @@ -77,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/src/monsters.rs b/crates/config/src/monsters.rs index 6bb9bc2..5cec993 100644 --- a/crates/config/src/monsters.rs +++ b/crates/config/src/monsters.rs @@ -5,6 +5,7 @@ #![allow(dead_code)] use clap::{Args, ValueEnum}; +use serde::Deserialize; #[derive(Args, Debug, Clone)] /// The configuration struct for the Graph @@ -30,3 +31,45 @@ pub enum MonsterTarget { /// Show useful data Show, } + +/// The config data in .toml +#[allow(dead_code)] +#[derive(Deserialize)] +pub struct MonsterMarkup { + /// Intro – the very first chunk of LaTeX that starts a monster page. + pub intro: String, + + // ──────────────────────── BODY‑PART TABLE ──────────────────────── // + /// Opening `` tag and any pre‑header rows for the body‑part table + pub body_parts_intro: String, + /// One row per body part (e.g. “Tête”, “Corps”). Use `{}` placeholders if you need dynamic values. + pub body_parts_row: String, + /// Closing `\hline`/`\end{tblr}` tags for the body‑part table + pub body_parts_end: String, + + // ──────────────────────── RESISTANCE TABLE ────────────────────── // + /// Opening tag & any header rows before the resistance rows + pub resists_intro: String, + /// One row per resistance type (e.g. “Slashing”, “Fire”) + pub resists_row: String, + /// Closing `\hline`/`\end{tblr}` tags for the resistance table + pub resist_end: String, + + // ──────────────────────── STATS BLOCK ───────────────────────── // + /// The whole stat block (body‑part thresholds, protection, HP…) + pub stats: String, + + // ──────────────────────── ATTACK LIST ─────────────────────── // + /// Opening `` tag & header rows for the action list + pub attacks_intro: String, + /// Closing `\hline`/`\end{tblr}` tags for the action list + pub attacks_end: String, + + // ──────────────────────── PHASE TABLES ─────────────────────── // + /// One row per “phase” of the monster’s combat routine + pub phase_row: String, + /// A repeatable action row (used inside a phase) + pub attack_repeatable_row: String, + /// An informational row that expands on the current action + pub attack_info_row: String, +} 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/monsters/Cargo.toml b/crates/monsters/Cargo.toml index d0c0ebb..e499a1f 100644 --- a/crates/monsters/Cargo.toml +++ b/crates/monsters/Cargo.toml @@ -17,6 +17,7 @@ rusqlite = { version = "0.40.1" } # , features = ["bundled"] serde_rusqlite = "0.43.0" # serde_json = { version = "1.0.150", features = ["alloc"] } strum = { version = "0.28.0", features = ["derive"] } +handlebars = "6.4.3" # charming = { version = "0.4.0", features = [] } [dev-dependencies] diff --git a/crates/monsters/src/lib.rs b/crates/monsters/src/lib.rs index 08a0ab9..11441f9 100644 --- a/crates/monsters/src/lib.rs +++ b/crates/monsters/src/lib.rs @@ -13,8 +13,11 @@ //! (`MonsterConfig`) and delegates to the appropriate sub‑routine (clean, export or show). //! -use anyhow::{Context, anyhow}; -use serde::de::DeserializeOwned; +use crate::monster_database::fetch_all_data; +use std::collections::BTreeMap; + +use anyhow::Context; +use handlebars::Handlebars; mod monster_database; mod monster_export; pub mod monster_structs; @@ -24,31 +27,26 @@ use cli_parser::Config; use config::monsters::MonsterConfig; use rusqlite::Connection; -use crate::monster_structs::{ - CreatureBodyPart, CreatureData, CreatureStats, FullMonster, MonsterAttacks, MonsterSingleAttack, -}; - -/// 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))? - }}; -} /// Dispatches the chosen monster action. -pub fn monsters_dispatch(args: &MonsterConfig, _config: &Config) -> Result<()> { +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))?; - fetch_all_data(connection)?; + let all_monsters = fetch_all_data(connection)?; + let table_end = &config.monster.intro; + let mut template = Handlebars::new(); + template + .register_template_string("intro", &config.monster.intro) + .context("Registering intro template")?; + + let mut data = BTreeMap::new(); + data.insert("calamity", "Bob"); + println!( + "{:#}", + template.render("intro", &all_monsters[0].data).unwrap() + ); // match args.target { // MonsterTarget::Clean => todo!("implement cleaning logic"), // MonsterTarget::Export => todo!("implement export logic"), @@ -56,91 +54,3 @@ pub fn monsters_dispatch(args: &MonsterConfig, _config: &Config) -> Result<()> { // } Ok(()) } - -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, attack_type, name") - ); - 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(); - - finished_creatures.push(FullMonster { - id: creature.id, - name: creature.name.clone(), - stats: creature_stats, - attacks: MonsterAttacks { - attacks: creature_attacks, - }, - body_parts: monster_structs::CreatureBodyParts { - body_parts: creature_resistances, - }, - data: creature.clone(), - }); - } - 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_database.rs b/crates/monsters/src/monster_database.rs index f9da2c4..cd920b9 100644 --- a/crates/monsters/src/monster_database.rs +++ b/crates/monsters/src/monster_database.rs @@ -1 +1,111 @@ #![allow(dead_code)] + +use crate::monster_structs; +use crate::monster_structs::{ + CreatureBodyPart, CreatureData, CreatureStats, FullMonster, MonsterAttacks, 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, attack_type, name") + ); + 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(); + + finished_creatures.push(FullMonster { + id: creature.id, + name: creature.name.clone(), + stats: creature_stats, + attacks: MonsterAttacks { + attacks: creature_attacks, + }, + body_parts: monster_structs::CreatureBodyParts { + body_parts: creature_resistances, + }, + data: creature.clone(), + }); + } + 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 index 317cfc8..590fcf3 100644 --- a/crates/monsters/src/monster_export.rs +++ b/crates/monsters/src/monster_export.rs @@ -1,4 +1,5 @@ //! Monster export module +use serde::Deserialize; pub trait ToTex { fn export_to_tex(self) -> String; diff --git a/helper_config.toml b/helper_config.toml index cfb250a..51c8e8e 100644 --- a/helper_config.toml +++ b/helper_config.toml @@ -146,3 +146,138 @@ 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} \\ +{{rewards}} +\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 +\SetCell{font=\footnotesize} Tête & $(s1)$ & $(p1)$ & \SetCell{r,f}\tiny$(i1)$ & \SetCell{r,f}\tiny$(h1)$ & $(s2)$ & $(p2)$ & \SetCell{r,f}\tiny$(i2)$ & \SetCell{r,f}\tiny$(h2)$\\ +''' +body_parts_row=''' \SetCell{font=\footnotesize} Corps & $3$ & $3$ & \SetCell{r,f}\tiny$999$ & \SetCell{r,f}\tiny$999$ & $3$ & $3$ & \SetCell{r,f}\tiny$999$ & \SetCell{r,f}\tiny$999$\\ +\SetCell{font=\footnotesize} M AvD & $3$ & $3$ & \SetCell{r,f}\tiny$999$ & \SetCell{r,f}\tiny$999$ & $3$ & $3$ & \SetCell{r,f}\tiny$999$ & \SetCell{r,f}\tiny$999$\\ +\SetCell{font=\footnotesize} M AvG & $3$ & $3$ & \SetCell{r,f}\tiny$999$ & \SetCell{r,f}\tiny$999$ & $3$ & $3$ & \SetCell{r,f}\tiny$999$ & \SetCell{r,f}\tiny$999$\\ +\SetCell{font=\footnotesize} M ArD & $3$ & $3$ & \SetCell{r,f}\tiny$999$ & \SetCell{r,f}\tiny$999$ & $3$ & $3$ & \SetCell{r,f}\tiny$999$ & \SetCell{r,f}\tiny$999$\\ +\SetCell{font=\footnotesize} M ArG & $3$ & $3$ & \SetCell{r,f}\tiny$999$ & \SetCell{r,f}\tiny$999$ & $3$ & $3$ & \SetCell{r,f}\tiny$999$ & \SetCell{r,f}\tiny$999$\\ +\SetCell{font=\footnotesize} Queue & $3$ & $3$ & \SetCell{r,f}\tiny$999$ & \SetCell{r,f}\tiny$999$ & $3$ & $3$ & \SetCell{r,f}\tiny$999$ & \SetCell{r,f}\tiny$999$\\ +\SetCell{font=\footnotesize} Aile G & $3$ & $3$ & \SetCell{r,f}\tiny$999$ & \SetCell{r,f}\tiny$999$ & $3$ & $3$ & \SetCell{r,f}\tiny$999$ & \SetCell{r,f}\tiny$999$\\ +\SetCell{font=\footnotesize} Aile D & $3$ & $3$ & \SetCell{r,f}\tiny$999$ & \SetCell{r,f}\tiny$999$ & $3$ & $3$ & \SetCell{r,f}\tiny$999$ & \SetCell{r,f}\tiny$999$\\ +''' +body_parts_end= ''' \hline +\SetCell[c=9]{j,h} {\textbf{Notes} \\ \lipsum[11][1-5]}\\ +\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} Tête & $+$ & $+$ & $+$ & $+$ & $+$ & $+$ & $+$ & $+$ & $+++$ & $---$ & $+$ & $--$ & $+$ \\''' +resist_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 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 & & & & & \SetCell[c=3]{c} Sang\\ + \cline{2-3} \cline{4-5} \cline{7-13} \cline{15-18} \cline{20-23} +\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} & & \rb{Base} & \rb{Combat} & \rb{Dépeçage}\\ +\SetCell{font=\footnotesize}$1$ & $20$ & $4$A & $22$ & $4$A & & $990$ & $991$ & $992$ & $993$ & $994$ & $995$ & $996$ & & $997$ & $998$ & $999$ & $111$ & & $20$ & $5$ & $7$ \\ +\SetCell{font=\footnotesize}$2$ & $15$ & $3$A & $17$ & $3$A \\ +\SetCell{font=\footnotesize}$3$ & $10$ & $2$A & $12$ & $2$A \\ +\SetCell{font=\footnotesize}$4$ & $5$ & $1$A & $7$ & $1$A \\ +\end{tblr} +} +\vfill ''' # Warn, annoying init +attacks_intro= '''\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 \\ +\lipsum[10] & \lipsum[15][1-3] \\ +\end{tblr} + +\vfill + +\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 1 & & & & & & & & & & \\ +''' +attack_repeatable_row= ''' \hline +\SetCell[r=2]{bg=ravred} & Thunder Bolt & THB & ATK & S & 2 & 2 & \symthunder & 3 & 18 25 32 & AB1 AB2 & 2 & 4 \\ +''' +attack_info_row=''' +& \SetCell[c=12]{j} \lipsum[7][1-6] & & & & & & & & & & \\ +\hline +''' +attacks_end= ''' \end{tblr} +} +\vfill +\renewcommand{\rb}{\undefined} +''' diff --git a/ravenous_databases b/ravenous_databases index 9667d60..dd0e1eb 160000 --- a/ravenous_databases +++ b/ravenous_databases @@ -1 +1 @@ -Subproject commit 9667d600d45589b7ece90114d99862bb4f14c58c +Subproject commit dd0e1eba2cf34521dfdccbe84b2cf71cd851e9e9 -- 2.45.1 From f86199d4975427fd6a76d22d3b33582c3ca50b82 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Thu, 16 Jul 2026 01:53:32 +0200 Subject: [PATCH 6/9] All but the attacks --- crates/config/src/monsters.rs | 66 ++++++++---- crates/monsters/src/lib.rs | 91 +++++++++++++--- crates/monsters/src/monster_database.rs | 19 +++- crates/monsters/src/monster_structs.rs | 131 ++++++++++++++++++++++-- helper_config.toml | 87 ++++++++-------- ravenous_databases | 2 +- 6 files changed, 305 insertions(+), 91 deletions(-) diff --git a/crates/config/src/monsters.rs b/crates/config/src/monsters.rs index 5cec993..c1e7da8 100644 --- a/crates/config/src/monsters.rs +++ b/crates/config/src/monsters.rs @@ -32,44 +32,66 @@ pub enum MonsterTarget { Show, } -/// The config data in .toml +/// 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 { - /// Intro – the very first chunk of LaTeX that starts a monster page. + /// Header of the page (image + basic attributes). pub intro: String, - // ──────────────────────── BODY‑PART TABLE ──────────────────────── // - /// Opening `` tag and any pre‑header rows for the body‑part table + /// Body‑parts section header. pub body_parts_intro: String, - /// One row per body part (e.g. “Tête”, “Corps”). Use `{}` placeholders if you need dynamic values. + + /// One row of the body‑parts table. pub body_parts_row: String, - /// Closing `\hline`/`\end{tblr}` tags for the body‑part table + + /// Body‑parts table footer. pub body_parts_end: String, - // ──────────────────────── RESISTANCE TABLE ────────────────────── // - /// Opening tag & any header rows before the resistance rows - pub resists_intro: String, - /// One row per resistance type (e.g. “Slashing”, “Fire”) - pub resists_row: String, - /// Closing `\hline`/`\end{tblr}` tags for the resistance table - pub resist_end: String, + /// Rewards section header (the table that lists each reward). + pub rewards_row: String, - // ──────────────────────── STATS BLOCK ───────────────────────── // - /// The whole stat block (body‑part thresholds, protection, HP…) + /// 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, - // ──────────────────────── ATTACK LIST ─────────────────────── // - /// Opening `` tag & header rows for the action list + /// 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, - /// Closing `\hline`/`\end{tblr}` tags for the action list + + /// Footer of the attacks section. pub attacks_end: String, - // ──────────────────────── PHASE TABLES ─────────────────────── // - /// One row per “phase” of the monster’s combat routine + /// Row used for each attack’s data (IDs, types, damage, etc.). pub phase_row: String, - /// A repeatable action row (used inside a phase) + + /// Row that lists repeatable attacks. pub attack_repeatable_row: String, - /// An informational row that expands on the current action + + /// Row that contains additional information for an attack. pub attack_info_row: String, + + /// The intent table & Battle plan + pub intent_table: String, } diff --git a/crates/monsters/src/lib.rs b/crates/monsters/src/lib.rs index 11441f9..0307ab4 100644 --- a/crates/monsters/src/lib.rs +++ b/crates/monsters/src/lib.rs @@ -13,8 +13,8 @@ //! (`MonsterConfig`) and delegates to the appropriate sub‑routine (clean, export or show). //! -use crate::monster_database::fetch_all_data; -use std::collections::BTreeMap; +use crate::{monster_database::fetch_all_data, monster_structs::MonsterRepetableInitRow}; +use std::fmt::Write; use anyhow::Context; use handlebars::Handlebars; @@ -27,6 +27,24 @@ use cli_parser::Config; use config::monsters::MonsterConfig; use rusqlite::Connection; +/// 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 + }}; +} + +// TODO: Create a method on the struct instead of this inane bs /// Dispatches the chosen monster action. pub fn monsters_dispatch(args: &MonsterConfig, config: &Config) -> Result<()> { // use config::monsters::MonsterTarget; @@ -35,18 +53,65 @@ pub fn monsters_dispatch(args: &MonsterConfig, config: &Config) -> Result<()> { Connection::open(&args.database).context(format!("Opening database {}", args.database))?; let all_monsters = fetch_all_data(connection)?; - let table_end = &config.monster.intro; - let mut template = Handlebars::new(); - template - .register_template_string("intro", &config.monster.intro) - .context("Registering intro template")?; + 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, intent_table); - let mut data = BTreeMap::new(); - data.insert("calamity", "Bob"); - println!( - "{:#}", - template.render("intro", &all_monsters[0].data).unwrap() - ); + 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)?)?; + } + + // write!(out, "{}", &config.monster.attacks_intro)?; + + // write!(out, "{}", &config.monster.attacks_end)?; + // write!(out, "{}", templates.render("intent_table", &creature.data)?)?; + + println!("{}", out); + // templates // match args.target { // MonsterTarget::Clean => todo!("implement cleaning logic"), // MonsterTarget::Export => todo!("implement export logic"), diff --git a/crates/monsters/src/monster_database.rs b/crates/monsters/src/monster_database.rs index cd920b9..dc4d397 100644 --- a/crates/monsters/src/monster_database.rs +++ b/crates/monsters/src/monster_database.rs @@ -1,8 +1,9 @@ #![allow(dead_code)] -use crate::monster_structs; +use crate::monster_structs::{self, CreatureReward}; use crate::monster_structs::{ - CreatureBodyPart, CreatureData, CreatureStats, FullMonster, MonsterAttacks, MonsterSingleAttack, + CreatureBodyPart, CreatureData, CreatureListAttacks, CreatureStats, FullMonster, + MonsterSingleAttack, }; use anyhow::{Context, anyhow}; use rusqlite::Connection; @@ -54,17 +55,27 @@ pub(crate) fn fetch_all_data(connection: Connection) -> Result, }; 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: MonsterAttacks { + attacks: CreatureListAttacks { attacks: creature_attacks, }, - body_parts: monster_structs::CreatureBodyParts { + body_parts: monster_structs::CreatureListBodyParts { body_parts: creature_resistances, }, data: creature.clone(), + rewards: monster_structs::CreatureListRewards { + rewards: creature_rewards, + }, }); } Ok(finished_creatures) diff --git a/crates/monsters/src/monster_structs.rs b/crates/monsters/src/monster_structs.rs index 99d72d4..f0a8b1a 100644 --- a/crates/monsters/src/monster_structs.rs +++ b/crates/monsters/src/monster_structs.rs @@ -11,6 +11,8 @@ //! ``` //! #![allow(dead_code)] +use std::iter::Zip; + use more_fields::FieldsAsSlice; use serde::{Deserialize, Serialize}; @@ -26,10 +28,13 @@ pub struct FullMonster { pub data: CreatureData, /// Collection of attacks, wrapped in a helper that exposes useful functions. - pub attacks: MonsterAttacks, + pub attacks: CreatureListAttacks, /// Collection of resistances, wrapped in a helper for convenient iteration. - pub body_parts: CreatureBodyParts, + 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, @@ -77,16 +82,36 @@ pub struct CreatureData { /// 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, - /// Problematic list of rewards - // TODO: FIX +} + +/// 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 rewards: String, + 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. @@ -94,7 +119,7 @@ pub struct CreatureData { /// 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 MonsterAttacks { +pub struct CreatureListAttacks { /// All attack rows for the monster, as read from the database. pub attacks: Vec, } @@ -104,7 +129,7 @@ pub struct MonsterAttacks { /// 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 CreatureBodyParts { +pub struct CreatureListBodyParts { /// All resistance rows for the monster, as read from the database. pub body_parts: Vec, } @@ -217,13 +242,13 @@ pub struct CreatureStats { #[INTEGER] pub creature_id: i64, #[TEXT] - pub p1_init: String, + pub p1_init: MonsterInitString, #[TEXT] - pub p2_init: String, + pub p2_init: MonsterInitString, #[TEXT] - pub p1_actions: String, + pub p1_actions: MonsterInitString, #[TEXT] - pub p2_actions: String, + pub p2_actions: MonsterInitString, #[INTEGER] pub strength: i64, #[INTEGER] @@ -253,3 +278,87 @@ pub struct CreatureStats { #[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)), + ) + } +} + +// impl From<&str> for CustomString { +// fn from(value: &str) -> Self { +// Self { +// inner: value.to_string(), +// } +// } +// } diff --git a/helper_config.toml b/helper_config.toml index 51c8e8e..616da90 100644 --- a/helper_config.toml +++ b/helper_config.toml @@ -179,11 +179,24 @@ Mœurs & \SetCell{font=\footnotesize} {{habits}} \\ \textbf{Annotations} \\ {{annotations}} \\ \textbf{Récompenses} \\ -{{rewards}} \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[]}, @@ -197,19 +210,10 @@ body_parts_intro=''' & P1 & & & & P2 & \\ & Seuil & Prot & Intégrité & PV & Seuil & Prot & Intégrité & PV\\ \hline -\SetCell{font=\footnotesize} Tête & $(s1)$ & $(p1)$ & \SetCell{r,f}\tiny$(i1)$ & \SetCell{r,f}\tiny$(h1)$ & $(s2)$ & $(p2)$ & \SetCell{r,f}\tiny$(i2)$ & \SetCell{r,f}\tiny$(h2)$\\ -''' -body_parts_row=''' \SetCell{font=\footnotesize} Corps & $3$ & $3$ & \SetCell{r,f}\tiny$999$ & \SetCell{r,f}\tiny$999$ & $3$ & $3$ & \SetCell{r,f}\tiny$999$ & \SetCell{r,f}\tiny$999$\\ -\SetCell{font=\footnotesize} M AvD & $3$ & $3$ & \SetCell{r,f}\tiny$999$ & \SetCell{r,f}\tiny$999$ & $3$ & $3$ & \SetCell{r,f}\tiny$999$ & \SetCell{r,f}\tiny$999$\\ -\SetCell{font=\footnotesize} M AvG & $3$ & $3$ & \SetCell{r,f}\tiny$999$ & \SetCell{r,f}\tiny$999$ & $3$ & $3$ & \SetCell{r,f}\tiny$999$ & \SetCell{r,f}\tiny$999$\\ -\SetCell{font=\footnotesize} M ArD & $3$ & $3$ & \SetCell{r,f}\tiny$999$ & \SetCell{r,f}\tiny$999$ & $3$ & $3$ & \SetCell{r,f}\tiny$999$ & \SetCell{r,f}\tiny$999$\\ -\SetCell{font=\footnotesize} M ArG & $3$ & $3$ & \SetCell{r,f}\tiny$999$ & \SetCell{r,f}\tiny$999$ & $3$ & $3$ & \SetCell{r,f}\tiny$999$ & \SetCell{r,f}\tiny$999$\\ -\SetCell{font=\footnotesize} Queue & $3$ & $3$ & \SetCell{r,f}\tiny$999$ & \SetCell{r,f}\tiny$999$ & $3$ & $3$ & \SetCell{r,f}\tiny$999$ & \SetCell{r,f}\tiny$999$\\ -\SetCell{font=\footnotesize} Aile G & $3$ & $3$ & \SetCell{r,f}\tiny$999$ & \SetCell{r,f}\tiny$999$ & $3$ & $3$ & \SetCell{r,f}\tiny$999$ & \SetCell{r,f}\tiny$999$\\ -\SetCell{font=\footnotesize} Aile D & $3$ & $3$ & \SetCell{r,f}\tiny$999$ & \SetCell{r,f}\tiny$999$ & $3$ & $3$ & \SetCell{r,f}\tiny$999$ & \SetCell{r,f}\tiny$999$\\ ''' +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} \\ \lipsum[11][1-5]}\\ +\SetCell[c=9]{j,h} {\textbf{Notes} \\ {{annotations_master}}\\ \hline \end{tblr}''' resists_intro=''' \center{ @@ -222,38 +226,28 @@ resists_intro=''' \center{ \SetCell{c} Res & \slash & \pierce & \blunt & \symceleste & \symfire & \symearth & \symwood & \symmagma & \symabyss & \symwater & \symwind & \symice & \symthunder \\ \hline ''' -resists_row= ''' \SetCell{font=\footnotesize} Tête & $+$ & $+$ & $+$ & $+$ & $+$ & $+$ & $+$ & $+$ & $+++$ & $---$ & $+$ & $--$ & $+$ \\''' -resist_end=' \end{tblr} ' +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 c c c c}, - row{2}={font=\footnotesize}, - row{3-6}={font=\tiny}, +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 & & & & & \SetCell[c=3]{c} Sang\\ - \cline{2-3} \cline{4-5} \cline{7-13} \cline{15-18} \cline{20-23} -\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} & & \rb{Base} & \rb{Combat} & \rb{Dépeçage}\\ -\SetCell{font=\footnotesize}$1$ & $20$ & $4$A & $22$ & $4$A & & $990$ & $991$ & $992$ & $993$ & $994$ & $995$ & $996$ & & $997$ & $998$ & $999$ & $111$ & & $20$ & $5$ & $7$ \\ -\SetCell{font=\footnotesize}$2$ & $15$ & $3$A & $17$ & $3$A \\ -\SetCell{font=\footnotesize}$3$ & $10$ & $2$A & $12$ & $2$A \\ -\SetCell{font=\footnotesize}$4$ & $5$ & $1$A & $7$ & $1$A \\ + & \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 ''' # Warn, annoying init -attacks_intro= '''\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 \\ -\lipsum[10] & \lipsum[15][1-3] \\ -\end{tblr} - -\vfill - -\scriptsize{ +\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, @@ -281,3 +275,16 @@ 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 +''' diff --git a/ravenous_databases b/ravenous_databases index dd0e1eb..bdcf919 160000 --- a/ravenous_databases +++ b/ravenous_databases @@ -1 +1 @@ -Subproject commit dd0e1eba2cf34521dfdccbe84b2cf71cd851e9e9 +Subproject commit bdcf919c1066f5b175eb9c6896539fea72d03368 -- 2.45.1 From 08a66bf2b8b32ec7d5252e3c1859d54172a4bc2a Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Thu, 16 Jul 2026 02:08:43 +0200 Subject: [PATCH 7/9] Refactor export --- crates/monsters/src/lib.rs | 82 +------------------- crates/monsters/src/monster_export.rs | 101 ++++++++++++++++++++++++- crates/monsters/src/monster_structs.rs | 9 --- 3 files changed, 102 insertions(+), 90 deletions(-) diff --git a/crates/monsters/src/lib.rs b/crates/monsters/src/lib.rs index 0307ab4..21ae410 100644 --- a/crates/monsters/src/lib.rs +++ b/crates/monsters/src/lib.rs @@ -13,11 +13,9 @@ //! (`MonsterConfig`) and delegates to the appropriate sub‑routine (clean, export or show). //! -use crate::{monster_database::fetch_all_data, monster_structs::MonsterRepetableInitRow}; -use std::fmt::Write; +use crate::monster_export::generate_monsters_tex; use anyhow::Context; -use handlebars::Handlebars; mod monster_database; mod monster_export; pub mod monster_structs; @@ -27,24 +25,6 @@ use cli_parser::Config; use config::monsters::MonsterConfig; use rusqlite::Connection; -/// 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 - }}; -} - -// TODO: Create a method on the struct instead of this inane bs /// Dispatches the chosen monster action. pub fn monsters_dispatch(args: &MonsterConfig, config: &Config) -> Result<()> { // use config::monsters::MonsterTarget; @@ -52,65 +32,7 @@ pub fn monsters_dispatch(args: &MonsterConfig, config: &Config) -> Result<()> { let connection = Connection::open(&args.database).context(format!("Opening database {}", args.database))?; - let all_monsters = fetch_all_data(connection)?; - 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, intent_table); - - 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)?)?; - } - - // write!(out, "{}", &config.monster.attacks_intro)?; - - // write!(out, "{}", &config.monster.attacks_end)?; - // write!(out, "{}", templates.render("intent_table", &creature.data)?)?; - - println!("{}", out); + generate_monsters_tex(args, config, connection)?; // templates // match args.target { // MonsterTarget::Clean => todo!("implement cleaning logic"), diff --git a/crates/monsters/src/monster_export.rs b/crates/monsters/src/monster_export.rs index 590fcf3..7daca75 100644 --- a/crates/monsters/src/monster_export.rs +++ b/crates/monsters/src/monster_export.rs @@ -1,6 +1,105 @@ //! Monster export module -use serde::Deserialize; + +use anyhow::{Context, Result}; +use cli_parser::Config; +use config::monsters::MonsterConfig; +use handlebars::Handlebars; +use rusqlite::Connection; +use std::fmt::Write; + +use crate::{monster_database::fetch_all_data, monster_structs::MonsterRepetableInitRow}; + +/// 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, 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)?)?; + } + + // write!(out, "{}", &config.monster.attacks_intro)?; + + // write!(out, "{}", &config.monster.attacks_end)?; + // write!(out, "{}", templates.render("intent_table", &creature.data)?)?; + + println!("{}", out); + Ok(()) +} diff --git a/crates/monsters/src/monster_structs.rs b/crates/monsters/src/monster_structs.rs index f0a8b1a..6b53b0b 100644 --- a/crates/monsters/src/monster_structs.rs +++ b/crates/monsters/src/monster_structs.rs @@ -11,7 +11,6 @@ //! ``` //! #![allow(dead_code)] -use std::iter::Zip; use more_fields::FieldsAsSlice; use serde::{Deserialize, Serialize}; @@ -354,11 +353,3 @@ impl Serialize for MonsterInitString { ) } } - -// impl From<&str> for CustomString { -// fn from(value: &str) -> Self { -// Self { -// inner: value.to_string(), -// } -// } -// } -- 2.45.1 From 572ad159a2b60e1ac224bee5233500ffddc1930e Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Thu, 16 Jul 2026 05:35:37 +0200 Subject: [PATCH 8/9] Hideous hack Maybe some clean tomorrow --- Cargo.toml | 1 + crates/config/Cargo.toml | 2 + crates/config/src/monsters.rs | 57 +++++++- crates/make/Cargo.toml | 2 +- crates/monsters/Cargo.toml | 7 +- crates/monsters/src/monster_database.rs | 2 +- crates/monsters/src/monster_export.rs | 169 +++++++++++++++++++----- crates/monsters/src/monster_structs.rs | 23 +++- helper_config.toml | 16 ++- ravenous_databases | 2 +- 10 files changed, 231 insertions(+), 50 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index a467453..44dfdae 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -56,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/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/monsters.rs b/crates/config/src/monsters.rs index c1e7da8..663c02b 100644 --- a/crates/config/src/monsters.rs +++ b/crates/config/src/monsters.rs @@ -4,8 +4,10 @@ //! #![allow(dead_code)] +use anyhow::Result; use clap::{Args, ValueEnum}; -use serde::Deserialize; +use indexmap::IndexMap; +use serde::{Deserialize, Deserializer}; #[derive(Args, Debug, Clone)] /// The configuration struct for the Graph @@ -86,6 +88,12 @@ pub struct MonsterMarkup { /// 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, @@ -94,4 +102,51 @@ pub struct MonsterMarkup { /// 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/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 index e499a1f..00213a5 100644 --- a/crates/monsters/Cargo.toml +++ b/crates/monsters/Cargo.toml @@ -8,17 +8,12 @@ config = {workspace = true} cli_parser = {workspace = true} more_fields = {workspace = true} anyhow = {workspace = true} -# regex = {workspace = true} -# csv = {workspace = true} +indexmap = {workspace = true} serde = {workspace = true} -# comfy-table = "7.2.2" -# probability = "0.20.3" rusqlite = { version = "0.40.1" } # , features = ["bundled"] serde_rusqlite = "0.43.0" -# serde_json = { version = "1.0.150", features = ["alloc"] } strum = { version = "0.28.0", features = ["derive"] } handlebars = "6.4.3" -# charming = { version = "0.4.0", features = [] } [dev-dependencies] regex = {workspace = true} diff --git a/crates/monsters/src/monster_database.rs b/crates/monsters/src/monster_database.rs index dc4d397..450b67c 100644 --- a/crates/monsters/src/monster_database.rs +++ b/crates/monsters/src/monster_database.rs @@ -34,7 +34,7 @@ pub(crate) fn fetch_all_data(connection: Connection) -> Result, connection, creature, "creature_abilities", - Some("phase, attack_group, attack_type, name") + Some("phase, attack_group, attack_type") ); let creature_resistances = fetch_from!( CreatureBodyPart, diff --git a/crates/monsters/src/monster_export.rs b/crates/monsters/src/monster_export.rs index 7daca75..74f270b 100644 --- a/crates/monsters/src/monster_export.rs +++ b/crates/monsters/src/monster_export.rs @@ -4,10 +4,17 @@ use anyhow::{Context, Result}; use cli_parser::Config; use config::monsters::MonsterConfig; use handlebars::Handlebars; +use indexmap::IndexMap; use rusqlite::Connection; -use std::fmt::Write; +use serde::Serialize; +use std::{collections::HashMap, fmt::Write}; -use crate::{monster_database::fetch_all_data, monster_structs::MonsterRepetableInitRow}; +use crate::{ + monster_database::fetch_all_data, + monster_structs::{ + MonsterAllAttacks, MonsterFullAttack, MonsterRepetableInitRow, MonsterSingleAttack, + }, +}; /// Load a template from a struct field into a `templates` collection. /// @@ -40,6 +47,10 @@ fn load_templates(config: &Config) -> Result> { 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) } @@ -56,32 +67,32 @@ pub fn generate_monsters_tex( 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("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, @@ -95,11 +106,105 @@ pub fn generate_monsters_tex( write!(out, "{}", templates.render("init_rows", init)?)?; } - // write!(out, "{}", &config.monster.attacks_intro)?; + 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)?)?; + write!(out, "{}", &config.monster.attacks_end)?; + write!(out, "{}", templates.render("intent_table", &creature.data)?)?; - println!("{}", out); + // 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 index 6b53b0b..c3b2f6a 100644 --- a/crates/monsters/src/monster_structs.rs +++ b/crates/monsters/src/monster_structs.rs @@ -12,6 +12,7 @@ //! #![allow(dead_code)] +use indexmap::IndexMap; use more_fields::FieldsAsSlice; use serde::{Deserialize, Serialize}; @@ -159,16 +160,16 @@ pub struct MonsterSingleAttack { pub targetting: Option, /// Fatigue cost for activating the ability. #[INTEGER] - pub cost_fatigue: Option, + pub cost_fatigue: Option, /// Action‑point cost (used in systems where actions and fatigue are separate). #[INTEGER] - pub cost_action: Option, + 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, + pub damage_fatigue: Option, /// Regular textual description #[TEXT] pub damage_regular: Option, @@ -353,3 +354,19 @@ impl Serialize for MonsterInitString { ) } } + +/// 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/helper_config.toml b/helper_config.toml index 616da90..8ff4a0c 100644 --- a/helper_config.toml +++ b/helper_config.toml @@ -261,13 +261,14 @@ attacks_intro= '''\scriptsize{ ''' phase_row= ''' \SetHline{1}{0pt} -\SetCell[c=13]{white} PHASE 1 & & & & & & & & & & \\ +\SetCell[c=13]{white} {{phase_name}} & & & & & & & & & & \\ ''' -attack_repeatable_row= ''' \hline -\SetCell[r=2]{bg=ravred} & Thunder Bolt & THB & ATK & S & 2 & 2 & \symthunder & 3 & 18 25 32 & AB1 AB2 & 2 & 4 \\ + +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} \lipsum[7][1-6] & & & & & & & & & & \\ +attack_info_row='''& \SetCell[c=12]{j} {{description}} & & & & & & & & & & \\ \hline ''' attacks_end= ''' \end{tblr} @@ -288,3 +289,8 @@ Plan de combat & Graphique d'intentions \\ \end{tblr} \vfill ''' +color_table=''' + THB: \ravblue + TBD: \nocolor +''' +default_color='\blu' diff --git a/ravenous_databases b/ravenous_databases index bdcf919..211b22d 160000 --- a/ravenous_databases +++ b/ravenous_databases @@ -1 +1 @@ -Subproject commit bdcf919c1066f5b175eb9c6896539fea72d03368 +Subproject commit 211b22dbe327b66f0da9f5c5a780dd6ec00a88d8 -- 2.45.1 From 209c24aab2d3ee0a977a47f24e5c75490cc04b14 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Thu, 16 Jul 2026 17:31:42 +0200 Subject: [PATCH 9/9] Tries to have submodule on a https --- .gitmodules | 3 ++- crates/monsters/src/monster_database.rs | 2 +- crates/monsters/src/monster_export.rs | 2 +- 3 files changed, 4 insertions(+), 3 deletions(-) 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/crates/monsters/src/monster_database.rs b/crates/monsters/src/monster_database.rs index 450b67c..88e3bda 100644 --- a/crates/monsters/src/monster_database.rs +++ b/crates/monsters/src/monster_database.rs @@ -34,7 +34,7 @@ pub(crate) fn fetch_all_data(connection: Connection) -> Result, connection, creature, "creature_abilities", - Some("phase, attack_group, attack_type") + Some("phase, attack_group") ); let creature_resistances = fetch_from!( CreatureBodyPart, diff --git a/crates/monsters/src/monster_export.rs b/crates/monsters/src/monster_export.rs index 74f270b..c1336a0 100644 --- a/crates/monsters/src/monster_export.rs +++ b/crates/monsters/src/monster_export.rs @@ -7,7 +7,7 @@ use handlebars::Handlebars; use indexmap::IndexMap; use rusqlite::Connection; use serde::Serialize; -use std::{collections::HashMap, fmt::Write}; +use std::fmt::Write; use crate::{ monster_database::fetch_all_data, -- 2.45.1