Partial commit before a refactor

This commit is contained in:
Dandaedre 2026-07-15 19:00:09 +02:00
parent 1e0c6dfb53
commit 46b8e35254
Signed by: Dandaedre
GPG Key ID: 440C6592E8A26D99
7 changed files with 360 additions and 19 deletions

View File

@ -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,

View File

@ -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"]

View File

@ -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<Vec<FullMonster>, anyhow::Error> {
let list_creatures =
generic_deserialize::<CreatureData>(&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<T: more_fields::FieldsAsSlice + DeserializeOwned>(
connection: &Connection,
table_name: &str,
filter: Option<&str>,
sort: Option<&str>,
) -> Result<Vec<T>, anyhow::Error> {
let info = format!(
"Querying data on {} with {} WHERE {:?} ORDER BY {:?}",
table_name,
std::any::type_name::<T>(),
filter,
sort,
);
let generate_select_query = generate_select_query::<T>(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::<T>(rows).collect::<Result<Vec<T>, serde_rusqlite::Error>>();
r.context("No")
}
fn generate_select_query<T: more_fields::FieldsAsSlice>(
table_name: &str,
filter: Option<&str>,
sort: Option<&str>,
) -> String {
format!(
"SELECT {} FROM {}{}{};",
T::attributes_slice()
.iter()
.map(|(k, _v)| k.to_owned())
.collect::<Vec<_>>()
.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)
)
}

View File

@ -0,0 +1 @@
#![allow(dead_code)]

View File

@ -0,0 +1,5 @@
//! Monster export module
pub trait ToTex {
fn export_to_tex(self) -> String;
}

View File

@ -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<MonsterSingleResistance>,
pub resistances: Vec<CreatureResistance>,
}
/// 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<String>,
/// Ability “type” as a trigram
#[TEXT]
pub attack_type: String,
/// How the ability targets opponents (e.g. “single”, “area” …).
#[TEXT]
pub targetting: Option<String>,
/// Fatigue cost for activating the ability.
#[INTEGER]
pub cost_fatigue: Option<i64>,
/// Action‑point cost (used in systems where actions and fatigue are separate).
#[INTEGER]
pub cost_action: Option<i64>,
/// Element or school that powers the ability.
#[TEXT]
pub element: Option<String>,
/// Damage dealt as a *fatigue* penalty (i.e. non‑instant death).
#[INTEGER]
pub damage_fatigue: Option<i64>,
/// Regular textual description
#[TEXT]
pub damage_regular: Option<String>,
/// 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<i64>,
/// Minimum dodge rating required to avoid the ability’s effect.
#[INTEGER]
pub threshold_dodge: Option<i64>,
}
#[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<String>,
#[TEXT]
pub blunt: Option<String>,
#[TEXT]
pub piercing: Option<String>,
#[TEXT]
pub celestial: Option<String>,
#[TEXT]
pub fire: Option<String>,
#[TEXT]
pub magma: Option<String>,
#[TEXT]
pub earth: Option<String>,
#[TEXT]
pub wood: Option<String>,
#[TEXT]
pub abyssal: Option<String>,
#[TEXT]
pub wind: Option<String>,
#[TEXT]
pub water: Option<String>,
#[TEXT]
pub ice: Option<String>,
#[TEXT]
pub thunder: Option<String>,
}
#[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<i64>,
#[INTEGER]
pub threshold_p2: Option<i64>,
#[INTEGER]
pub protection_p1: Option<i64>,
#[INTEGER]
pub protection_p2: Option<i64>,
#[INTEGER]
pub integrity_p1: Option<i64>,
#[INTEGER]
pub integrity_p2: Option<i64>,
#[INTEGER]
pub life_points_p1: Option<i64>,
#[INTEGER]
pub life_points_p2: Option<i64>,
}
#[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<i64>,
#[INTEGER]
pub blood_base: i64,
#[INTEGER]
pub blood_battle: i64,
#[INTEGER]
pub blood_carve: i64,
}

@ -1 +1 @@
Subproject commit ee3b7ffd5fa4e3bfbcd13cb5d69b9c0e3e9b06e5
Subproject commit 9667d600d45589b7ece90114d99862bb4f14c58c