From 46b8e3525415dff4b8f7ac53c5cd98b001c4d4ac Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Wed, 15 Jul 2026 19:00:09 +0200 Subject: [PATCH] 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