database_monsters #131

Merged
Dandaedre merged 3 commits from database_monsters into main 2026-07-21 07:47:53 +02:00
32 changed files with 502 additions and 67 deletions

View File

@ -6,7 +6,7 @@ resolver = "3"
# edition = "2024"
# license = "MIT OR Apache-2.0"
[workspace.package]
version = "0.3.10"
version = "0.3.11"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
@ -60,3 +60,4 @@ pretty_assertions = "^1.4"
indexmap = {version= "2.14.0", features= ["serde"]}
rusqlite = { version = "0.40.1" } # , features = ["bundled"]
serde_rusqlite = "0.43.0"
handlebars = "6.4.3"

View File

@ -1,6 +1,6 @@
[package]
name = "cli_parser"
version = "0.1.7"
version.workspace = true
edition = "2024"
[dependencies]

View File

@ -4,12 +4,12 @@
use clap::{Args, Parser, Subcommand};
use config::{
analysis::AnalysisConfig,
analysis::{AnalysisConfig, WeaponConfig},
fast_tables::FastTableConfig,
formatter::FormatterConfig,
graph::GraphConfig,
make::{HELP_BLOCK_SELECTION, MakeTargets, VerboseLevel},
monsters::{MonsterConfig, MonsterMarkup},
monsters::{MonsterConfig, MonsterMarkup, WeaponExport},
statsolver::StatConfig,
tablegen::{Craft, TableArgs},
};
@ -47,6 +47,8 @@ pub enum Commands {
Format(FormatterConfig),
/// Generate analysis data
Analysis(AnalysisConfig),
/// Export all weapon data
Weapons(WeaponConfig),
/// Better Generation
BetterGen(FastTableConfig),
/// Monster database handling
@ -79,6 +81,8 @@ pub struct Config {
pub craft: Craft,
/// Config for monster exporting
pub monster: MonsterMarkup,
/// The config for weapon exporting
pub weapons: WeaponExport,
}
#[derive(Deserialize)]

View File

@ -1,6 +1,6 @@
[package]
name = "config"
version = "0.1.1"
version.workspace = true
edition = "2024"
[dependencies]

View File

@ -42,6 +42,21 @@ pub struct AnalysisConfig {
// - average per category
}
#[derive(Parser, Debug)]
/// Basic weapon generation
pub struct WeaponConfig {
#[arg(help = format!("The target to perform an analysis on [{:?}]", AnalysisTarget::value_variants()))]
/// The analysis target
pub target: ExportTarget,
/// The path to export to
#[arg(short, long, default_value = "./Craft")]
pub export: String,
#[arg(long, default_value_t = String::from("safe"))]
/// What function to sort by
pub sort: String,
}
#[derive(ValueEnum, Clone, Debug)]
/// The type of analysis to perform
pub enum AnalysisTarget {
@ -52,3 +67,10 @@ pub enum AnalysisTarget {
/// Analysis over shields
Shields,
}
#[derive(ValueEnum, Clone, Debug)]
/// The type of generation to perform
pub enum ExportTarget {
/// Generate all
All,
}

View File

@ -70,6 +70,13 @@ pub struct MonsterMarkup {
pub master_part: String,
}
#[derive(Deserialize)]
/// The configuration for the weapon exporting
pub struct WeaponExport {
/// The template to use
pub template: String,
}
/// Ghetto color import
pub struct MonsterColor {
/// Inner color

View File

@ -1,6 +1,6 @@
[package]
name = "fast_class"
version = "0.1.0"
version.workspace = true
edition = "2024"
[dependencies]

View File

@ -1,6 +1,6 @@
[package]
name = "formatter"
version = "0.1.1"
version.workspace = true
edition = "2024"
[dependencies]

View File

@ -1,6 +1,6 @@
[package]
name = "graphs"
version = "0.1.4"
version.workspace = true
edition = "2024"
[dependencies]

View File

@ -1,6 +1,6 @@
[package]
name = "make"
version = "0.1.2"
version.workspace = true
edition = "2024"
[dependencies]

View File

@ -1,6 +1,6 @@
[package]
name = "monsters"
version = "0.1.1"
version.workspace = true
edition = "2024"
[dependencies]
@ -13,8 +13,8 @@ serde = {workspace = true}
rusqlite = {workspace = true}
serde_rusqlite = {workspace = true}
serde_json = {workspace = true}
handlebars = {workspace = true}
strum = { version = "0.28.0", features = ["derive"] }
handlebars = "6.4.3"
[dev-dependencies]
regex = {workspace = true}

View File

@ -28,10 +28,6 @@ macro_rules! template_load {
}};
}
// pub trait ToTex {
// fn export_to_tex(self) -> String;
// }
handlebars_helper!(plus: |x:i64 ,y:Option<i64>| x+y.unwrap_or(0));
fn load_templates(config: &Config) -> Result<Handlebars<'_>> {

View File

@ -69,6 +69,9 @@ pub struct CreatureData {
/// The HSE danger level
#[INTEGER]
pub danger_level: i64,
/// The footprints and such
#[TEXT]
pub traces: Option<String>,
/// Type of habitat
#[TEXT]
pub habitat: Option<String>,
@ -271,6 +274,81 @@ pub struct CreatureBodyPart {
pub thunder: Option<String>,
}
/// Convenient wrapper to allow fetching easily resists to show
pub struct GroupedResists {
inner: IndexMap<String, Vec<Option<String>>>,
}
/// Counts how many items in `list` have a **Some** value for the given `field`.
///
/// # Example
/// ```
/// let pierced = count_present!(part_list, piercing);
/// ```
// macro_rules! count_present {
// ($list:expr, $field:ident) => {
// // We keep everything inside its own block so that it behaves like a single expression.
// let $field = $list
// .body_parts
// .iter()
// .filter(|v| v.$field.is_some())
// .count();
// };
// }
// impl GroupedResists {
// pub fn from_list_body_parts(part_list: CreatureListBodyParts) -> Self {
// let mut inner: IndexMap<String, Vec<Option<String>>> = IndexMap::new();
// count_present!(part_list, slash);
// count_present!(part_list, blunt);
// count_present!(part_list, piercing);
// count_present!(part_list, celestial);
// count_present!(part_list, fire);
// count_present!(part_list, magma);
// count_present!(part_list, earth);
// count_present!(part_list, wood);
// count_present!(part_list, abyssal);
// count_present!(part_list, wind);
// count_present!(part_list, water);
// count_present!(part_list, ice);
// count_present!(part_list, thunder);
// if slash > 0 {
// for part in part_list.body_parts {
// let key = &part.body_part_name;
// if let Some(values) = inner.get_mut(key) {
// let value = part_list.get(key).to_owned();
// values.push(value);
// }
// println!("{}", part.body_part_name);
// println!("{}", slash);
// }
// }
// // for elt in &[
// // "slash",
// // "blunt",
// // "piercing",
// // "celestial",
// // "fire",
// // "magma",
// // "earth",
// // "wood",
// // "abyssal",
// // "wind",
// // "water",
// // "ice",
// // "thunder",
// // ] {}
// // if slash > 0 { // inner.insert(
// // "slash".to_string(),
// // part_list
// // .body_parts
// // .iter()
// // .map(|v| v.slash.clone())
// // .collect(),
// // );
// // }
// Self { inner }
// }
// }
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, FieldsAsSlice)]
/// All creature stats
pub struct CreatureStats {

View File

@ -13,7 +13,7 @@ use make::make_pdf;
use monsters::monsters_dispatch;
use stats::stat_solver;
use tablegen::table_gen;
use weaponry::analysis::launch_analysis;
use weaponry::{analysis::launch_analysis, export_tex::export_weapons};
// External imports
use anyhow::{Context, Result};
@ -37,6 +37,7 @@ fn main() -> Result<()> {
Commands::Graphs(args) => make_graphs(&args, &config),
Commands::Format(args) => format_file(&args, &config),
Commands::Analysis(args) => Ok(launch_analysis(&args, &config)?), // Not using anyhow but a custom error
Commands::Weapons(args) => Ok(export_weapons(&args, &config)?), // Not using anyhow but a custom error
Commands::BetterGen(args) => make_better_gen(&args, &config),
Commands::Monsters(args) => monsters_dispatch(&args, &config),
}

View File

@ -1,6 +1,6 @@
[package]
name = "stats"
version = "0.1.1"
version.workspace = true
edition = "2024"
[dependencies]

View File

@ -1,6 +1,6 @@
[package]
name = "tablegen"
version = "0.1.2"
version.workspace = true
edition = "2024"
[dependencies]

View File

@ -1,6 +1,6 @@
[package]
name = "weaponry"
version = "0.1.1"
version.workspace = true
edition = "2024"
[dependencies]
@ -15,6 +15,7 @@ probability = "0.20.3"
rusqlite = {workspace = true}
serde_rusqlite = {workspace = true}
serde_json = {workspace = true}
handlebars = {workspace = true}
strum = { version = "0.28.0", features = ["derive"] }
thiserror = "2.0.18"
charming = { version = "0.4.0", features = [] }

View File

@ -103,7 +103,7 @@ fn export_as_csv(refined_list: &RefinedEquipementList, save_path: &str) {
type DynamicFilterType = Box<dyn FnMut(&RefinedEquipement, &RefinedEquipement) -> Ordering>;
fn cmd_to_filter(og_entry: &str) -> Result<DynamicFilterType, FatalEquipementError> {
pub fn cmd_to_filter(og_entry: &str) -> Result<DynamicFilterType, FatalEquipementError> {
let (category, entry) = if og_entry.starts_with("cat+") {
(true, og_entry.split_at(4).1)
} else {

View File

@ -9,7 +9,7 @@ use config::analysis::AnalysisConfig;
use crate::{
error::FatalEquipementError,
interfaces::{Reportable, Scenario, ToAnalysis, ToCSV, ToTex},
interfaces::{Reportable, Scenario, ToAnalysis, ToCSV},
weaponry_structs::{
CrossRecipeScenario, RefinedEquipement, RefinedEquipementList,
equipement_scenario::ConfigEquipementScenario,
@ -81,14 +81,7 @@ fn create_graphs(args: &AnalysisConfig, config: &Config, filter: DynamicFilterTy
}
Err(e) => panic!("{e}"),
}
// if args.html_export{}
refined_list.write_html(&save_path).unwrap();
// if args.csv_export{}
// export_as_csv(&refined_list, &save_path);
// if args.tex_export{}
// export_as_tex(&refined_list, &save_path);
}
#[allow(dead_code)]
@ -103,20 +96,20 @@ fn export_as_csv(refined_list: &RefinedEquipementList, save_path: &str) {
refined_list.write_csv(Path::new(&format!("{save_path}.csv")))
);
}
/// Export as a tex file in the given directory
///
/// Generic function dispatching any specific demand to different functions
/// TODO: FINISH IMPLEMENTATION
#[allow(dead_code)]
fn export_as_tex(refined_list: &RefinedEquipementList, save_path: &str) {
let _ = save_path;
println!("{}", refined_list.to_tex()); // TexType
// println!(
// "Saved initial data as {}.html: {:?}",
// save_path,
// refined_list.write_csv(Path::new(&format!("{save_path}.csv")))
// );
}
// /// Export as a tex file in the given directory
// ///
// /// Generic function dispatching any specific demand to different functions
// /// TODO: FINISH IMPLEMENTATION
// #[allow(dead_code)]
// fn export_as_tex(refined_list: &RefinedEquipementList, config: &Config, save_path: &str) {
// let _ = save_path;
// println!("{}", refined_list.to_tex(config)); // TexType
// // println!(
// // "Saved initial data as {}.html: {:?}",
// // save_path,
// // refined_list.write_csv(Path::new(&format!("{save_path}.csv")))
// // );
// }
/// A dynamic filtertype, as a boxed function over two equipement references
// #[allow(dead_code)]
@ -129,7 +122,7 @@ type DynamicFilterType = Box<dyn FnMut(&RefinedEquipement) -> bool>;
///
/// This informal implementation function as a mini language,
/// without any form of formalism, consistency or fixed API
fn cmd_to_filter(og_entry: &str) -> Result<DynamicSortType, FatalEquipementError> {
pub fn cmd_to_filter(og_entry: &str) -> Result<DynamicSortType, FatalEquipementError> {
let (category, entry) = if og_entry.starts_with("cat+") {
(true, og_entry.split_at(4).1)
} else {

View File

@ -21,6 +21,12 @@ pub enum FatalEquipementError {
#[error("Deserialisation from json failed : {0}")]
SerdeJSON(#[from] serde_json::Error),
#[error("Error making the template: {0}")]
TemplatingError(#[from] handlebars::TemplateError),
#[error("Error rendering the template: {0}")]
RenderError(#[from] handlebars::RenderError),
#[error(
"Deserialisation from json failed at line {line} on file {file} while trying to parse the value: {parsed_value}: {error}]"
)]
@ -47,6 +53,13 @@ pub enum FatalEquipementError {
SerdeRSQLite(#[from] serde_rusqlite::Error),
}
#[derive(Error, Debug)]
/// Generic error handling
pub enum WeaponGenerationError {
#[error("An unexpected error occured")]
Unexpected,
}
// #[derive(Error, Debug)]
// /// Recoverable error, all these error exist to signal a retry or another path that should be taken by the program
// pub enum LocalEquipementError {

View File

@ -0,0 +1,54 @@
// Workspace: weaponry
// File: weaponry/src/export_tex.rs
//! Module regrouping all generic function related to the exporting as tex
//!
use std::fs;
use std::io::Write;
use crate::interfaces::ToTex;
use crate::weaponry_structs::equipement_scenario::ConfigEquipementScenario;
use crate::{interfaces::Scenario, weaponry_structs::RefinedEquipementList};
use cli_parser::Config;
use config::analysis::WeaponConfig;
use crate::{error::WeaponGenerationError, weaponry_structs::CrossRecipeScenario};
/// Export as a tex file in the given directory
///
/// Generic function dispatching any specific demand to different functions
/// TODO: FINISH IMPLEMENTATION
pub fn export_as_tex(refined_list: &RefinedEquipementList, config: &Config, save_path: &str) {
let _ = save_path;
println!("{}", refined_list.to_tex(config).unwrap()); // TexType
// println!(
// "Saved initial data as {}.html: {:?}",
// save_path,
// refined_list.write_csv(Path::new(&format!("{save_path}.csv")))
// );
}
/// Export all weapon database as a tex data
pub fn export_weapons(args: &WeaponConfig, config: &Config) -> Result<(), WeaponGenerationError> {
let scenarios = CrossRecipeScenario::new_with_config(ConfigEquipementScenario {
table_name: "Equipements".into(),
db_path: config.data_generation.database.clone(),
shape: Some(()),
materials: None,
nature: Some(()), //(!args.no_natures).then_some(()),
finishing: None, //args.finishing.then_some(()),
})
.unwrap();
// let filter = Box::new(|_: &RefinedEquipement| true);
let refined_list = scenarios.generate_refined_recipes().unwrap();
// .inner_filter(filter);
let tex = refined_list.to_tex(config).unwrap();
let name = format!("{}gen-forge-table.tex", args.export);
println!("Writing to file {name}");
let mut f = fs::File::create(name).unwrap();
writeln!(f, "{}", tex).unwrap();
Ok(())
}

View File

@ -7,6 +7,7 @@
use std::{path::Path, rc::Rc};
use cli_parser::Config;
use more_fields::FieldsAsSlice;
use rusqlite::Connection;
use serde::{Serialize, de::DeserializeOwned};
@ -162,7 +163,7 @@ pub(crate) struct FilterFunction<T>(pub(super) FilterType<T>);
/// This element can be converted to tex
pub trait ToTex {
/// Export the object to a Tex string
fn to_tex(&self) -> String;
fn to_tex(&self, config: &Config) -> Result<String, FatalEquipementError>;
}
/// This element can be converted to a csv for further analysis

View File

@ -14,6 +14,7 @@ pub mod export;
pub mod interfaces;
#[macro_use]
pub mod weaponry_structs;
pub mod export_tex;
/// Signals the function running is unfinished
#[macro_export]

View File

@ -20,7 +20,8 @@ use crate::{
export::{initial_chart, initial_plot_chart},
interfaces::{RecipeCollection, RefinedList, ToAnalysis},
weaponry_structs::{
Equipement, InitialEquipementList,
Equipement, InitialEquipementList, WeaponBaseShape,
equipement_fields::WeaponBaseSize,
equipement_structs::InnerEquipementStats,
equipement_thin_types::{Dices, Precision},
},
@ -49,6 +50,88 @@ pub struct RefinedEquipementList {
pub inner: Vec<RefinedEquipement>,
}
#[allow(clippy::missing_docs_in_private_items)]
/// The exportable equipement minimum precalculated stats
#[derive(Serialize)]
pub struct ExportableEquipement {
pub name: String,
pub category: Option<WeaponBaseShape>,
pub maniement: String,
pub damage_base: i8,
pub damage_per: i8,
pub rmax: i8,
pub arbreak: i8,
pub protection: i8,
pub integrity: i8,
pub torque_one_handed: Option<i8>,
pub torque_two_handed: Option<i8>,
pub modes: String,
pub esquive: String,
pub parrade: String,
pub vitesse: String,
pub discretion: String,
pub difficulty: String,
pub special: String,
pub needs_break: bool,
}
impl From<&RefinedEquipement> for ExportableEquipement {
fn from(value: &RefinedEquipement) -> Self {
let mut special = Vec::new();
if value.inner.action_cost != 0 && value.inner.action_cost != 1 {
special.push(format!(r"{}A", value.inner.action_cost));
}
if let Some(cost) = value.inner.reload_cost {
special.push(format!(r"{cost}\reload{{}}"));
};
if value.inner.armor_pierce != 0 {
let mut parmure = value.inner.armor_pierce;
match (&value.inner.category_base, &value.inner.category_size) {
(&Some(WeaponBaseShape::Ranged), Some(WeaponBaseSize::Heavy)) => parmure += 1,
(&Some(WeaponBaseShape::Ranged), Some(WeaponBaseSize::SuperHeavy)) => parmure += 1,
_ => (),
}
special.push(format!(r"\Gls{{parmure}} {parmure}"));
}
if value.inner.range != 0 {
let mut range = value.inner.range;
match (&value.inner.category_base, &value.inner.category_size) {
(&Some(WeaponBaseShape::Ranged), Some(WeaponBaseSize::Heavy)) => range += 30,
(&Some(WeaponBaseShape::Ranged), Some(WeaponBaseSize::SuperHeavy)) => range += 60,
_ => (),
}
special.push(format!(r"{range}m"));
}
if value.inner.precision != 0 {
special.push(format!(
r"\glssymbol{{precision}} {:+}",
value.inner.precision
));
}
Self {
name: value.advanced.display_name.clone(),
maniement: value.inner.get_maniement(),
damage_base: value.inner.damage,
damage_per: value.inner.p_damage,
rmax: value.inner.rmax,
arbreak: value.inner.armor_break,
protection: value.inner.protection,
integrity: value.inner.integrity,
torque_one_handed: value.inner.torque_one_handed,
torque_two_handed: value.inner.torque_two_handed,
modes: value.inner.get_modes(),
esquive: value.inner.dodge.to_string(),
parrade: value.inner.parry.to_string(),
vitesse: value.inner.speed.to_string(),
discretion: value.inner.stealth.to_string(),
difficulty: value.inner.difficulty.to_string(),
category: value.inner.category_base,
special: special.join(", "),
needs_break: false,
}
}
}
// DONE: The use of Deref could be a subtle gotcha
impl Deref for RefinedEquipementList {
type Target = Vec<RefinedEquipement>;
@ -255,7 +338,7 @@ pub struct AdvancedStats {
}
impl From<&InnerEquipementStats> for AdvancedStats {
fn from(value: &InnerEquipementStats) -> Self {
let max_damage_per_attack = (value.damage + value.p_damage * (value.rmax)) as f64;
let max_damage_per_attack = (value.damage + value.p_damage * (value.rmax - 1)) as f64;
let armor_break_per_attack =
(value.armor_break as f64 + value.antimaterial as f64).min(max_damage_per_attack);
let variance = (value.p_damage * value.rmax) as f64;

View File

@ -293,7 +293,8 @@ pub(super) fn binomial_dice_distribution(
+ equipement.p_damage as f64
* (target_dices
.saturating_sub(1)
.clamp(0, equipement.rmax as usize)) as f64)
.clamp(0, (equipement.rmax - 1) as usize))
as f64)
* probability_success
} else {
0.

View File

@ -48,26 +48,65 @@ pub enum NatureTarget {
/// Enum of all different physical weapon damage types
#[allow(clippy::missing_docs_in_private_items, missing_docs)]
#[derive(Clone, Debug, Deserialize, Serialize)]
#[cfg_attr(test, derive(PartialEq))]
#[derive(Copy, Clone, Debug, Deserialize, Serialize, PartialEq, Eq, PartialOrd, Ord)]
// #[cfg_attr(test, derive(PartialEq))]
pub enum PhysicalDamageType {
Blunt,
Slash,
Pierce,
}
impl PhysicalDamageType {
/// Get a exportable representation
pub fn export(&self) -> String {
match self {
PhysicalDamageType::Blunt => "\\blunt".to_string(),
PhysicalDamageType::Slash => "\\slash".to_string(),
PhysicalDamageType::Pierce => "\\pierce".to_string(),
}
}
}
/// Weapon damage, combining the base weapon damage type and it's level
///
/// Signifying wether the damage is pure or \[secondary\] or \[\[tertiary\]\]
#[allow(clippy::missing_docs_in_private_items, missing_docs)]
#[derive(Clone, Debug, Display, Deserialize, Serialize)]
#[cfg_attr(test, derive(PartialEq))]
#[derive(Clone, Debug, Display, Deserialize, Serialize, Eq, PartialEq, PartialOrd, Ord)]
pub enum DamageMod {
Primary(PhysicalDamageType),
Secondary(PhysicalDamageType),
Tertiary(PhysicalDamageType),
}
impl DamageMod {
/// Get the underlying value of the mod
pub fn underlying(&self) -> PhysicalDamageType {
match self {
DamageMod::Primary(physical_damage_type) => *physical_damage_type,
DamageMod::Secondary(physical_damage_type) => *physical_damage_type,
DamageMod::Tertiary(physical_damage_type) => *physical_damage_type,
}
}
/// Get a exportable representation
pub fn export(&self) -> String {
match self {
DamageMod::Primary(phy) => phy.export(),
DamageMod::Secondary(phy) => format!(r"[{}]", phy.export()),
DamageMod::Tertiary(phy) => format!(r"[[{}]]", phy.export()),
}
}
/// Does the damagemode contain this physical type
pub fn contains(&self, value: &PhysicalDamageType) -> bool {
self.underlying() == *value
}
// /// Does the other mod have a better mod variant, only true if the underlying value is the same
// pub fn upgrade(&self, value: &DamageMod) -> bool {
// value > self
// }
}
/// Combined damage type, as a vector of all damage types
///
/// Meant to be serialised to tex and deserialized directly from the table
@ -76,6 +115,20 @@ pub enum DamageMod {
// TODO: avoid pub make an impl ?
pub struct DamageType(Vec<DamageMod>);
impl DamageType {
/// Get the best modes from self, stripping redundant ones
pub fn get_best_modes(&self) -> DamageType {
let mut best: Vec<DamageMod> = Vec::new();
for m in self.iter() {
if let Some(_v) = best.iter().find(|v| v.contains(&m.underlying())) {
} else {
best.push(m.clone());
}
}
Self(best)
}
}
impl Deref for DamageType {
type Target = Vec<DamageMod>;
@ -229,8 +282,9 @@ pub enum EquipementSerializedCategory {
// : This should replace the used MacroCategory
/// The Base Shape of the weapon, used to infer the final category of the weapon
#[allow(clippy::missing_docs_in_private_items, missing_docs)]
#[derive(Clone, Debug, Display, Deserialize, Serialize, strum::EnumString)]
#[cfg_attr(test, derive(PartialEq))]
#[derive(
Copy, Clone, Debug, Display, Deserialize, Serialize, strum::EnumString, Default, PartialEq,
)]
pub enum WeaponBaseShape {
Staves,
Blunt,
@ -239,6 +293,7 @@ pub enum WeaponBaseShape {
Armors,
Shields,
Exotic,
#[default]
None,
}

View File

@ -10,6 +10,7 @@
use super::equipement_structs::InnerEquipementStats;
use crate::interfaces::{FilterFunction, Reportable};
use crate::weaponry_structs::equipement_fields::WeaponBaseSize;
use crate::weaponry_structs::{SpecialField, WeaponBaseShape};
use comfy_table::{Table, modifiers::UTF8_ROUND_CORNERS};
use std::{
@ -228,13 +229,38 @@ macro_rules! first_correct_option {
};
}
/// Fixing the french grammar in the worst way possible
fn stupid_adjective_fix(name_base: &str, adj: String) -> String {
let plur = || format!("{adj}s");
let masc = || match adj.as_str() {
"moyenne" => "moyen".to_owned(),
"légère" => "léger".to_owned(),
_ => adj[..adj.len() - 1].to_string(),
};
match name_base {
"Griffes" => plur(),
"Hast" => masc(),
"Marteau" => masc(),
"Arc" => masc(),
"Bouclier" => masc(),
_ => adj,
}
}
impl std::ops::Add for &InnerEquipementStats {
type Output = InnerEquipementStats;
fn add(self, rhs: Self) -> Self::Output {
InnerEquipementStats {
id: add_to_vec!(self.id, rhs.id),
name: add_to_vec!(self.name, rhs.name),
name: add_to_vec!(
self.name,
if let Some(ad) = &rhs.adjective {
vec![stupid_adjective_fix(&self.name[0], ad.clone())]
} else {
rhs.name.clone()
}
),
adjective: rhs.adjective.clone(),
rarity: self.rarity + rhs.rarity,
cost: self.cost + rhs.cost,
difficulty: self.difficulty + rhs.difficulty,
@ -285,6 +311,45 @@ impl std::ops::Add for SpecialField {
}
}
impl InnerEquipementStats {
/// Get the maniement as a printable string
pub fn get_maniement(&self) -> String {
match &self.category_size {
Some(WeaponBaseSize::SuperHeavy) => match self.name[0].as_str() {
"Griffes" => "Frienzä",
"Marteau" => "Rhödarak",
"Épée" => "Haroth",
"Hache" => "Kahml",
"Hast" => "Paysagiste",
"Arc" => "Distance",
"Arbalète" => "Distance",
_ => "-",
}
.to_string(),
_ => match &self.category_base {
Some(WeaponBaseShape::Staves) => "Hast".to_string(),
Some(WeaponBaseShape::Blunt) => "Contondante".to_string(),
Some(WeaponBaseShape::Slash) => "Tranchante".to_string(),
Some(WeaponBaseShape::Ranged) => "Distance".to_string(),
_ => "-".to_string(),
},
}
}
/// Get the modes as a printable string
pub fn get_modes(&self) -> String {
match &self.damage_type {
Some(t) => t
.get_best_modes()
.iter()
.map(|v| v.export())
.collect::<Vec<String>>()
.join(","),
None => "-".to_string(),
}
}
}
#[cfg(test)]
mod test {
use crate::{

View File

@ -92,6 +92,7 @@ impl TryFrom<DatabaseEquipementStats> for InnerEquipementStats {
Ok(Self {
id: vec![value.id], // Special case where manual is better than serde
name: vec![value.name],
adjective: value.adjective,
rarity: value.rarity, // Generic case, into(), serde or cast are equivalent
cost: value.cost,
difficulty: value.difficulty,

View File

@ -2,8 +2,15 @@
// File: weaponry/src/weaponry_structs/equipement_impl_io.rs
//! All implementation IO specific (mainly export and serde)
use cli_parser::Config;
use handlebars::Handlebars;
use super::equipement_advanced_repr::RefinedEquipementList;
use crate::interfaces::{ToCSV, ToTex};
use crate::{
error::FatalEquipementError,
interfaces::{ToCSV, ToTex},
weaponry_structs::equipement_advanced_repr::ExportableEquipement,
};
use std::path::Path;
impl ToCSV for RefinedEquipementList {
@ -17,10 +24,24 @@ impl ToCSV for RefinedEquipementList {
}
impl ToTex for RefinedEquipementList {
// Nom & \rotbx{Rareté} & \rotbx{Dégâts} & + & \rotbx{R.Max} & \rotbx{Armr.B} & \rotbx{Protbx} & \rotbx{Int.} & \rotbx{Deux M} & \rotbx{Une M} & \rotbx{Esq.} & \rotbx{Parr.} & \rotbx{Vitesse} & \rotbx{Discr.} & \rotbx{Catégorie} & \rotbx{Modes} & \rotbx{Spécial} \\
fn to_tex(&self) -> String {
self.inner.iter().for_each(|m| println!("{:?}", m.inner));
todo!()
fn to_tex(&self, config: &Config) -> Result<String, FatalEquipementError> {
let mut template = Handlebars::new();
template.register_template_string("weapons", &config.weapons.template)?;
let mut data = self
.iter()
.map(std::convert::Into::<ExportableEquipement>::into)
.collect::<Vec<ExportableEquipement>>();
for i in 0..data.len() - 1 {
if data[i].category != data[i + 1].category
&& data[i + 1].category == Some(super::WeaponBaseShape::Shields)
{
data[i].needs_break = true;
}
}
let r = template.render("weapons", &data)?;
// println!("{}", r);
Ok(r)
}
}

View File

@ -80,6 +80,7 @@ impl<T> FilterFunction<T> {
pub struct InnerEquipementStats {
pub id: Vec<u8>,
pub name: Vec<String>,
pub adjective: Option<String>,
pub(super) rarity: i8,
pub(super) cost: i8,
pub(super) difficulty: i8,
@ -130,6 +131,8 @@ pub struct DatabaseEquipementStats {
pub id: u8,
pub meta_category: String,
pub name: String,
#[TEXT]
pub adjective: Option<String>,
#[INTEGER]
pub rarity: i8,
#[INTEGER]
@ -212,6 +215,7 @@ impl Default for DatabaseEquipementStats {
range: 0,
agility_bonus: 0.,
action_cost: 0,
adjective: None,
}
}
}

View File

@ -2,7 +2,6 @@
# This value should be overwriten by a relative path
database = "./ravenous_databases/weapons.db"
[classes]
header = '''\begin{}[
presep = 0pt, postsep = 0pt,
@ -156,7 +155,7 @@ common_part = '''
cell{1}{1}={c=2}{c},
}
{{#if image}}\includegraphics[height=5cm]{ {{{image}}} } & \\{{/if}}
{{#if image}}\includegraphics[height=5cm]{ {{{~image~}}} } & \\ {{/if}}
& \\
Nom & {{{name}}} \\
{{#if denomination}}Dénomination & {{{denomination}}} \\
@ -230,7 +229,7 @@ master_part = '''
\SetCell{c} Res & \slash & \pierce & \blunt & \symceleste & \symfire & \symearth & \symwood & \symmagma & \symabyss & \symwater & \symwind & \symice & \symthunder \\
\hline
{{#each body_parts.body_parts}}
\SetCell{font=\footnotesize} {{{body_part_name}}} & ${{{slash}}} $ & ${{{pierce}}} $ & ${{{blunt}}} $ & ${{{celestial}}} $ & ${{{fire}}} $ & ${{{earth}}} $ & ${{{wood}}} $ & ${{{magma}}} $ & ${{{celeste}}} $ & ${{{water}}} $ & ${{{wind}}} $ & ${{{ice}}} $ & ${{{thunder}}} $ \\
\SetCell{font=\footnotesize} {{{body_part_name}}} & ${{{slash}}} $ & ${{{pierce}}} $ & ${{{blunt}}} $ & ${{{celestial}}} $ & ${{{fire}}} $ & ${{{earth}}} $ & ${{{wood}}} $ & ${{{magma}}} $ & ${{{celeste}}} $ & ${{{water}}} $ & ${{{wind}}} $ & ${{{ice}}} $ & ${{{thunder}}} $ \\
{{/each}}
\end{tblr}
\end{center}
@ -263,16 +262,16 @@ master_part = '''
hspan=minimal,
colsep=2pt,
row{2}={font=\tiny},
rowshead=2,
rowhead=2,
}
& & & & & \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}
{{#each all_attacks.phases as | phase |}}
\SetHline{1}{0pt}
{{#if @first}}
& {\scriptsize\SetCell{white} \textsc{ {{{@key}}} }} & {Type} & {Préquis} & \rb{Ciblage} & \rb{Fatigue} & \rb{Action} & \rb{Élément} & \rb{Fatigue} & \SetCell{c} \rb{Normaux} & {Effets} & \rb{Parade} & \rb{Esquive} \\
& {\scriptsize\SetCell{white} \textsc{ {{{~@key~}}} }} & {Type} & {Préquis} & \rb{Ciblage} & \rb{Fatigue} & \rb{Action} & \rb{Élément} & \rb{Fatigue} & \SetCell{c} \rb{Normaux} & {Effets} & \rb{Parade} & \rb{Esquive} \\
{{else}}
\SetCell[c=13]{white} \textsc{ {{{@key}}} } & & & & & & & & & & \\
\SetCell[c=13]{white} \textsc{ {{{~@key~}}} } & & & & & & & & & & \\
{{/if}}
{{#each phase as | attack_group |}}
\hline
@ -290,7 +289,7 @@ master_part = '''
{{#with data}}
\pagebreak
\begin{tblr}{
colspec={X[7] {{#if intent_graph}}|X[3] {{/if}} },
colspec={X[7] {{#if intent_graph}}|X[3] {{/if~}} },
rowspec={X[c] X[j,h,8cm]},
hline{2},
row{2}={font=\footnotesize},
@ -331,3 +330,37 @@ BIS: ravredD
BYP: ravredD
'''
default_color=''
[weapons]
template='''
\begin{landscape}\begin{center}
\begin{longtblr}[
entry = none,
label = none,
]{
colspec = {|QQQQQQQQQQQQQQQQQ|},
cells = {font = \footnotesize\selectfont},
row{1} = {bg=cobluel, fg=white},
row{even} = {coblueL},
hspan = minimal, vspan=minimal,
colsep = 2mm, abovesep=0px,belowsep=0px, leftsep=3px, rightsep=3px,
rowhead = 1,
}
\hline
{Forme} & {Maniement} & {\damagew} & + & {R.Max} & \arbreakw & \protection & \integrite & $\mathbb{T}$2 & $\mathbb{T}$1 & {Modes} & {Esq.} & {Par.} & {Vit.} & {Disc.} & {Spécial} & {Diff.} \\
\hline
{{#each this}}
{{name}} & {{maniement}} & {{damage_base}} & {{damage_per}} & {{rmax}} & {{arbreak}} & {{protection}} & {{integrity}} & {{torque_two_handed}} & {{torque_one_handed}} & $\mathbf{ {{{~modes~}}} }$ & {{esquive}} & {{parrade}} & {{vitesse}} & {{discretion}} & {{{special}}} & \ddlvl{ {{~difficulty~}} } \\
{{#if needs_break}}
\hline
\hline
{{/if}}
{{/each}}
\hline
\end{longtblr}
\end{center}
\end{landscape}
'''
# Nom & \rotbx{Rareté} & \rotbx{Dégâts} & + & \rotbx{R.Max} & \rotbx{Armr.B} & \rotbx{Protbx} & \rotbx{Int.} & \rotbx{Deux M} & \rotbx{Une M} & \rotbx{Esq.} & \rotbx{Parr.} & \rotbx{Vitesse} & \rotbx{Discr.} & \rotbx{Catégorie} & \rotbx{Modes} & \rotbx{Spécial} \\

@ -1 +1 @@
Subproject commit 5570da8b814f0d3925d0369131ae9baad72a31e8
Subproject commit 14934910a40cd5fdee09f9ef7df75e1e4d0f2288