weapons #49

Merged
Dandaedre merged 2 commits from weapons into project_weaponry 2025-02-19 09:30:07 +01:00
10 changed files with 252 additions and 64 deletions

View File

@ -10,7 +10,7 @@ csv = "1.3.1"
fastrand = "2.3.0"
pretty_assertions = "1.4.1"
probability = "0.20.3"
rusqlite = { version = "0.33.0", features = ["bundled"] }
rusqlite = { version = "0.33.0" } # , features = ["bundled"]
serde = { version = "1.0.217", features = ["derive"] }
serde_rusqlite = "0.37.0"
serde_json = { version = "1.0.138", features = ["alloc"] }

Binary file not shown.

View File

@ -0,0 +1,68 @@
// Workspace: weaponry
// File: examples/typical_wl_recipe.rs
//! Example of a typical workload
//!
use more_fields::FieldsAsSlice;
use serde_rusqlite::to_params_named;
use weaponry::interfaces::RecipeDatabase;
use weaponry::weaponry_structs::equipement_impl_database::EquipementDatabase;
use weaponry::weaponry_structs::equipement_structs::{
DatabaseEquipementStats, InnerEquipementStats,
};
fn main() {
let db = EquipementDatabase::new("./databases/weapons.db").unwrap();
let mut data_eg = DatabaseEquipementStats::random_new();
// data_eg.id = fastrand::u8(1..u8::MAX);
// data_eg.damage_type = serde_json::to_string(&Some(DamageType(vec![DamageMod::Primary(
// PhysicalDamageType::Blunt,
// )])))
// .unwrap();
// data_eg.category = serde_json::to_string(&Some(WeaponCategory::Dagger)).unwrap();
// data_eg.target = serde_json::to_string(&Some(WeaponCategory::Dagger)).unwrap();
// data_eg.special =
// serde_json::to_string(&SpecialCategory(vec!["noo".to_string(), "boo".to_string()]))
// .unwrap();
// data_eg.reload_cost = serde_json::to_string(&Some(12)).unwrap();
data_eg.id = fastrand::u8(1..u8::MAX);
db.initialize_empty_table::<DatabaseEquipementStats>("Equipements")
.unwrap();
let sql = &format!(
"INSERT INTO Equipements ({}) VALUES ({})",
DatabaseEquipementStats::attributes_slice()
.iter()
// .filter_map(|(k, _v)| (*k != "id").then_some(*k))
.map(|(k, _v)| *k)
.collect::<Vec<_>>()
.join(", "),
DatabaseEquipementStats::attributes_slice()
.iter()
// .filter_map(|(k, _v)| (*k != "id").then_some(":".to_string() + *k))
.map(|(k, _v)| ":".to_string() + *k)
.collect::<Vec<_>>()
.join(", ")
);
println!("{}", sql);
let r = db.conn.execute(
sql,
to_params_named(&data_eg).unwrap().to_slice().as_slice(),
);
println!("{:?}", r);
let v = db.serialize_vec_from_table::<DatabaseEquipementStats>("Equipements", None);
// println!("{:#?}", v);
println!(
"{:#?}",
v.unwrap()
.into_iter()
.map(InnerEquipementStats::try_from)
.collect::<Vec<_>>()
);
// let mut r = db.conn.prepare("SELECT * FROM InnerStats").unwrap();
// let mut v = r.query([]).unwrap();
// println!("{:?}:\n {:#?}", db, r);
}

View File

@ -10,8 +10,12 @@ use thiserror::Error;
pub enum FatalEquipementError {
#[error("Rusqlite failed to connect to the given path {0}")]
RusqliteConnection(#[from] rusqlite::Error),
#[error("Deserialization from object : {0}")]
#[error("Deserialization from object failed : {0}")]
SerdeRusqlite(#[from] serde_rusqlite::Error),
#[error("Deserialisation from json failed : {0}")]
SerdeJSON(#[from] serde_json::Error),
}
#[derive(Error, Debug)]

View File

@ -165,11 +165,12 @@ pub trait RecipeDatabase {
Self: std::marker::Sized;
/// Serialize a vector of objects of the given type in the specified table with an optional filter of the underlying database
fn serialize_vec_from_table<T: DeserializeOwned + more_fields::FieldsAsSlice>(
/// The FROM type is the original data, directly deserialized from the table
fn serialize_vec_from_table<FROM: DeserializeOwned + more_fields::FieldsAsSlice>(
&self,
table: &str,
filter: Option<&str>,
) -> std::result::Result<Vec<T>, FatalEquipementError>;
) -> std::result::Result<Vec<FROM>, FatalEquipementError>;
/// Initialize an empty database & table
fn initialize_empty_table<T: FieldsAsSlice>(

View File

@ -10,7 +10,8 @@ use strum::Display;
#[derive(Clone, Default, Debug, Deserialize, Serialize)]
#[cfg_attr(test, derive(PartialEq))]
/// The special category, a vec of string, for display purposes only
pub struct SpecialCategory(pub(super) Vec<String>);
// TODO: avoid pub make an impl ?
pub struct SpecialCategory(pub Vec<String>);
/// The kind of target this nature can apply to
#[derive(Clone)]
@ -24,7 +25,7 @@ pub enum NatureTarget {
}
/// Enum of all different physical weapon damage types
#[allow(clippy::missing_docs_in_private_items)]
#[allow(clippy::missing_docs_in_private_items, missing_docs)]
#[derive(Clone, Debug, Deserialize, Serialize)]
#[cfg_attr(test, derive(PartialEq))]
pub enum PhysicalDamageType {
@ -32,13 +33,6 @@ pub enum PhysicalDamageType {
Slash,
Pierce,
}
impl From<&str> for PhysicalDamageType {
fn from(value: &str) -> Self {
let _ = value;
// Matchcase for all damage types
todo!()
}
}
/// Weapon damage, combining the base weapon damage type and it's level
///
@ -52,21 +46,15 @@ pub enum DamageMod {
Tertiary(PhysicalDamageType),
}
impl From<&str> for DamageMod {
fn from(value: &str) -> Self {
let _ = value;
// Detect [] and recurse from
todo!()
}
}
/// Combined damage type, as a vector of all damage types
///
/// Meant to be serialised to tex and deserialized directly from the table
#[derive(Clone, Debug, Deserialize, Serialize)]
#[cfg_attr(test, derive(PartialEq))]
pub struct DamageType(pub(super) Vec<DamageMod>);
// TODO: avoid pub make an impl ?
pub struct DamageType(pub Vec<DamageMod>);
// TODO: Find a better way to make an easy creation at least for tests
impl From<&str> for DamageType {
fn from(value: &str) -> Self {
let _ = value;
@ -109,18 +97,6 @@ pub enum WeaponCategory {
Cannon,
}
impl From<&str> for WeaponCategory {
fn from(value: &str) -> Self {
let _ = value;
todo!()
}
}
// TODO: Consider this for test
// impl Equipement{
// fn random_equipement(){}
// }
#[cfg(test)]
mod test {
// use super::*;

View File

@ -12,7 +12,10 @@ use crate::interfaces::RecipeDatabase;
use rusqlite::Connection;
use serde::de::DeserializeOwned;
use super::equipement_structs::{DatabaseEquipementStats, InnerEquipementStats};
/// Struct for database connection.
#[derive(Debug)]
pub struct EquipementDatabase {
/// Connection parameter for rusqlite
pub conn: rusqlite::Connection,
@ -45,3 +48,42 @@ impl RecipeDatabase for EquipementDatabase {
Ok(())
}
}
// #[allow(clippy::useless_conversion)]
impl TryFrom<DatabaseEquipementStats> for InnerEquipementStats {
type Error = FatalEquipementError;
fn try_from(value: DatabaseEquipementStats) -> Result<Self, Self::Error> {
Ok(Self {
id: vec![value.id], // Special case where manual is better than serde
name: vec![value.name],
rarity: value.rarity, // Generic case, into(), serde or cast are equivalent
cost: value.cost,
difficulty: value.difficulty,
tier: value.tier,
damage: value.damage,
p_damage: value.p_damage,
precision: value.precision,
rmax: value.rmax,
armor_break: value.armor_break,
armor_pierce: value.armor_pierce,
antimaterial: value.antimaterial,
damage_type: serde_json::from_str(&value.damage_type)?, // Serde and derive are godsent
protection: value.protection,
integrity: value.integrity,
torque_two_handed: value.torque_two_handed,
torque_one_handed: value.torque_one_handed,
dodge: value.dodge,
parry: value.parry,
speed: value.speed,
stealth: value.stealth,
category: serde_json::from_str(&value.category)?,
target: serde_json::from_str(&value.target)?,
special: serde_json::from_str(&value.special)?,
action_cost: value.action_cost,
reload_cost: serde_json::from_str(&value.reload_cost)?,
range: value.range,
agility_bonus: value.agility_bonus,
})
}
}

View File

@ -11,7 +11,7 @@
use crate::weaponry_structs::Equipement;
use crate::weaponry_structs::InitialEquipementList;
use crate::weaponry_structs::equipement_structs::InnerEquipementStats;
use crate::weaponry_structs::equipement_structs::DatabaseEquipementStats;
use crate::{
error::{EquipementError, FatalEquipementError},
interfaces::{RecipeCollection, RecipeDatabase, Scenario, ViewTable},
@ -72,15 +72,21 @@ pub struct CrossRecipeScenario {
/// Automatically deserialize into an equipement
// TODO: This macro only exists because no blanket implementation or function does this *relatively* easy step
// TODO: This place the place where all new impl and simplifications will be done
macro_rules! deserde_into_equipement {
( $db:expr, $name:expr, $type:ident) => {
InitialEquipementList::from_vectored(
$db.serialize_vec_from_table::<InnerEquipementStats>(
$db.serialize_vec_from_table::<DatabaseEquipementStats>(
"Equipement",
Some(&format!("CATEGORY == {}", $name)),
)?
.into_iter()
.map(|eq| $type { stats: eq }.into())
.map(|eq| {
$type {
stats: eq.try_into().unwrap(),
}
.into()
})
.collect::<Vec<Equipement>>(),
)
};

View File

@ -52,72 +52,148 @@ impl<T> FilterFunction<T> {
Self(Box::new(Rc::new(filter)))
}
}
/// The inner statistics of the equipement, used across all parts and final weapon
#[allow(clippy::missing_docs_in_private_items, missing_docs)]
#[derive(Clone, Default, FieldsAsSlice, Debug, Deserialize, Serialize)]
#[derive(Clone, Default, FieldsAsSlice, Debug)]
#[cfg_attr(test, derive(PartialEq))]
pub struct InnerEquipementStats {
#[INTEGER]
pub id: Vec<u8>,
pub name: Vec<String>,
#[INTEGER]
pub(super) rarity: u8,
#[INTEGER]
pub(super) cost: u8,
#[INTEGER]
pub(super) difficulty: u8,
#[INTEGER]
pub(super) tier: u8,
#[INTEGER]
pub(super) damage: u8,
#[INTEGER]
pub(super) p_damage: u8,
#[INTEGER]
pub(super) precision: i8,
#[INTEGER]
pub(super) rmax: u8,
#[INTEGER]
pub(super) armor_break: u8,
#[INTEGER]
pub(super) armor_pierce: u8,
#[INTEGER]
pub(super) antimaterial: u8,
pub(super) damage_type: Option<DamageType>,
#[INTEGER]
pub(super) protection: u8,
#[INTEGER]
pub(super) integrity: u8,
#[INTEGER]
pub(super) torque_two_handed: u8,
#[INTEGER]
pub(super) torque_one_handed: u8,
#[INTEGER]
pub(super) dodge: u8,
#[INTEGER]
pub(super) parry: u8,
#[INTEGER]
pub(super) speed: u8,
#[INTEGER]
pub(super) stealth: u8,
pub(super) category: Option<WeaponCategory>,
pub(super) target: Option<WeaponCategory>,
pub(super) special: SpecialCategory,
#[INTEGER]
pub(super) action_cost: u8,
pub(super) reload_cost: Option<u8>,
#[INTEGER]
pub(super) range: u8,
#[INTEGER]
pub(super) agility_bonus: u8,
}
// TODO: This implementation of default is painfull
// TODO: Have either an auto-macro implementation or a manual one
// TODO: This implementation is Quasi-redondant
// TODO: Have a way to limit code duplication
#[allow(clippy::missing_docs_in_private_items, missing_docs)]
#[derive(Clone, FieldsAsSlice, Debug, Deserialize, Serialize)]
#[cfg_attr(test, derive(PartialEq))]
pub struct DatabaseEquipementStats {
#[INTEGER]
pub id: u8,
pub meta_category: String,
pub name: String,
#[INTEGER]
pub rarity: u8,
#[INTEGER]
pub cost: u8,
#[INTEGER]
pub difficulty: u8,
#[INTEGER]
pub tier: u8,
#[INTEGER]
pub damage: u8,
#[INTEGER]
pub p_damage: u8,
#[INTEGER]
pub precision: i8,
#[INTEGER]
pub rmax: u8,
#[INTEGER]
pub armor_break: u8,
#[INTEGER]
pub armor_pierce: u8,
#[INTEGER]
pub antimaterial: u8,
pub damage_type: String,
#[INTEGER]
pub protection: u8,
#[INTEGER]
pub integrity: u8,
#[INTEGER]
pub torque_two_handed: u8,
#[INTEGER]
pub torque_one_handed: u8,
#[INTEGER]
pub dodge: u8,
#[INTEGER]
pub parry: u8,
#[INTEGER]
pub speed: u8,
#[INTEGER]
pub stealth: u8,
pub category: String,
pub target: String,
pub special: String,
#[INTEGER]
pub action_cost: u8,
pub reload_cost: String,
#[INTEGER]
pub range: u8,
#[INTEGER]
pub agility_bonus: u8,
}
impl Default for DatabaseEquipementStats {
fn default() -> Self {
Self {
id: 0,
meta_category: "EqShape".to_string(),
name: String::new(),
damage_type: serde_json::to_string(&None::<DamageType>).unwrap(),
category: serde_json::to_string(&None::<WeaponCategory>).unwrap(),
target: serde_json::to_string(&None::<WeaponCategory>).unwrap(),
special: serde_json::to_string(&SpecialCategory::default()).unwrap(),
reload_cost: serde_json::to_string(&None::<u8>).unwrap(),
rarity: 0,
cost: 0,
difficulty: 0,
tier: 0,
damage: 0,
p_damage: 0,
precision: 0,
rmax: 0,
armor_break: 0,
armor_pierce: 0,
antimaterial: 0,
protection: 0,
integrity: 0,
torque_two_handed: 0,
torque_one_handed: 0,
dodge: 0,
parry: 0,
speed: 0,
stealth: 0,
range: 0,
agility_bonus: 0,
action_cost: 0,
}
}
}
#[allow(dead_code)]
/// A manually implemented hashmap of all values
#[doc(hidden)]
macro_rules! r {
() => {
fastrand::u8(1..10)
fastrand::u8(1..u8::MAX)
};
}
// TODO: Make this a test requirement or hide it behind a profile
@ -134,6 +210,20 @@ impl InnerEquipementStats {
}
}
}
// TODO: Make this a test requirement or hide it behind a profile
impl DatabaseEquipementStats {
/// Testing function to fuzz data
pub fn random_new() -> Self {
Self {
id: r!(),
range: r!(),
damage: r!(),
p_damage: r!(),
protection: r!(),
..Default::default()
}
}
}
/// Shape of the equipement, first mandatory part of an equipement
#[derive(Default)]

View File

@ -32,5 +32,6 @@ mod equipement_views;
pub use equipement_structs::{Equipement, InitialEquipementList};
// All generic fields
#[allow(unused_imports)]
// #[allow(unused_imports)]
pub use equipement_fields::PhysicalDamageType;
pub use equipement_fields::{DamageMod, DamageType, NatureTarget, SpecialCategory, WeaponCategory};