Working on the template

This commit is contained in:
Dandaedre 2026-07-15 20:22:40 +02:00
parent 37a6531ae4
commit 006ebe9a0b
Signed by: Dandaedre
GPG Key ID: 440C6592E8A26D99
9 changed files with 314 additions and 112 deletions

View File

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

View File

@ -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 `<tblr>` 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 `<tblr>` 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,
}

View File

@ -31,7 +31,7 @@ pub struct TableArgs {
pub filenames: Vec<String>,
}
// 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

View File

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

View File

@ -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<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!(
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<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

@ -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<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!(
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<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

@ -1,4 +1,5 @@
//! Monster export module
use serde::Deserialize;
pub trait ToTex {
fn export_to_tex(self) -> String;

View File

@ -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}
'''

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