From a0f05fb63816c208c6a5ee69d158c0e8ecbc8803 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Fri, 24 Jul 2026 05:17:28 +0200 Subject: [PATCH] Adds a draft of balancing --- Cargo.toml | 3 +- crates/monsters/Cargo.toml | 2 +- crates/monsters/src/monster_analysis.rs | 213 ++++++++++-------- .../monster_analysis_structs.rs | 194 ++++++++++++++++ crates/monsters/src/monster_render.rs | 139 +++++++++++- crates/monsters/src/monster_structs.rs | 24 +- crates/more_fields/src/lib.rs | 91 ++++++-- crates/more_fields_macro/Cargo.toml | 2 +- crates/more_fields_macro/src/lib.rs | 120 ++++++++-- crates/weaponry/Cargo.toml | 2 +- .../equipement_advanced_tools.rs | 25 +- ravenous_databases | 2 +- 12 files changed, 658 insertions(+), 159 deletions(-) create mode 100644 crates/monsters/src/monster_analysis/monster_analysis_structs.rs diff --git a/Cargo.toml b/Cargo.toml index 169995c..99cec21 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -6,7 +6,7 @@ resolver = "3" # edition = "2024" # license = "MIT OR Apache-2.0" [workspace.package] -version = "0.3.14" +version = "0.3.15" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html @@ -61,3 +61,4 @@ indexmap = {version= "2.14.0", features= ["serde"]} rusqlite = { version = "0.40.1" } # , features = ["bundled"] serde_rusqlite = "0.43.0" handlebars = "6.4.3" +strum = { version = "0.28.0", features = ["derive"] } diff --git a/crates/monsters/Cargo.toml b/crates/monsters/Cargo.toml index 5af9f24..0c489af 100644 --- a/crates/monsters/Cargo.toml +++ b/crates/monsters/Cargo.toml @@ -14,7 +14,7 @@ rusqlite = {workspace = true} serde_rusqlite = {workspace = true} serde_json = {workspace = true} handlebars = {workspace = true} -strum = { version = "0.28.0", features = ["derive"] } +strum = {workspace = true} comfy-table = "7.2.2" colored = "3.1.1" diff --git a/crates/monsters/src/monster_analysis.rs b/crates/monsters/src/monster_analysis.rs index 8531efc..0932b2d 100644 --- a/crates/monsters/src/monster_analysis.rs +++ b/crates/monsters/src/monster_analysis.rs @@ -3,12 +3,14 @@ use crate::{ Config, Connection, MonsterConfig, + monster_analysis::monster_analysis_structs::{ArmorBreakCategory, DamageCategory}, monster_database::{fetch_all_creature_data, fetch_all_player_data}, - monster_render::ToRow, - monster_structs::{MonsterFullAttack, PlayerBalancing}, + monster_render::ToTable, + monster_structs::PlayerBalancing, }; -use comfy_table::{presets, *}; use more_fields::FieldsAsSlice; +use std::cmp::{max, min}; +pub mod monster_analysis_structs; /// Shows balancing information for monsters and players. pub fn show_balancing_data( @@ -20,111 +22,140 @@ pub fn show_balancing_data( let data = fetch_all_creature_data(&connection, config)?; let player_data = fetch_all_player_data(&connection, config)?; - let mut table = Table::new(); - table - .load_preset(presets::UTF8_FULL_CONDENSED) - .apply_modifier(modifiers::UTF8_ROUND_CORNERS) - .set_content_arrangement(ContentArrangement::Dynamic) - .set_width(120) - .set_header( - PlayerBalancing::attributes_slice() - .iter() - .map(|(a, _b)| Cell::new(a)), - ); - // table.add_row(player_data.as_slice()); + // let table = player_data.to_table(); - for entry in player_data { - table.add_row(entry.to_row()); - } for creature in data { println!("{}", creature.name); - for (_, phases) in creature.all_attacks.phases { - for attack in phases { - for sub_attack in &attack.attacklist { - println!("{:?}", sub_attack); - let m = MonsterAttack { - base_attack: &attack, - damage: damage_from_string(sub_attack.damage_regular.as_ref()), - successes: from_opt_str(sub_attack.success.as_ref()), - armor_break: from_opt_i64(sub_attack.armor_break.as_ref()), - action_cost: from_opt_str(sub_attack.success.as_ref()), - }; - println!("{m:?}") - } - } + let player_level = &creature.balancing.profile_hse; + let available_profiles = player_data + .clone() + .into_iter() + .filter(|v| &v.profile_hse == player_level) + .collect::>(); + let profile_a = &available_profiles[0]; + let attacks: Vec = creature.into(); + let table = attacks.to_table(); + println!("{table}"); + + let mut res = Vec::new(); + for attack in attacks { + let report = attack_player(&attack, profile_a, DefenseMode::Best).unwrap(); + res.push(report); } + let res = res + .into_iter() + .filter(|v| { + v.damage_category != v.damage_expected || v.armor_expected != v.armor_category + }) + .collect::>(); + println!("{}", res.to_table()); } - println!("{table}"); + // println!("{table}"); Ok(()) } - -fn damage_from_string(str: Option<&String>) -> Vec { - match str { - Some(str) => str - .split("/") - .map(|v| v.parse().unwrap_or_default()) - .collect(), - None => Vec::new(), - } +#[derive(Debug)] +pub enum DefenseMode { + Best, + Worst, } -fn from_opt_str(str: Option<&String>) -> i64 { - match str { - Some(str) => str.parse().unwrap_or_default(), - None => 0, - } -} -fn from_opt_i64(val: Option<&i64>) -> i64 { - match val { - Some(val) => *val, - None => 0, +pub fn attack_player( + attack: &monster_analysis_structs::MonsterBalancingAttack, + victim: &PlayerBalancing, + mode: DefenseMode, +) -> Option { + // How much successes left + let threshold = match mode { + DefenseMode::Best => max(attack.threshold_parry, attack.threshold_dodge), + DefenseMode::Worst => max(attack.threshold_parry, attack.threshold_dodge), + }; + let rem_s = attack.successes - thld(victim.successes_def, threshold); + + let mut damage_incoming = how_much_with_succeses(&attack.damage, rem_s); + let mut effective_damage = (damage_incoming - victim.protection - victim.strength).max(0); + let mut armor_loss = (damage_incoming - victim.protection).clamp(0, attack.armor_break); + if rem_s < 0 { + damage_incoming = 0; + effective_damage = 0; + armor_loss = 0; } + let report = DamageReport { + damage_incoming, + damage_tanked: effective_damage, + armor_loss, + successes_left: rem_s, + damage_category: DamageCategory::from_percent( + effective_damage as f64 / victim.health as f64, + ), + armor_expected: attack.target_ab, + name: attack.name.clone(), + damage_expected: attack.target_damage, + armor_category: ArmorBreakCategory::from_percent( + armor_loss as f64 / victim.integrity as f64, + ), + player_health: victim.health, + player_integrity: victim.integrity, + threshold, + attack_successes: attack.successes, + mode, + }; + Some(report) } -impl PlayerBalancing { - // /// Estimate what an attack does to a player - // pub fn estimate_attack(&self, atk: MonsterAttack) {} +#[derive(Debug, FieldsAsSlice)] +pub struct DamageReport { + pub name: String, + #[INTEGER(name = "dmg_inc")] + pub damage_incoming: i64, + #[INTEGER(name = "r_left")] + pub successes_left: i64, + #[INTEGER(name = "dmg_tak")] + pub damage_tanked: i64, + #[TEXT(name = "dmg_cat")] + pub damage_category: DamageCategory, + #[TEXT(name = "dmg_expt")] + pub damage_expected: DamageCategory, + #[INTEGER(name = "arm_loss")] + pub armor_loss: i64, + #[TEXT(name = "arm_cat")] + pub armor_category: ArmorBreakCategory, + #[TEXT(name = "arm_expt")] + pub armor_expected: ArmorBreakCategory, + #[SKIP] + pub player_health: i64, + #[SKIP] + pub player_integrity: i64, + #[SKIP] + pub threshold: i64, + #[SKIP] + pub mode: DefenseMode, + #[SKIP] + pub attack_successes: i64, +} - /// Apply an attack to a player, returns the damage done but "healing" afterwards - pub fn apply_attack(&mut self, atk: &MonsterAttack) -> DamageDone { - let _ = atk; - self.health -= 1; - DamageDone { - armor: 0, - health: 0, - category: DamageCategory::Low, +impl DamageCategory { + fn from_percent(percent: f64) -> Self { + match percent { + ..0.01 => Self::None, + 0.01..0.15 => Self::Chip, + 0.15..0.5 => Self::Moderate, + 0.5..0.8 => Self::High, + 0.8..1.0 => Self::NearDeath, + 1.0..1.5 => Self::Kill, + 1.5.. => Self::Overkill, + _ => Self::None, } } } -#[derive(Debug)] -pub struct MonsterAttack<'a> { - base_attack: &'a MonsterFullAttack, - damage: Vec, - successes: i64, - armor_break: i64, - action_cost: i64, +fn thld(r_succeses: i64, threshold_parry: i64) -> i64 { + (r_succeses * min(threshold_parry, 10)) / 10 } -pub struct DamageDone { - armor: i64, - health: i64, - category: DamageCategory, -} - -pub enum DamageCategory { - /// No lasting damage - None, - /// Chip damage - Low, - /// Average, under half - Moderate, - /// High, above half - High, - /// Near death 90% - NearDeath, - /// Kill, above > 100% - Kill, - /// Complete overkill > 200% - Overkill, +fn how_much_with_succeses(damage: &[i64], succeses: i64) -> i64 { + if succeses <= 0 { + 0 + } else { + damage[min(succeses, (damage.len() - 1) as i64) as usize] + } } diff --git a/crates/monsters/src/monster_analysis/monster_analysis_structs.rs b/crates/monsters/src/monster_analysis/monster_analysis_structs.rs new file mode 100644 index 0000000..30e66db --- /dev/null +++ b/crates/monsters/src/monster_analysis/monster_analysis_structs.rs @@ -0,0 +1,194 @@ +use crate::monster_structs::{FullMonster, PlayerBalancing, ProfileStance}; +use more_fields::FieldsAsSlice; +use std::str::FromStr; +use strum::EnumString; + +impl From for Vec { + fn from(creature: FullMonster) -> Self { + creature + .all_attacks + .phases + .into_iter() + .flat_map(|(_, phases)| { + phases.into_iter().flat_map(|monster_full_attack| { + let mut cumul = 0; + monster_full_attack + .attacklist + .into_iter() + .map(move |sub_attack| { + cumul += from_successes(sub_attack.success.as_ref()); + MonsterBalancingAttack { + damage: damage_from_string(sub_attack.damage_regular.as_ref()), + successes: cumul, + armor_break: from_opt_i64(sub_attack.armor_break.as_ref()), + action_cost: from_actions(sub_attack.cost_action.as_ref()), + name: sub_attack.name, + threshold_parry: from_opt_i64(sub_attack.threshold_parry.as_ref()), + threshold_dodge: from_opt_i64(sub_attack.threshold_dodge.as_ref()), + target_damage: sub_attack.target_damage_category.into(), + target_ab: sub_attack.target_ab_category.into(), + target_stance: sub_attack.target_stance.into(), + } + }) + .filter(|sub| !sub.damage.is_empty()) + }) + }) + .collect() + } +} + +impl PlayerBalancing { + // /// Estimate what an attack does to a player + // pub fn estimate_attack(&self, atk: MonsterAttack) {} + + /// Apply an attack to a player, returns the damage done but "healing" afterwards + pub fn apply_attack(&mut self, atk: &MonsterBalancingAttack) -> DamageDone { + let _ = atk; + self.health -= 1; + DamageDone { + armor: 0, + health: 0, + category: DamageCategory::Chip, + } + } +} + +#[derive(Debug, FieldsAsSlice)] +pub struct MonsterBalancingAttack { + pub name: String, + pub damage: Vec, + #[INTEGER(name = "s")] + pub successes: i64, + #[INTEGER(name = "ab")] + pub armor_break: i64, + #[INTEGER(name = "A")] + pub action_cost: i64, + #[SKIP(name = "parry_t")] + pub threshold_parry: i64, + #[SKIP(name = "dodge_t")] + pub threshold_dodge: i64, + #[TEXT(name = "damage_t")] + pub target_damage: DamageCategory, + #[TEXT(name = "arbreak_t")] + pub target_ab: ArmorBreakCategory, + #[TEXT(name = "stance_t")] + pub target_stance: ProfileStance, +} + +pub struct DamageDone { + pub(crate) armor: i64, + pub(crate) health: i64, + pub(crate) category: DamageCategory, +} + +#[derive(Copy, Clone, Debug, EnumString, Default, strum::Display, PartialEq)] +pub enum DamageCategory { + /// No lasting damage + #[default] + None, + /// Chip damage + Chip, + /// Average, under half + Moderate, + /// High, above half + High, + /// Near death 90% + NearDeath, + /// Kill, above > 100% + Kill, + /// Complete overkill > 200% + Overkill, +} + +#[derive(Copy, Clone, Debug, EnumString, Default, strum::Display, PartialEq, Eq)] +pub enum ArmorBreakCategory { + /// No lasting damage + #[default] + None, + /// Chip damage + Chip, + /// High, above half + High, + /// Full destruction + FullBreak, + /// Complete overkill > 200% + Overkill, +} + +impl ArmorBreakCategory { + pub fn from_percent(value: f64) -> Self { + match value { + ..0.01 => ArmorBreakCategory::None, + 0.01..0.3 => ArmorBreakCategory::Chip, + 0.3..0.7 => ArmorBreakCategory::High, + 0.7..1.2 => ArmorBreakCategory::FullBreak, + 1.2.. => ArmorBreakCategory::Overkill, + _ => ArmorBreakCategory::None, + } + } +} +impl From> for DamageCategory { + fn from(value: Option) -> Self { + if let Some(value) = value { + Self::from_str(&value).unwrap_or_default() + } else { + Self::None + } + } +} + +impl From> for ArmorBreakCategory { + fn from(value: Option) -> Self { + if let Some(value) = value { + Self::from_str(&value).unwrap_or_default() + } else { + Self::None + } + } +} + +impl From> for ProfileStance { + fn from(value: Option) -> Self { + if let Some(value) = value { + Self::from_str(&value).unwrap_or_default() + } else { + Self::Neutral + } + } +} + +pub(crate) fn damage_from_string(str: Option<&String>) -> Vec { + match str { + Some(str) => str.split("/").map(|v| v.parse().ok()).collect(), + None => None, + } + .unwrap_or_default() +} + +pub(crate) fn from_successes(str: Option<&String>) -> i64 { + match str { + Some(str) => str.replace("r", "").parse().unwrap_or_default(), + None => 0, + } +} + +pub(crate) fn from_actions(str: Option<&String>) -> i64 { + match str { + Some(str) => str.replace("A", "").parse().unwrap_or_default(), + None => 0, + } +} + +pub(crate) fn from_opt_str(str: Option<&String>) -> i64 { + match str { + Some(str) => str.parse().unwrap_or_default(), + None => 0, + } +} + +pub(crate) fn from_opt_i64(val: Option<&i64>) -> i64 { + match val { + Some(val) => *val, + None => 0, + } +} diff --git a/crates/monsters/src/monster_render.rs b/crates/monsters/src/monster_render.rs index 461f7d3..39be4d4 100644 --- a/crates/monsters/src/monster_render.rs +++ b/crates/monsters/src/monster_render.rs @@ -1,7 +1,12 @@ -use comfy_table::Color; -use comfy_table::{Cell, Row}; +use comfy_table::{Color, Table, *}; -use crate::monster_structs::{PlayerBalancing, ProfileHSE, ProfileStance}; +use crate::{ + monster_analysis::{ + DamageReport, + monster_analysis_structs::{ArmorBreakCategory, DamageCategory, MonsterBalancingAttack}, + }, + monster_structs::{PlayerBalancing, ProfileHSE, ProfileStance}, +}; /// Handy trait: “give me the table row that represents this record” pub trait ToCell { @@ -11,7 +16,45 @@ pub trait ToCell { pub trait ToRow { fn to_row(&self) -> Row; } +pub trait ToTable { + fn to_table(&self) -> Table; +} +impl ToTable for Vec +where + T: more_fields::FieldsAsSlice + ToRow, +{ + fn to_table(&self) -> Table { + let mut table = Table::new(); + table + .load_preset(presets::UTF8_FULL_CONDENSED) + .apply_modifier(modifiers::UTF8_ROUND_CORNERS) + .set_content_arrangement(ContentArrangement::Dynamic) + .set_width(120) + .set_header(T::attributes_slice().iter().map(|(a, _b)| Cell::new(a))); + // table.add_row(player_data.as_slice()); + + for entry in self { + table.add_row(entry.to_row()); + } + table + } +} +impl ToRow for MonsterBalancingAttack { + fn to_row(&self) -> Row { + vec![ + self.name.to_cell(), + self.damage.to_cell(), + self.successes.to_cell(), + self.armor_break.to_cell(), + self.action_cost.to_cell(), + self.target_damage.to_cell(), + self.target_ab.to_cell(), + self.target_stance.to_cell(), + ] + .into() + } +} impl ToRow for PlayerBalancing { fn to_row(&self) -> Row { vec![ @@ -27,7 +70,97 @@ impl ToRow for PlayerBalancing { .into() } } +impl ToRow for DamageReport { + fn to_row(&self) -> Row { + vec![ + self.name.to_cell().fg(Color::Green), + format!("{} [{}r]", self.damage_incoming, self.attack_successes,).to_cell(), + format!("{} [>{}]", self.successes_left, self.threshold) + .to_cell() + .fg(if self.successes_left > 0 { + Color::Blue + } else { + Color::Red + }), + format!("{}/{}", self.damage_tanked, self.player_health) + .to_cell() + .fg(self.damage_category.get_color()), + self.damage_category.to_cell().add_attribute( + if self.damage_expected != self.damage_category { + Attribute::Reverse + } else { + Attribute::Dim + }, + ), + self.damage_expected.to_cell(), + format!("{}/{}", self.armor_loss, self.player_integrity) + .to_cell() + .fg(self.armor_category.get_color()), + self.armor_category.to_cell().add_attribute( + if self.armor_expected != self.armor_category { + Attribute::Reverse + } else { + Attribute::Dim + }, + ), + self.armor_expected.to_cell(), + ] + .into() + } +} +impl ToCell for DamageCategory { + fn to_cell(&self) -> Cell { + Into::::into(format!("{self:?}")).fg(self.get_color()) + } +} +pub trait ToColor { + fn get_color(&self) -> Color; +} +impl ToColor for DamageCategory { + fn get_color(&self) -> Color { + match self { + DamageCategory::None => Color::DarkGrey, + DamageCategory::Chip => Color::DarkBlue, + DamageCategory::Moderate => Color::Blue, + DamageCategory::High => Color::Green, + DamageCategory::NearDeath => Color::Yellow, + DamageCategory::Kill => Color::Red, + DamageCategory::Overkill => Color::DarkRed, + } + } +} +impl ToCell for ArmorBreakCategory { + fn to_cell(&self) -> Cell { + Into::::into(format!("{self:?}")).fg(self.get_color()) + } +} +impl ToColor for ArmorBreakCategory { + fn get_color(&self) -> Color { + match self { + ArmorBreakCategory::None => Color::DarkGrey, + ArmorBreakCategory::Chip => Color::Blue, + ArmorBreakCategory::High => Color::Yellow, + ArmorBreakCategory::FullBreak => Color::Red, + ArmorBreakCategory::Overkill => Color::DarkRed, + } + } +} +impl ToCell for i64 { + fn to_cell(&self) -> Cell { + format!("{}", self).into() + } +} +impl ToCell for Vec { + fn to_cell(&self) -> Cell { + format!("{self:?}").into() + } +} +impl ToCell for String { + fn to_cell(&self) -> Cell { + self.into() + } +} impl ToCell for ProfileHSE { fn to_cell(&self) -> Cell { match self { diff --git a/crates/monsters/src/monster_structs.rs b/crates/monsters/src/monster_structs.rs index 3c18127..6b48187 100644 --- a/crates/monsters/src/monster_structs.rs +++ b/crates/monsters/src/monster_structs.rs @@ -15,6 +15,7 @@ use indexmap::IndexMap; use more_fields::FieldsAsSlice; use serde::{Deserialize, Serialize}; +use strum::EnumString; /// Full data, including monster_data & balancing data pub struct FullData {} @@ -230,6 +231,12 @@ pub struct MonsterSingleAttack { /// Minimum dodge rating required to avoid the ability’s effect. #[INTEGER] pub threshold_dodge: Option, + /// Target level of damage + pub target_damage_category: Option, + /// Target level of damage + pub target_ab_category: Option, + /// Target stance of players + pub target_stance: Option, } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default, FieldsAsSlice)] @@ -408,25 +415,25 @@ pub struct CreatureStats { #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, FieldsAsSlice)] pub struct CreatureBalancing { #[INTEGER] - creature_id: i64, + pub creature_id: i64, #[TEXT] /// (Fixed) HSE profile of the monster (see `ProfileHSE`). - profile_hse: ProfileHSE, + pub profile_hse: ProfileHSE, #[INTEGER] /// (Goal) Turns needed to reach phase 2. - time_to_p2: i64, + pub time_to_p2: i64, #[INTEGER] /// (Goal) Turns until the monster’s armor breaks. - time_to_armorbreak: i64, + pub time_to_armorbreak: i64, #[INTEGER] /// (GOAL) Avg. turns to kill a single target. - time_to_first_kill: i64, + pub time_to_first_kill: i64, #[INTEGER] /// (FIXED) Size of a single monster group (usually one). - monster_groupsize: i64, + pub monster_groupsize: i64, #[INTEGER] /// (FIXED) The number of players this fight was designed for - player_groupsize: i64, + pub player_groupsize: i64, } /// Balancing info on all the player depending on their level @@ -463,11 +470,12 @@ pub struct PlayerBalancing { pub health: i64, } -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default, EnumString)] /// Player stance preference used for balance tables. pub enum ProfileStance { Defensive, Offensive, + #[default] Neutral, } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] diff --git a/crates/more_fields/src/lib.rs b/crates/more_fields/src/lib.rs index 6bfd4df..8e7e36f 100644 --- a/crates/more_fields/src/lib.rs +++ b/crates/more_fields/src/lib.rs @@ -5,28 +5,24 @@ //! however this limitation is completely artificial pub use more_fields_macro::FieldsAsSlice; +pub use more_fields_macro::InstanceAsArray; pub trait FieldsAsSlice { fn attributes_slice() -> &'static [(&'static str, &'static str)]; } -// fn iter(&self) -> std::vec::IntoIter<(&'static str, &'static str)>; +/// Converts an instance into a homogeneous array. +/// +/// The array length is determined by the derive macro. +pub trait InstanceAsArray { + /// Element type of the generated array. + type Item; -// #[cfg(feature = "expand_macro")] -// #[derive(FieldsAsSlice, Default)] -// struct Bob { -// #[TEXT] -// field_ouane: u16, -// #[INTEGER] -// field_2: u16, -// #[BLOB] -// field_3: u16, -// #[NULL] -// field_4: u16, -// #[REAL] -// field_5: u16, -// field_6: u16, -// } + // /// Concrete array type, e.g. `[Value; 5]`. + // type Array: AsRef>; + + fn instance_as_array(&self) -> Vec; +} #[cfg(test)] mod test { @@ -63,4 +59,67 @@ mod test { assert_eq!(Bob::attributes_slice(), b_hash); } + use crate::InstanceAsArray; + + #[allow(dead_code)] + #[derive(Debug, PartialEq)] + enum Value { + Integer(i64), + Text(String), + } + + impl From for Value { + fn from(v: i32) -> Self { + Value::Integer(v as i64) + } + } + + impl From for Value { + fn from(v: String) -> Self { + Value::Text(v) + } + } + + #[derive(FieldsAsSlice, InstanceAsArray)] + #[InstanceAsArray(Type = String)] + struct Person { + #[INTEGER] + id: String, + + #[TEXT] + name: String, + + #[SKIP] + cached: String, + } + + #[test] + fn instance_as_array_works() { + let person = Person { + id: "Alice".into(), + name: "Alice".into(), + cached: "Alice".into(), + }; + assert!(person.cached == "Alice",); + let array = person.instance_as_array(); + let slice = array.as_ref(); + + assert_eq!(slice, &["Alice".to_string(), "Alice".to_string(),]); + } + + // #[test] + // fn attributes_slice_matches_instance_array() { + // let attrs = Person::attributes_slice(); + + // assert_eq!(attrs, &[("id", "INTEGER"), ("name", "TEXT"),]); + + // let values = Person { + // id: 1, + // name: "Bob".into(), + // cached: false, + // } + // .instance_as_array(); + + // assert_eq!(attrs.len(), values.as_ref().len()); + // } } diff --git a/crates/more_fields_macro/Cargo.toml b/crates/more_fields_macro/Cargo.toml index 30da338..4ffc9db 100644 --- a/crates/more_fields_macro/Cargo.toml +++ b/crates/more_fields_macro/Cargo.toml @@ -8,4 +8,4 @@ proc-macro = true [dependencies] quote = "1.0.46" -syn = "2.0.118" +syn = {version= "2.0.118", features=["full"]} diff --git a/crates/more_fields_macro/src/lib.rs b/crates/more_fields_macro/src/lib.rs index 155f06b..a2966e4 100644 --- a/crates/more_fields_macro/src/lib.rs +++ b/crates/more_fields_macro/src/lib.rs @@ -50,37 +50,52 @@ pub fn derive_iterable(input: TokenStream) -> TokenStream { // For each field: * skip if `#[SKIP]` is present // * otherwise find the first of the type attributes, or default to TEXT let fields_iter = fields.iter().filter_map(|field| { - // 1. Skip any field that has a SKIP attribute. + // Skip fields marked with #[SKIP] if field.attrs.iter().any(|a| a.path().is_ident("SKIP")) { return None; } - // 2. Determine the SQLite type for this field - let val = field - .attrs - .iter() - .filter_map(|attr| attr.path().get_ident()) - .find(|ident| { - matches!( - ident.to_string().as_str(), - "INTEGER" | "NULL" | "REAL" | "TEXT" | "BLOB" - ) - }) - .cloned() - .unwrap_or_else(|| syn::Ident::new("TEXT", proc_macro::Span::call_site().into())) - .to_string(); - - // 3. Get the field name (it is guaranteed to be Some for named fields) - let field_name = field + let mut sqlite_type = "TEXT".to_string(); + let mut exported_name = field .ident .as_ref() - .expect("Expected a named field") + .expect("Expected named field") .to_string(); - // Produce the tokens that will end up in the generated slice. - Some(quote! { (#field_name, #val) }) - }); + for attr in &field.attrs { + let ident = match attr.path().get_ident() { + Some(i) => i.to_string(), + None => continue, + }; + if !matches!( + ident.as_str(), + "INTEGER" | "NULL" | "REAL" | "TEXT" | "BLOB" + ) { + continue; + } + + sqlite_type = ident; + + // Parse optional: #[TEXT(name = "...")] + let _ = attr.parse_nested_meta(|meta| { + if meta.path.is_ident("name") { + let value = meta.value()?; + let lit: syn::LitStr = value.parse()?; + exported_name = lit.value(); + Ok(()) + } else { + Err(meta.error("expected `name = \"...\"`")) + } + }); + + break; + } + + Some(quote! { + (#exported_name, #sqlite_type) + }) + }); // Build a unique static name for the slice. let const_name_str = format!( "{}_ATTR_SLICE", @@ -106,3 +121,64 @@ pub fn derive_iterable(input: TokenStream) -> TokenStream { TokenStream::from(expanded) } + +#[proc_macro_derive(InstanceAsArray, attributes(InstanceAsArray, SKIP))] +pub fn derive_instance_as_array(input: TokenStream) -> TokenStream { + use syn::{Data, DeriveInput, Fields, Type, parse_macro_input}; + + let input = parse_macro_input!(input as DeriveInput); + let struct_name = &input.ident; + + // Read #[InstanceAsSlice(Type = "...")] + let mut output_ty: Option = None; + + for attr in &input.attrs { + if !attr.path().is_ident("InstanceAsArray") { + continue; + } + + attr.parse_nested_meta(|meta| { + if meta.path.is_ident("Type") { + let value = meta.value()?; + let ty: Type = value.parse()?; + output_ty = Some(ty); + Ok(()) + } else { + Err(meta.error("expected `Type = ...`")) + } + }) + .unwrap(); + } + + let output_ty = output_ty.expect("Missing #[InstanceAsArray(Type = YourType)] attribute."); + + let fields = match &input.data { + Data::Struct(data) => match &data.fields { + Fields::Named(fields) => &fields.named, + _ => panic!("Only named structs are supported."), + }, + _ => panic!("Only structs are supported."), + }; + + let field_idents: Vec<_> = fields + .iter() + .filter(|field| !field.attrs.iter().any(|a| a.path().is_ident("SKIP"))) + .map(|field| field.ident.as_ref().unwrap()) + .collect(); + + let field_count = field_idents.len(); + + let expanded = quote! { + impl #struct_name { + pub fn instance_as_array(&self) -> [#output_ty; #field_count] { + [ + #( + ::core::convert::Into::<#output_ty>::into(&self.#field_idents) + ),* + ] + } + } + }; + + TokenStream::from(expanded) +} diff --git a/crates/weaponry/Cargo.toml b/crates/weaponry/Cargo.toml index 19586ad..e3e6043 100644 --- a/crates/weaponry/Cargo.toml +++ b/crates/weaponry/Cargo.toml @@ -16,7 +16,7 @@ rusqlite = {workspace = true} serde_rusqlite = {workspace = true} serde_json = {workspace = true} handlebars = {workspace = true} -strum = { version = "0.28.0", features = ["derive"] } +strum = {workspace = true} thiserror = "2.0.18" charming = { version = "0.4.0", features = [] } diff --git a/crates/weaponry/src/weaponry_structs/equipement_advanced_tools.rs b/crates/weaponry/src/weaponry_structs/equipement_advanced_tools.rs index 9c3d2a3..a85dcd6 100644 --- a/crates/weaponry/src/weaponry_structs/equipement_advanced_tools.rs +++ b/crates/weaponry/src/weaponry_structs/equipement_advanced_tools.rs @@ -355,12 +355,9 @@ mod test { let eq = new_inner_eq(); assert_close!( average_damage(&eq, &[Precision(9)], &[Dices(9)]), - 13.999999999 - ); - assert_close!( - average_damage(&eq, &[Precision(4)], &[Dices(4)]), - 10.1119999 + 11.999999826 ); + assert_close!(average_damage(&eq, &[Precision(4)], &[Dices(4)]), 9.753599); } #[test] @@ -401,7 +398,7 @@ mod test { Dices(3), Precision(10), ), - 14., + 12., ), ( BestDamageScenarios::from_action_constraints_it( @@ -461,7 +458,7 @@ mod test { Dices(3), Precision(10), ), - 14., + 12., ), ( BestDamageScenarios::from_action_constraints_it( @@ -481,7 +478,7 @@ mod test { Dices(6), Precision(10), ), - 28., + 24., ), ( BestDamageScenarios::from_action_constraints_it( @@ -501,7 +498,7 @@ mod test { Dices(3), Precision(10), ), - 14., + 12., ), ( BestDamageScenarios::from_action_constraints_it( @@ -511,7 +508,7 @@ mod test { Dices(3), Precision(10), ), - 14., + 12., ), ( BestDamageScenarios::from_action_constraints_it( @@ -531,7 +528,7 @@ mod test { Dices(6), Precision(10), ), - 28., + 24., ), ( BestDamageScenarios::from_action_constraints_it( @@ -581,15 +578,15 @@ mod test { }; assert_close!( get_damage_with_simulation(&eq1, Actions(2), Attacks(1)), - 8.3998 + 7.1999 ); assert_close!( get_damage_with_simulation(&eq2, Actions(2), Attacks(1)), - 9.6936 + 8.3624 ); assert_close!( get_damage_with_simulation(&eq3, Actions(2), Attacks(1)), - 9.6936 + 8.36249 ); } #[test] diff --git a/ravenous_databases b/ravenous_databases index 01dbdc1..265a896 160000 --- a/ravenous_databases +++ b/ravenous_databases @@ -1 +1 @@ -Subproject commit 01dbdc14a30d63a555aa5848619f941585934fd3 +Subproject commit 265a89610bcb3ec621e0386ec2284e49f2b5288e