Compare commits
6 Commits
main
...
legacy_wea
| Author | SHA1 | Date |
|---|---|---|
|
|
5f0ddbeefb | |
|
|
c0d008b6a4 | |
|
|
e838e4e286 | |
|
|
897ea9983a | |
|
|
51bbf45b57 | |
|
|
a155e53b30 |
|
|
@ -1,12 +0,0 @@
|
|||
specs:
|
||||
- name: base
|
||||
prefix: r
|
||||
source_url: "https://github.com/bearcove/tracey"
|
||||
include:
|
||||
- "requirements/**/*.md"
|
||||
impls:
|
||||
- name: main
|
||||
include:
|
||||
- "crates/**/*.rs"
|
||||
exclude:
|
||||
- "target/**"
|
||||
|
|
@ -16,16 +16,19 @@ Cargo.lock
|
|||
# MSVC Windows builds of rustc generate these, which store debugging information
|
||||
*.pdb
|
||||
|
||||
|
||||
|
||||
# Added by cargo
|
||||
|
||||
/target
|
||||
|
||||
*.html
|
||||
.cargo/
|
||||
.tracey/
|
||||
*.json.gz
|
||||
callgrind*
|
||||
cache.out
|
||||
tarpaulin-report.html
|
||||
*.html
|
||||
*.bkp
|
||||
coverage/
|
||||
testdata/
|
||||
# snapshots/
|
||||
|
|
|
|||
|
|
@ -1,4 +0,0 @@
|
|||
[submodule "ravenous_databases"]
|
||||
path = ravenous_databases
|
||||
url = git@git.dandaedre.com:Ravenous/ravenous_databases.git
|
||||
# url = https://proxy.dandaedre.com/gitea/Ravenous/ravenous_databases.git
|
||||
|
|
@ -1,8 +0,0 @@
|
|||
[last_run_clean]
|
||||
run_status = "Success"
|
||||
lines_parsed = 151
|
||||
coverage = 20.88
|
||||
|
||||
[last_run_clean.run_duration]
|
||||
secs = 22
|
||||
nanos = 771992149
|
||||
62
Cargo.toml
62
Cargo.toml
|
|
@ -1,17 +1,23 @@
|
|||
cargo-features = ["codegen-backend"]
|
||||
# cargo-features = ["edition2024"]
|
||||
|
||||
[workspace]
|
||||
members = ["crates/*"]
|
||||
members = [ "cli_parser", "config", "graphs", "make", "more_fields", "more_fields_macro",
|
||||
"ravenous-tools", "stats",
|
||||
"tablegen", "weaponry",
|
||||
]
|
||||
resolver = "3"
|
||||
|
||||
# [workspace.package]
|
||||
# edition = "2024"
|
||||
# license = "MIT OR Apache-2.0"
|
||||
[workspace.package]
|
||||
version = "0.3.34"
|
||||
version = "0.2.0"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[profile.dev]
|
||||
debug = 0
|
||||
debug = true
|
||||
strip = false
|
||||
codegen-backend = "cranelift"
|
||||
split-debuginfo = "off"
|
||||
# codegen-backend = "cranelift"
|
||||
|
||||
[profile.release]
|
||||
|
|
@ -29,47 +35,3 @@ lto = false
|
|||
codegen-units = 256
|
||||
incremental = true
|
||||
panic = "abort"
|
||||
|
||||
# [profile.dev-analysis]
|
||||
# inherits = "dev"
|
||||
# opt-level = 0
|
||||
# debug = 0
|
||||
# strip = "none"
|
||||
# lto = false
|
||||
# # codegen-units = 256
|
||||
# incremental = true
|
||||
# # codegen-backend = "cranelift"
|
||||
|
||||
[workspace.dependencies]
|
||||
config = {path = "./crates/config"}
|
||||
tablegen = {path = "./crates/tablegen"}
|
||||
graphs = {path = "./crates/graphs"}
|
||||
cli_parser = {path = "./crates/cli_parser"}
|
||||
stats = {path = "./crates/stats"}
|
||||
make = {path = "./crates/make"}
|
||||
fast_class = {path = "./crates/fast_class"}
|
||||
formatter = {path = "./crates/formatter"}
|
||||
weaponry = {path = "./crates/weaponry"}
|
||||
more_fields = {path = "./crates/more_fields"}
|
||||
monsters = {path = "./crates/monsters"}
|
||||
|
||||
anyhow = "1.0.103"
|
||||
toml = "1.1.3"
|
||||
clap = { version = "4.6.1", features = ["derive"] }
|
||||
phf = { version = "0.14.0", features = ["macros"] }
|
||||
regex = "1.13.0"
|
||||
regex_static = "0.1.1"
|
||||
serde = { version = "1.0.228", features = ["derive", "alloc"] }
|
||||
serde_json = { version = "1.0.150", features = ["alloc"] }
|
||||
csv = "1.4.0"
|
||||
ron = "0.12.2"
|
||||
glob = "0.3.3"
|
||||
tokio = { version = "1.52.3", features = ["full"] }
|
||||
dynfmt = { version = "0.1.5", features = ["curly"] }
|
||||
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"
|
||||
strum = { version = "0.28.0", features = ["derive"] }
|
||||
probability = "0.20.3"
|
||||
|
|
|
|||
|
|
@ -1,69 +0,0 @@
|
|||
// Don't forget to add http://192.168.1.37:8080/gitea-webhook/post as a gitea webhook
|
||||
|
||||
pipeline {
|
||||
agent { label 'rust_no_docker' }
|
||||
/* ===============
|
||||
BEGIN USER CONFIG
|
||||
================== */
|
||||
|
||||
environment {
|
||||
DEPLOY_DIR = "/mnt/books/rust_doc/efo/" // Important, all books are in /mnt/book
|
||||
MDBOOK_BUILD_DIR = "target/doc/"
|
||||
}
|
||||
|
||||
stages {
|
||||
stage('Checkout') {
|
||||
steps {
|
||||
checkout scm // Checkout intead of full clone
|
||||
}
|
||||
}
|
||||
|
||||
stage('Update') {
|
||||
steps {
|
||||
sh "rustup update"
|
||||
// sh "rustup show"
|
||||
}
|
||||
}
|
||||
|
||||
/* ===============
|
||||
END USER CONFIG
|
||||
================== */
|
||||
|
||||
stage('Build Book') {
|
||||
steps {
|
||||
script {
|
||||
if (env.BRANCH_NAME == 'origin/review' || env.BRANCH_NAME == 'review' || env.BRANCH_NAME == 'origin/dev-ci' || env.BRANCH_NAME == 'dev-ci') {
|
||||
sh 'cargo test'
|
||||
// sh 'cargo doc'
|
||||
// sh 'echo "Deploying to ${DEPLOY_DIR}"'
|
||||
// sh 'mkdir -p ${DEPLOY_DIR}'
|
||||
// sh 'rsync -a --delete ${MDBOOK_BUILD_DIR}/ ${DEPLOY_DIR}'
|
||||
} else if (env.BRANCH_NAME == 'origin/master' || env.BRANCH_NAME == 'master') {
|
||||
sh 'cargo test'
|
||||
// sh 'cargo doc'
|
||||
// sh 'echo "Deploying to ${DEPLOY_DIR}"'
|
||||
// sh 'mkdir -p ${DEPLOY_DIR}'
|
||||
// sh 'rsync -a --delete ${MDBOOK_BUILD_DIR}/ ${DEPLOY_DIR}'
|
||||
} else {
|
||||
echo "Unknown branch: ${env.BRANCH_NAME} - skipping build."
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
post {
|
||||
success {
|
||||
publishChecks conclusion: 'SUCCESS', name: 'Build Successful', summary: 'The build was successful', text: 'The build was sucessful', title: 'Build Successful'
|
||||
echo '✅ Build Deployed!'
|
||||
}
|
||||
failure {
|
||||
publishChecks conclusion: 'FAILURE', name: 'Build Failed', summary: 'The build failed', text: 'The build was a failure', title: 'Build failed'
|
||||
echo '❌Build Failed to Deploy'
|
||||
}
|
||||
unstable{
|
||||
publishChecks conclusion: 'ACTION_REQUIRED', name: 'Build Unstable', summary: 'Unstable build', text: 'Unstable build', title: 'Build Unstable'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -1 +1 @@
|
|||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="122" height="18" role="img" aria-label="test-coverage: 21%"><title>test-coverage: 21%</title><linearGradient id="bms-fdc6068972daa61b" x2="0" y2="100%"><stop offset="0" stop-color="#fff" stop-opacity=".7"/><stop offset=".1" stop-color="#aaa" stop-opacity=".1"/><stop offset=".9" stop-color="#000" stop-opacity=".3"/><stop offset="1" stop-color="#000" stop-opacity=".5"/></linearGradient><clipPath id="bmr-fdc6068972daa61b"><rect width="122" height="18" rx="4" fill="#fff"/></clipPath><g clip-path="url(#bmr-fdc6068972daa61b)"><rect width="87" height="18" fill="#555"/><rect x="87" width="35" height="18" fill="#97ca00"/><rect width="122" height="18" fill="url(#bms-fdc6068972daa61b)"/></g><g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" text-rendering="geometricPrecision" font-size="110"><text aria-hidden="true" x="445" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="770">test-coverage</text><text x="445" y="130" transform="scale(.1)" fill="#fff" textLength="770">test-coverage</text><text aria-hidden="true" x="1035" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="250">21%</text><text x="1035" y="130" transform="scale(.1)" fill="#fff" textLength="250">21%</text></g></svg>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="122" height="18" role="img" aria-label="test-coverage: 38%"><title>test-coverage: 38%</title><linearGradient id="bms-ef2093ce1077dbe3" x2="0" y2="100%"><stop offset="0" stop-color="#fff" stop-opacity=".7"/><stop offset=".1" stop-color="#aaa" stop-opacity=".1"/><stop offset=".9" stop-color="#000" stop-opacity=".3"/><stop offset="1" stop-color="#000" stop-opacity=".5"/></linearGradient><clipPath id="bmr-ef2093ce1077dbe3"><rect width="122" height="18" rx="4" fill="#fff"/></clipPath><g clip-path="url(#bmr-ef2093ce1077dbe3)"><rect width="87" height="18" fill="#555"/><rect x="87" width="35" height="18" fill="#e05d44"/><rect width="122" height="18" fill="url(#bms-ef2093ce1077dbe3)"/></g><g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" text-rendering="geometricPrecision" font-size="110"><text aria-hidden="true" x="445" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="770">test-coverage</text><text x="445" y="130" transform="scale(.1)" fill="#fff" textLength="770">test-coverage</text><text aria-hidden="true" x="1035" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="250">38%</text><text x="1035" y="130" transform="scale(.1)" fill="#fff" textLength="250">38%</text></g></svg>
|
||||
|
|
|
|||
|
Before Width: | Height: | Size: 1.3 KiB After Width: | Height: | Size: 1.3 KiB |
|
|
@ -1 +1 @@
|
|||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="82" height="18" role="img" aria-label="test: passing"><title>test: passing</title><linearGradient id="bms-5402c39dce014bd3" x2="0" y2="100%"><stop offset="0" stop-color="#fff" stop-opacity=".7"/><stop offset=".1" stop-color="#aaa" stop-opacity=".1"/><stop offset=".9" stop-color="#000" stop-opacity=".3"/><stop offset="1" stop-color="#000" stop-opacity=".5"/></linearGradient><clipPath id="bmr-5402c39dce014bd3"><rect width="82" height="18" rx="4" fill="#fff"/></clipPath><g clip-path="url(#bmr-5402c39dce014bd3)"><rect width="31" height="18" fill="#555"/><rect x="31" width="51" height="18" fill="#97ca00"/><rect width="82" height="18" fill="url(#bms-5402c39dce014bd3)"/></g><g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" text-rendering="geometricPrecision" font-size="110"><text aria-hidden="true" x="165" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="210">test</text><text x="165" y="130" transform="scale(.1)" fill="#fff" textLength="210">test</text><text aria-hidden="true" x="555" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="410">passing</text><text x="555" y="130" transform="scale(.1)" fill="#fff" textLength="410">passing</text></g></svg>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="82" height="18" role="img" aria-label="test: passing"><title>test: passing</title><linearGradient id="bms-5402c39dce014bd3" x2="0" y2="100%"><stop offset="0" stop-color="#fff" stop-opacity=".7"/><stop offset=".1" stop-color="#aaa" stop-opacity=".1"/><stop offset=".9" stop-color="#000" stop-opacity=".3"/><stop offset="1" stop-color="#000" stop-opacity=".5"/></linearGradient><clipPath id="bmr-5402c39dce014bd3"><rect width="82" height="18" rx="4" fill="#fff"/></clipPath><g clip-path="url(#bmr-5402c39dce014bd3)"><rect width="31" height="18" fill="#555"/><rect x="31" width="51" height="18" fill="#97ca00"/><rect width="82" height="18" fill="url(#bms-5402c39dce014bd3)"/></g><g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" text-rendering="geometricPrecision" font-size="110"><text aria-hidden="true" x="165" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="210">test</text><text x="165" y="130" transform="scale(.1)" fill="#fff" textLength="210">test</text><text aria-hidden="true" x="555" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="410">passing</text><text x="555" y="130" transform="scale(.1)" fill="#fff" textLength="410">passing</text></g></svg>
|
||||
|
|
|
|||
|
Before Width: | Height: | Size: 1.3 KiB After Width: | Height: | Size: 1.3 KiB |
|
|
@ -1 +1 @@
|
|||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="90" height="18" role="img" aria-label="version: 0.3.0"><title>version: 0.3.0</title><linearGradient id="bms-d6e9a62d4ef68176" x2="0" y2="100%"><stop offset="0" stop-color="#fff" stop-opacity=".7"/><stop offset=".1" stop-color="#aaa" stop-opacity=".1"/><stop offset=".9" stop-color="#000" stop-opacity=".3"/><stop offset="1" stop-color="#000" stop-opacity=".5"/></linearGradient><clipPath id="bmr-d6e9a62d4ef68176"><rect width="90" height="18" rx="4" fill="#fff"/></clipPath><g clip-path="url(#bmr-d6e9a62d4ef68176)"><rect width="51" height="18" fill="#555"/><rect x="51" width="39" height="18" fill="#fe7d37"/><rect width="90" height="18" fill="url(#bms-d6e9a62d4ef68176)"/></g><g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" text-rendering="geometricPrecision" font-size="110"><text aria-hidden="true" x="265" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="410">version</text><text x="265" y="130" transform="scale(.1)" fill="#fff" textLength="410">version</text><text aria-hidden="true" x="695" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="290">0.3.0</text><text x="695" y="130" transform="scale(.1)" fill="#fff" textLength="290">0.3.0</text></g></svg>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="90" height="18" role="img" aria-label="version: 0.2.0"><title>version: 0.2.0</title><linearGradient id="bms-db7098c97f02adb0" x2="0" y2="100%"><stop offset="0" stop-color="#fff" stop-opacity=".7"/><stop offset=".1" stop-color="#aaa" stop-opacity=".1"/><stop offset=".9" stop-color="#000" stop-opacity=".3"/><stop offset="1" stop-color="#000" stop-opacity=".5"/></linearGradient><clipPath id="bmr-db7098c97f02adb0"><rect width="90" height="18" rx="4" fill="#fff"/></clipPath><g clip-path="url(#bmr-db7098c97f02adb0)"><rect width="51" height="18" fill="#555"/><rect x="51" width="39" height="18" fill="#fe7d37"/><rect width="90" height="18" fill="url(#bms-db7098c97f02adb0)"/></g><g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" text-rendering="geometricPrecision" font-size="110"><text aria-hidden="true" x="265" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="410">version</text><text x="265" y="130" transform="scale(.1)" fill="#fff" textLength="410">version</text><text aria-hidden="true" x="695" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="290">0.2.0</text><text x="695" y="130" transform="scale(.1)" fill="#fff" textLength="290">0.2.0</text></g></svg>
|
||||
|
|
|
|||
|
Before Width: | Height: | Size: 1.3 KiB After Width: | Height: | Size: 1.3 KiB |
|
|
@ -0,0 +1,9 @@
|
|||
[package]
|
||||
name = "cli_parser"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
config = {path = "../config"}
|
||||
clap = { version = "4.5.28", features = ["derive"] }
|
||||
serde = { version = "1.0.217", features = ["derive", "alloc"] }
|
||||
|
|
@ -4,12 +4,11 @@
|
|||
|
||||
use clap::{Args, Parser, Subcommand};
|
||||
use config::{
|
||||
analysis::{AnalysisConfig, WeaponConfig},
|
||||
fast_tables::FastTableConfig,
|
||||
formatter::FormatterConfig,
|
||||
graph::GraphConfig,
|
||||
make::{HELP_BLOCK_SELECTION, MakeTargets, VerboseLevel},
|
||||
monsters::{MonsterConfig, MonsterMarkup, WeaponExport},
|
||||
make::{
|
||||
HELP_BLOCK_SELECTION, HELP_BUILD_TARGET_LIST, HELP_VERBOSITY_LEVEL, MakeTargets,
|
||||
VerboseLevel,
|
||||
},
|
||||
statsolver::StatConfig,
|
||||
tablegen::{Craft, TableArgs},
|
||||
};
|
||||
|
|
@ -43,16 +42,8 @@ pub enum Commands {
|
|||
Make(MakeConfig),
|
||||
/// Make all graphs
|
||||
Graphs(GraphConfig),
|
||||
/// Format the file given on input
|
||||
Format(FormatterConfig),
|
||||
/// Generate analysis data
|
||||
Analysis(AnalysisConfig),
|
||||
/// Export all weapon data
|
||||
Weapons(WeaponConfig),
|
||||
/// Better Generation
|
||||
BetterGen(FastTableConfig),
|
||||
/// Monster database handling
|
||||
Monsters(MonsterConfig),
|
||||
// /// Generate analysis data
|
||||
// Analysis(AnalysisConfig)
|
||||
}
|
||||
|
||||
#[derive(Debug, Args)]
|
||||
|
|
@ -73,16 +64,10 @@ pub struct ConfigArgs {
|
|||
#[derive(Deserialize)]
|
||||
/// The config struct, holding all runtime information
|
||||
pub struct Config {
|
||||
/// Config specific for data generation
|
||||
pub data_generation: Datagen,
|
||||
/// Config specific for the classes table generation
|
||||
pub classes: Classes,
|
||||
/// Config for all the tables
|
||||
pub craft: Craft,
|
||||
/// Config for monster exporting
|
||||
pub monster: MonsterMarkup,
|
||||
/// The config for weapon exporting
|
||||
pub weapons: WeaponExport,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
|
|
@ -98,27 +83,21 @@ pub struct Classes {
|
|||
pub end: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
/// The data generation configuration
|
||||
pub struct Datagen {
|
||||
/// Where to find the data generation database
|
||||
pub database: String,
|
||||
}
|
||||
|
||||
// The make structs
|
||||
|
||||
#[derive(Args, Debug, Clone)]
|
||||
// #[command(after_)]
|
||||
/// The configuration struct for the PdfMaker
|
||||
pub struct MakeConfig {
|
||||
/// The filename to compile
|
||||
pub filename: String,
|
||||
|
||||
/// Special target
|
||||
#[arg(short, long)]
|
||||
#[arg(short, long, help = format!("Build with a special target. [{}]", HELP_BUILD_TARGET_LIST.as_str()))]
|
||||
pub target: Option<MakeTargets>,
|
||||
|
||||
/// The verbosity level
|
||||
#[arg(short, long, default_value = "warning")]
|
||||
#[arg(short, long, default_value = "warning", help = format!("The verbosity level. [{}]",HELP_VERBOSITY_LEVEL.as_str()))]
|
||||
pub verbosity: VerboseLevel,
|
||||
|
||||
/// The progress bar style
|
||||
|
|
@ -144,8 +123,4 @@ pub struct MakeConfig {
|
|||
/// Activate shell escape
|
||||
#[arg(short, long)]
|
||||
pub shell_escape: bool,
|
||||
|
||||
/// The pdflatex command
|
||||
#[arg(short, long, default_value_t = String::from("pdflatex"))]
|
||||
pub latex_command: String,
|
||||
}
|
||||
|
|
@ -0,0 +1,12 @@
|
|||
[package]
|
||||
name = "config"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
clap = { version = "4.5.28", features = ["derive"] }
|
||||
phf = { version = "0.11.3", features = ["macros"] }
|
||||
serde = { version = "1.0.217", features = ["derive"] }
|
||||
|
||||
[dev-dependencies]
|
||||
insta = { version = "1.42.2", features = ["yaml"] }
|
||||
|
|
@ -0,0 +1,101 @@
|
|||
// Workspace: config
|
||||
// File: config/src/graph.rs
|
||||
//! The inner config for graph module
|
||||
//!
|
||||
use clap::Args;
|
||||
use phf::phf_map;
|
||||
use std::sync::LazyLock;
|
||||
|
||||
#[derive(Args, Debug, Clone)]
|
||||
/// The configuration struct for the Graph
|
||||
pub struct GraphConfig {
|
||||
/// Special target
|
||||
#[arg(help = format!("The target to execute [{}]", *HELP_STR_TO_GRAPH))]
|
||||
pub target: GraphTargetType,
|
||||
|
||||
/// Alternative origin
|
||||
#[arg(short, long, default_value = "Images/Radar/radar.csv")]
|
||||
pub origin: String,
|
||||
|
||||
/// Alternative destination
|
||||
#[arg(short, long, default_value = "Images/Radar")]
|
||||
pub destination: String,
|
||||
|
||||
/// Alternative config to load (generate a new one with init)
|
||||
#[arg(short, long)]
|
||||
pub config: Option<String>,
|
||||
|
||||
/// Clean all the artefacts (including generated images)
|
||||
#[arg(short, long)]
|
||||
pub all: bool,
|
||||
}
|
||||
|
||||
/// Link from user str input to the action to perform
|
||||
static STR_TO_GRAPH_TARGET_TYPE: phf::Map<&'static str, GraphTargetType> = phf_map! {
|
||||
"generate" => GraphTargetType::Generate,
|
||||
"gen" => GraphTargetType::Generate,
|
||||
"remove" => GraphTargetType::Remove,
|
||||
"clean" => GraphTargetType::Remove,
|
||||
"init" => GraphTargetType::Init,
|
||||
};
|
||||
|
||||
/// Help listing all the actions availables
|
||||
static HELP_STR_TO_GRAPH: LazyLock<String> = LazyLock::new(|| {
|
||||
let targets = STR_TO_GRAPH_TARGET_TYPE
|
||||
.keys()
|
||||
.map(|v| v.to_string())
|
||||
.collect::<Vec<String>>();
|
||||
targets.join(", ").to_string()
|
||||
});
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
#[cfg_attr(test, derive(PartialEq))]
|
||||
/// All target type
|
||||
pub enum GraphTargetType {
|
||||
/// Make all graphs
|
||||
Generate,
|
||||
/// Clean all graphs
|
||||
Remove,
|
||||
/// Initialize the connfig
|
||||
Init,
|
||||
}
|
||||
impl From<&str> for GraphTargetType {
|
||||
fn from(value: &str) -> Self {
|
||||
if let Some(target) = STR_TO_GRAPH_TARGET_TYPE.get(&value.to_lowercase()).cloned() {
|
||||
target
|
||||
} else {
|
||||
panic!(
|
||||
"Invalid target {}. The target available are : [{}]",
|
||||
value, *HELP_STR_TO_GRAPH
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use crate::graph::HELP_STR_TO_GRAPH;
|
||||
|
||||
use super::GraphTargetType;
|
||||
|
||||
#[test]
|
||||
fn test_help_str() {
|
||||
/// Doc comment
|
||||
insta::assert_yaml_snapshot!(HELP_STR_TO_GRAPH.to_string());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_block_prog_and_verbosity() {
|
||||
assert_eq!(GraphTargetType::from("generate"), GraphTargetType::Generate);
|
||||
assert_eq!(GraphTargetType::from("gen"), GraphTargetType::Generate);
|
||||
assert_eq!(GraphTargetType::from("remove"), GraphTargetType::Remove);
|
||||
assert_eq!(GraphTargetType::from("clean"), GraphTargetType::Remove);
|
||||
assert_eq!(GraphTargetType::from("init"), GraphTargetType::Init);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic]
|
||||
fn test_bad_graph() {
|
||||
let _ = GraphTargetType::from("bad_graph");
|
||||
}
|
||||
}
|
||||
|
|
@ -7,11 +7,7 @@
|
|||
#![warn(missing_docs, clippy::missing_docs_in_private_items)]
|
||||
|
||||
// Internal Modules
|
||||
pub mod analysis;
|
||||
pub mod fast_tables;
|
||||
pub mod formatter;
|
||||
pub mod graph;
|
||||
pub mod make;
|
||||
pub mod monsters;
|
||||
pub mod statsolver;
|
||||
pub mod tablegen;
|
||||
|
|
@ -0,0 +1,188 @@
|
|||
// Workspace: config
|
||||
// File: config/src/make.rs
|
||||
//! Makepdf generation structs
|
||||
|
||||
use phf::phf_map;
|
||||
use std::{collections::HashMap, fmt::Debug, sync::LazyLock};
|
||||
|
||||
/// Convert str to verbosity level
|
||||
static STR_TO_VERBOSITY: phf::Map<&'static str, VerboseLevel> = phf_map! {
|
||||
"misc" =>VerboseLevel::Misc,
|
||||
"box" => VerboseLevel::Box,
|
||||
"context" => VerboseLevel::Context,
|
||||
"info" => VerboseLevel::Info,
|
||||
"warning" => VerboseLevel::Warning,
|
||||
"error" => VerboseLevel::Error,
|
||||
"critical" => VerboseLevel::Critical,
|
||||
};
|
||||
|
||||
/// Convert str to build target
|
||||
static STR_TO_BUILD_TARGET: phf::Map<&'static str, MakeTargets> = phf_map! {
|
||||
"all" => MakeTargets::All,
|
||||
"list" => MakeTargets::List,
|
||||
"glossaries" => MakeTargets::Glossaries,
|
||||
"clean" => MakeTargets::Clean,
|
||||
};
|
||||
|
||||
/// List all blocktype
|
||||
pub static HELP_BLOCK_SELECTION: LazyLock<String> = LazyLock::new(|| {
|
||||
let mut targets = BLOCK_PROGRESSION
|
||||
.keys()
|
||||
.map(|v| v.to_owned())
|
||||
.collect::<Vec<String>>();
|
||||
targets.sort();
|
||||
targets.join(", ").to_string()
|
||||
});
|
||||
|
||||
/// List all targets
|
||||
pub static HELP_VERBOSITY_LEVEL: LazyLock<String> = LazyLock::new(|| {
|
||||
let mut targets = STR_TO_VERBOSITY
|
||||
.values()
|
||||
.map(|v| format!("{:?}", v).to_lowercase())
|
||||
.collect::<Vec<String>>();
|
||||
targets.sort();
|
||||
targets.join(", ").to_string()
|
||||
});
|
||||
|
||||
/// List all targets
|
||||
pub static HELP_BUILD_TARGET_LIST: LazyLock<String> = LazyLock::new(|| {
|
||||
let targets = STR_TO_BUILD_TARGET
|
||||
.values()
|
||||
.map(|v| format!("{:?}", v).to_lowercase())
|
||||
.collect::<Vec<String>>();
|
||||
targets.join(", ").to_string()
|
||||
});
|
||||
|
||||
/// The verbosity level
|
||||
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub enum VerboseLevel {
|
||||
/// Shouldn't be printed no matter what
|
||||
None,
|
||||
/// Garbage
|
||||
Misc,
|
||||
/// Boxness, barely above Misc
|
||||
Box,
|
||||
/// Context info (Debug info)
|
||||
Context,
|
||||
/// Usefull info
|
||||
Info,
|
||||
/// Important warnings
|
||||
Warning,
|
||||
/// Errors encountered requiring user input
|
||||
Error,
|
||||
/// Uncatachable errors
|
||||
Critical,
|
||||
/// Literrally uncatchable things
|
||||
Uncatchable,
|
||||
}
|
||||
impl From<&str> for VerboseLevel {
|
||||
fn from(value: &str) -> Self {
|
||||
if let Some(target) = STR_TO_VERBOSITY.get(&value.to_lowercase()).cloned() {
|
||||
target
|
||||
} else {
|
||||
panic!(
|
||||
"Invalid debug level {}. The debug level available are (from highest verbosity to lowest): [{:?}]",
|
||||
value, HELP_VERBOSITY_LEVEL
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// All progress bar styles
|
||||
pub static BLOCK_PROGRESSION: LazyLock<HashMap<String, String>> = LazyLock::new(|| {
|
||||
let mut m = HashMap::new();
|
||||
m.insert("class".to_string(), "#>-".to_string());
|
||||
m.insert("cargo".to_string(), "#> ".to_string());
|
||||
m.insert("rough".to_string(), "█ ".to_string());
|
||||
m.insert("fine".to_string(), "█▉▊▋▌▍▎▏ ".to_string());
|
||||
m.insert("vert".to_string(), "█▇▆▅▄▃▂▁ ".to_string());
|
||||
m.insert("fade".to_string(), "█▓▒░ ".to_string());
|
||||
m.insert("block".to_string(), "█▛▌▖ ".to_string());
|
||||
m.insert("curse".to_string(), "▓▙▚▐▔ ▛▘▖▄▟▞▂█".to_string());
|
||||
m.insert("load".to_string(), " ⱠØ₳Đł₦₲ ".to_string());
|
||||
m.insert("cool".to_string(), "▰▱".to_string());
|
||||
m.insert("neo".to_string(), "▰═".to_string());
|
||||
m
|
||||
});
|
||||
// Spinners
|
||||
// ▁ ▂ ▃ ▄ ▅ ▆ ▇ █ ▇ ▆ ▅ ▄ ▃ ▁
|
||||
// ▉▊▋▌▍▎▏▎▍▌▋▊▉
|
||||
// ▖ ▘ ▝ ▗
|
||||
// ┤ ┘ ┴ └ ├ ┌ ┬ ┐
|
||||
// ◢ ◣ ◤ ◥
|
||||
// ◡◡ ⊙⊙ ◠◠
|
||||
// ⣾⣽⣻⢿⡿⣟⣯⣷ ⠁⠂⠄⡀⢀⠠⠐⠈
|
||||
// .tick_strings(&[
|
||||
// "▹▹▹▹▹",
|
||||
// "▸▹▹▹▹",
|
||||
// "▹▸▹▹▹",
|
||||
// "▹▹▸▹▹",
|
||||
// "▹▹▹▸▹",
|
||||
// "▹▹▹▹▸",
|
||||
// "▪▪▪▪▪",
|
||||
// ]),
|
||||
//
|
||||
|
||||
/// List of all alternative targets
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum MakeTargets {
|
||||
/// Make all targets
|
||||
All,
|
||||
/// Make a list of all optionals
|
||||
List,
|
||||
/// Make glossaries
|
||||
Glossaries,
|
||||
/// Make the working directory clean
|
||||
Clean,
|
||||
}
|
||||
|
||||
impl From<&str> for MakeTargets {
|
||||
fn from(value: &str) -> Self {
|
||||
if let Some(target) = STR_TO_BUILD_TARGET.get(&value.to_lowercase()).cloned() {
|
||||
target
|
||||
} else {
|
||||
panic!(
|
||||
"Invalid build target {}. The build target available are [{:?}]",
|
||||
value, HELP_BUILD_TARGET_LIST
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use crate::make::{
|
||||
HELP_BLOCK_SELECTION, HELP_BUILD_TARGET_LIST, HELP_VERBOSITY_LEVEL, VerboseLevel,
|
||||
};
|
||||
|
||||
use super::MakeTargets;
|
||||
|
||||
#[test]
|
||||
fn test_help_str() {
|
||||
insta::assert_yaml_snapshot!(HELP_BLOCK_SELECTION.to_string());
|
||||
insta::assert_yaml_snapshot!(HELP_VERBOSITY_LEVEL.to_string());
|
||||
insta::assert_yaml_snapshot!(HELP_BUILD_TARGET_LIST.to_string());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_block_prog_and_verbosity() {
|
||||
assert_eq!(VerboseLevel::from("misc"), VerboseLevel::Misc);
|
||||
assert_eq!(VerboseLevel::from("box"), VerboseLevel::Box);
|
||||
assert_eq!(VerboseLevel::from("context"), VerboseLevel::Context);
|
||||
assert_eq!(VerboseLevel::from("info"), VerboseLevel::Info);
|
||||
assert_eq!(VerboseLevel::from("warning"), VerboseLevel::Warning);
|
||||
assert_eq!(VerboseLevel::from("error"), VerboseLevel::Error);
|
||||
assert_eq!(VerboseLevel::from("critical"), VerboseLevel::Critical);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic]
|
||||
fn test_bad_verbose() {
|
||||
let _ = VerboseLevel::from("bad_level");
|
||||
}
|
||||
#[test]
|
||||
#[should_panic]
|
||||
fn test_bad_make() {
|
||||
let _ = MakeTargets::from("bad_make");
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
---
|
||||
source: config/src/graph.rs
|
||||
expression: HELP_STR_TO_GRAPH.to_string()
|
||||
---
|
||||
"init, generate, gen, clean, remove"
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
---
|
||||
source: config/src/make.rs
|
||||
expression: HELP_VERBOSITY_LEVEL.to_string()
|
||||
---
|
||||
"box, context, critical, error, info, misc, warning"
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
---
|
||||
source: config/src/make.rs
|
||||
expression: HELP_BUILD_TARGET_LIST.to_string()
|
||||
---
|
||||
"clean, list, glossaries, all"
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
---
|
||||
source: config/src/make.rs
|
||||
expression: HELP_BLOCK_SELECTION.to_string()
|
||||
---
|
||||
"block, cargo, class, cool, curse, fade, fine, load, neo, rough, vert"
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
---
|
||||
source: config/src/tablegen.rs
|
||||
expression: HELP_STR_TO_TARGET_TABLES.to_string()
|
||||
---
|
||||
"all, classes, craft, files"
|
||||
|
|
@ -0,0 +1,123 @@
|
|||
// Workspace: config
|
||||
// File: config/src/tablegen.rs
|
||||
//! Table generation structs
|
||||
|
||||
use clap::Args;
|
||||
use phf::phf_map;
|
||||
use serde::Deserialize;
|
||||
use std::sync::LazyLock;
|
||||
|
||||
/// An enumeration representing different target types.
|
||||
#[derive(Debug, Clone)]
|
||||
#[cfg_attr(test, derive(serde::Serialize))]
|
||||
pub enum TableGenerationTarget {
|
||||
/// Processes all classes
|
||||
Classes,
|
||||
/// Processes all the craft tables
|
||||
Craft,
|
||||
/// Processes only the given files
|
||||
Files,
|
||||
/// Processes all the known targets
|
||||
All,
|
||||
}
|
||||
|
||||
impl From<&str> for TableGenerationTarget {
|
||||
fn from(value: &str) -> Self {
|
||||
if let Some(target) = STR_TO_TARGET.get(value).cloned() {
|
||||
target
|
||||
} else {
|
||||
panic!(
|
||||
"Only the following target can be used: {}",
|
||||
*HELP_STR_TO_TARGET_TABLES
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A mapping of string representations to target types.
|
||||
static STR_TO_TARGET: phf::Map<&'static str, TableGenerationTarget> = phf_map! {
|
||||
"classes" => TableGenerationTarget::Classes,
|
||||
"craft" => TableGenerationTarget::Craft,
|
||||
"files" => TableGenerationTarget::Files,
|
||||
"all" => TableGenerationTarget::All,
|
||||
};
|
||||
|
||||
/// A help of all the table targets to be built
|
||||
static HELP_STR_TO_TARGET_TABLES: LazyLock<String> = LazyLock::new(|| {
|
||||
let mut targets = STR_TO_TARGET
|
||||
.keys()
|
||||
.map(|v| v.to_string())
|
||||
.collect::<Vec<String>>();
|
||||
targets.sort();
|
||||
targets.join(", ").to_string()
|
||||
});
|
||||
/// Configuration options for processing TSV files and generating LaTeX tables.
|
||||
#[derive(Debug, Args)]
|
||||
pub struct TableArgs {
|
||||
/// Wether to export all files (if used), or output everything to stdout
|
||||
#[arg(short)]
|
||||
pub export: bool,
|
||||
|
||||
/// The kind of tables to operate on: classes, craft or files followed by a list of files
|
||||
// #[arg(help = format!("The kind of tables to operate on : {}", "TODO: FIX"))]
|
||||
#[arg(help = format!("The kind of tables to operate on : {}", *HELP_STR_TO_TARGET_TABLES))]
|
||||
pub kind: TableGenerationTarget,
|
||||
/// A vector of strings representing the names of TSV files to process.
|
||||
pub filenames: Vec<String>,
|
||||
}
|
||||
|
||||
// This config is can contain unconstructed code for compatibility purposes
|
||||
#[allow(dead_code)]
|
||||
#[derive(Deserialize)]
|
||||
/// The Craft configs
|
||||
pub struct Craft {
|
||||
/// The food header string formatter
|
||||
pub header_food: String,
|
||||
/// The alchemy header string formatter
|
||||
pub header_alchemy: String,
|
||||
/// The forge header string formatter
|
||||
pub header_forge: String,
|
||||
/// The mtrap header string formatter
|
||||
pub header_mtrap: String,
|
||||
/// The weapons header string formatter
|
||||
pub header_weapons: String,
|
||||
/// The armors header string formatter
|
||||
pub header_armors: String,
|
||||
/// The gadgets header string formatter
|
||||
pub header_gadgets: String,
|
||||
/// The potions header string formatter
|
||||
pub header_potions: String,
|
||||
/// The traps header string formatter
|
||||
pub header_traps: String,
|
||||
/// The table end string formatter
|
||||
pub end: String,
|
||||
/// The long table end string formatter
|
||||
pub end_long: String,
|
||||
/// The long sideways table end string formatter
|
||||
pub end_long_side: String,
|
||||
/// The no_headers table end string formatter
|
||||
pub end_empty: String,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use crate::tablegen::{HELP_STR_TO_TARGET_TABLES, TableGenerationTarget};
|
||||
#[test]
|
||||
#[should_panic]
|
||||
fn test_bad_targets() {
|
||||
let _ = TableGenerationTarget::from("bob");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_targets() {
|
||||
let _ = TableGenerationTarget::from("all");
|
||||
let _ = TableGenerationTarget::from("files");
|
||||
let _ = TableGenerationTarget::from("craft");
|
||||
let _ = TableGenerationTarget::from("classes");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_str_gen() {
|
||||
insta::assert_yaml_snapshot!(HELP_STR_TO_TARGET_TABLES.to_string());
|
||||
}
|
||||
}
|
||||
|
|
@ -1,9 +0,0 @@
|
|||
[package]
|
||||
name = "cli_parser"
|
||||
version.workspace = true
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
config = {workspace = true}
|
||||
clap = {workspace = true}
|
||||
serde = {workspace = true}
|
||||
|
|
@ -1,11 +0,0 @@
|
|||
[package]
|
||||
name = "config"
|
||||
version.workspace = true
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
clap = {workspace = true}
|
||||
serde = {workspace = true}
|
||||
phf = {workspace = true}
|
||||
indexmap = {workspace = true}
|
||||
anyhow = {workspace = true}
|
||||
|
|
@ -1,76 +0,0 @@
|
|||
// Workspace: config
|
||||
// File: config/src/graph.rs
|
||||
//! The inner config for the analysis module
|
||||
//!
|
||||
|
||||
use clap::{Parser, ValueEnum};
|
||||
|
||||
#[derive(Parser, Debug)]
|
||||
/// Basic analisys CLI
|
||||
pub struct AnalysisConfig {
|
||||
#[arg(help = format!("The target to perform an analysis on [{:?}]", AnalysisTarget::value_variants()))]
|
||||
/// The analysis target
|
||||
pub target: AnalysisTarget,
|
||||
|
||||
/// The path to save to.
|
||||
pub path: Option<String>,
|
||||
/// Wether to generate shapes
|
||||
#[arg(short('S'), long, default_value_t)]
|
||||
pub no_shapes: bool,
|
||||
/// Wether to generate materials
|
||||
#[arg(short, long)]
|
||||
pub materials: Option<usize>,
|
||||
/// Wether to generate all natures
|
||||
#[arg(short('N'), long)]
|
||||
pub no_natures: bool,
|
||||
/// Wether to generate all finishing
|
||||
#[arg(short, long, default_value_t = false)]
|
||||
pub finishing: bool,
|
||||
#[arg(long, default_value_t = String::from("safe"))]
|
||||
/// What function to sort by
|
||||
pub sort: String,
|
||||
// An html export path -h or -o
|
||||
// A csv export path -c or --csv
|
||||
// A presort --sort
|
||||
// A prefilter with some filters ?
|
||||
// - weapons
|
||||
// - shields
|
||||
// - armors
|
||||
// - damage
|
||||
// Data manipulation ??
|
||||
// - decimate
|
||||
// - 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 {
|
||||
/// Analysis over weapons
|
||||
Weapon,
|
||||
/// Analysis over armors
|
||||
Armors,
|
||||
/// Analysis over shields
|
||||
Shields,
|
||||
}
|
||||
|
||||
#[derive(ValueEnum, Clone, Debug)]
|
||||
/// The type of generation to perform
|
||||
pub enum ExportTarget {
|
||||
/// Generate all
|
||||
All,
|
||||
}
|
||||
|
|
@ -1,57 +0,0 @@
|
|||
//! # `fast_table` Configuration
|
||||
//!
|
||||
//! This module defines the command‑line configuration used by the **fast‑tables**
|
||||
//! tool. The struct `FastTableConfig` is a thin wrapper around the `clap`
|
||||
//! `Args` derive macro, which automatically turns the struct into a CLI
|
||||
//! parser. All public fields are exposed to the user via command‑line flags
|
||||
//! (or environment variables) and are documented below.
|
||||
//!
|
||||
|
||||
use clap::{Args, ValueEnum};
|
||||
|
||||
/// Configuration for the `fast‑tables` command.
|
||||
///
|
||||
/// This struct is passed directly to `clap::Command::new` when creating the
|
||||
/// CLI. Each field corresponds to a CLI flag; the attribute annotations
|
||||
/// control how `clap` renders help text and parses values.
|
||||
///
|
||||
#[derive(Args, Debug, Clone)]
|
||||
pub struct FastTableConfig {
|
||||
/// Target table type to generate or operate on.
|
||||
#[arg()]
|
||||
pub target: TableTargetType,
|
||||
|
||||
/// Optional path to the destination directory for the generated tables.
|
||||
#[arg(short, long)]
|
||||
pub destination: Option<String>,
|
||||
|
||||
/// Optional path to an existing configuration file.
|
||||
/// If omitted, a new config will be created with default values.
|
||||
#[arg(short, long)]
|
||||
pub config: Option<String>,
|
||||
|
||||
/// Simple string filter applied to class names.
|
||||
/// Empty string matches all classes.
|
||||
#[arg(long)]
|
||||
pub filter: String,
|
||||
}
|
||||
|
||||
/// Enumerated set of table target types.
|
||||
///
|
||||
/// This enum implements `ValueEnum`, which gives it two important traits:
|
||||
/// * It can be used directly as a `clap` argument type.
|
||||
/// * It can be parsed from a string (`"classes"`, `"alchemy"`, etc.) in a
|
||||
/// case‑insensitive manner.
|
||||
#[derive(ValueEnum, Debug, Clone)]
|
||||
pub enum TableTargetType {
|
||||
/// Classes table
|
||||
Classes,
|
||||
/// Alchemy table
|
||||
Alchemy,
|
||||
/// Brewry table
|
||||
Brewry,
|
||||
/// All crafting tables
|
||||
AllCraft,
|
||||
/// All tables
|
||||
All,
|
||||
}
|
||||
|
|
@ -1,17 +0,0 @@
|
|||
// Workspace: config
|
||||
// File: config/src/formatter.rs
|
||||
//! The inner config for formatter module
|
||||
|
||||
use clap::Args;
|
||||
|
||||
#[derive(Args, Debug, Clone)]
|
||||
/// The configuration struct for the Formatter
|
||||
pub struct FormatterConfig {
|
||||
/// Export the config
|
||||
#[arg(short, long)]
|
||||
pub config: bool,
|
||||
|
||||
/// Take the arguments via stdin
|
||||
#[arg(long)]
|
||||
pub stdin: bool,
|
||||
}
|
||||
|
|
@ -1,237 +0,0 @@
|
|||
// Workspace: config
|
||||
// File: config/src/graph.rs
|
||||
//! The inner config for graph module
|
||||
//!
|
||||
use clap::{Args, ValueEnum};
|
||||
use phf::phf_map;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{ops::Add, sync::LazyLock};
|
||||
|
||||
#[derive(Args, Debug, Clone)]
|
||||
/// The configuration struct for the Graph
|
||||
pub struct GraphConfig {
|
||||
/// Special target
|
||||
pub target: GraphTargetType,
|
||||
|
||||
/// Alternative origin
|
||||
#[arg(short, long, default_value = "Images/Radar/radar.csv")]
|
||||
pub origin: String,
|
||||
|
||||
/// Alternative destination
|
||||
#[arg(short, long, default_value = "Images/Radar")]
|
||||
pub destination: String,
|
||||
|
||||
/// Alternative config to load (generate a new one with init)
|
||||
#[arg(short, long)]
|
||||
pub config: Option<String>,
|
||||
|
||||
/// Clean all the artefacts (including generated images)
|
||||
#[arg(short, long)]
|
||||
pub all: bool,
|
||||
}
|
||||
|
||||
/// Link from user str input to the action to perform
|
||||
static STR_TO_GRAPH_TARGET_TYPE: phf::Map<&'static str, GraphTargetType> = phf_map! {
|
||||
"load" => GraphTargetType::Load,
|
||||
"generate" => GraphTargetType::Generate,
|
||||
"gen" => GraphTargetType::Generate,
|
||||
"remove" => GraphTargetType::Remove,
|
||||
"clean" => GraphTargetType::Remove,
|
||||
"init" => GraphTargetType::Init,
|
||||
};
|
||||
|
||||
/// Help listing all the actions availables
|
||||
static HELP_STR_TO_GRAPH: LazyLock<String> = LazyLock::new(|| {
|
||||
let targets = STR_TO_GRAPH_TARGET_TYPE
|
||||
.keys()
|
||||
.map(|v| v.to_string())
|
||||
.collect::<Vec<String>>();
|
||||
targets.join(", ").to_string()
|
||||
});
|
||||
|
||||
#[derive(ValueEnum, Debug, Clone)]
|
||||
/// All target type
|
||||
pub enum GraphTargetType {
|
||||
/// Load graph data from the classes
|
||||
Load,
|
||||
/// Make all graphs
|
||||
Generate,
|
||||
/// Clean all graphs
|
||||
Remove,
|
||||
/// Initialize the connfig
|
||||
Init,
|
||||
}
|
||||
|
||||
impl From<&str> for GraphTargetType {
|
||||
fn from(value: &str) -> Self {
|
||||
if let Some(target) = STR_TO_GRAPH_TARGET_TYPE.get(&value.to_lowercase()).cloned() {
|
||||
target
|
||||
} else {
|
||||
panic!(
|
||||
"Invalid target {}. The target available are : [{}]",
|
||||
value, *HELP_STR_TO_GRAPH
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
/// The named categories to save on file
|
||||
#[derive(Default, Debug, Deserialize, Serialize)]
|
||||
pub struct FinalClassRadar {
|
||||
/// A name to identify the categories
|
||||
#[serde(rename = "Classe")]
|
||||
pub name: String,
|
||||
/// The values of the different radar categories
|
||||
/// The ability to survive.
|
||||
#[serde(rename = "Survivabilité")]
|
||||
pub survivability: f64,
|
||||
/// The ability to deal damage.
|
||||
#[serde(rename = "Dégats")]
|
||||
pub damage: f64,
|
||||
/// The ability to move.
|
||||
#[serde(rename = "Mobilité")]
|
||||
pub mobility: f64,
|
||||
/// The ability to inflict state alterations.
|
||||
#[serde(rename = "Altérations")]
|
||||
pub alterations: f64,
|
||||
/// The armor break of the class
|
||||
#[serde(rename = "Brise-Armure")]
|
||||
pub armorbreak: f64,
|
||||
/// The ability to provide support.
|
||||
#[serde(rename = "Support")]
|
||||
pub support: f64,
|
||||
/// The ability to inflict crowd control.
|
||||
#[serde(rename = "C.C")]
|
||||
pub cc: f64,
|
||||
/// The ability to improve quality of life.
|
||||
#[serde(rename = "QoL")]
|
||||
pub qol: f64,
|
||||
// / The class complexity
|
||||
}
|
||||
|
||||
/// All the categories to load from the tables
|
||||
#[derive(Default, Debug, Deserialize, Serialize)]
|
||||
pub struct LoadedClassRadar {
|
||||
/// The ability to survive.
|
||||
pub survivability: f64,
|
||||
/// The ability to deal damage.
|
||||
pub damage: f64,
|
||||
/// The ability to move.
|
||||
pub mobility: f64,
|
||||
/// The ability to inflict state alterations.
|
||||
pub alterations: f64,
|
||||
/// The ability to break armor.
|
||||
pub armorbreak: f64,
|
||||
/// The ability to provide support.
|
||||
pub support: f64,
|
||||
/// The ability to inflict crowd control.
|
||||
pub cc: f64,
|
||||
/// The ability to improve quality of life.
|
||||
pub qol: f64,
|
||||
}
|
||||
|
||||
/// All the categories to load from the tables
|
||||
#[derive(Deserialize, Clone, Debug)]
|
||||
pub struct RawRow {
|
||||
/// The name of a technique.
|
||||
pub technique: String,
|
||||
/// The level or rank of a technique
|
||||
pub niveau: String,
|
||||
/// The type of technique, such as Actif or Exclusif.
|
||||
pub technique_type: String,
|
||||
/// The blood cost for this technique.
|
||||
pub cout_blood: String,
|
||||
/// The gauge cost for this technique.
|
||||
pub cout_jauge: String,
|
||||
/// A brief description of the effect or outcome of using this technique.
|
||||
pub effet: String,
|
||||
/// A indicative column for notes
|
||||
pub indicative: String,
|
||||
/// The ability to provide support.
|
||||
pub support: String,
|
||||
/// The ability to deal damage.
|
||||
pub damage: String,
|
||||
/// The ability to survive.
|
||||
pub survivability: String,
|
||||
/// The ability to move.
|
||||
pub mobility: String,
|
||||
/// The ability to inflict crowd control.
|
||||
pub cc: String,
|
||||
/// The ability to inflict state alterations.
|
||||
pub alterations: String,
|
||||
/// The ability to improve quality of life.
|
||||
pub qol: String,
|
||||
/// The ability to break armor.
|
||||
pub armorbreak: String,
|
||||
}
|
||||
|
||||
impl From<RawRow> for LoadedClassRadar {
|
||||
fn from(value: RawRow) -> Self {
|
||||
Self {
|
||||
survivability: value.survivability.parse().unwrap_or(0.0),
|
||||
damage: value.damage.parse().unwrap_or(0.0),
|
||||
mobility: value.mobility.parse().unwrap_or(0.0),
|
||||
alterations: value.alterations.parse().unwrap_or(0.0),
|
||||
support: value.support.parse().unwrap_or(0.0),
|
||||
cc: value.cc.parse().unwrap_or(0.0),
|
||||
qol: value.qol.parse().unwrap_or(0.0),
|
||||
armorbreak: value.armorbreak.parse().unwrap_or(0.0),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Add for LoadedClassRadar {
|
||||
type Output = Self;
|
||||
|
||||
fn add(self, rhs: Self) -> Self::Output {
|
||||
Self {
|
||||
survivability: self.survivability + rhs.survivability,
|
||||
damage: self.damage + rhs.damage,
|
||||
mobility: self.mobility + rhs.mobility,
|
||||
alterations: self.alterations + rhs.alterations,
|
||||
support: self.support + rhs.support,
|
||||
cc: self.cc + rhs.cc,
|
||||
qol: self.qol + rhs.qol,
|
||||
armorbreak: self.armorbreak + rhs.armorbreak,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl FinalClassRadar {
|
||||
/// A very wastful (but simple) way to only add the max value
|
||||
pub fn find_max(self, rhs: &Self) -> Self {
|
||||
Self {
|
||||
survivability: self.survivability.max(rhs.survivability),
|
||||
damage: self.damage.max(rhs.damage),
|
||||
mobility: self.mobility.max(rhs.mobility),
|
||||
alterations: self.alterations.max(rhs.alterations),
|
||||
support: self.support.max(rhs.support),
|
||||
cc: self.cc.max(rhs.cc),
|
||||
qol: self.qol.max(rhs.qol),
|
||||
armorbreak: self.armorbreak.max(rhs.armorbreak),
|
||||
name: self.name,
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a class from a loaded categories
|
||||
pub fn from_radar_with_name(name: String, categorie: LoadedClassRadar) -> Self {
|
||||
Self {
|
||||
name,
|
||||
survivability: categorie.survivability,
|
||||
damage: categorie.damage,
|
||||
mobility: categorie.mobility,
|
||||
alterations: categorie.alterations,
|
||||
support: categorie.support,
|
||||
cc: categorie.cc,
|
||||
qol: categorie.qol,
|
||||
armorbreak: categorie.armorbreak,
|
||||
}
|
||||
}
|
||||
|
||||
/// A default value for accumulation
|
||||
pub fn default_for_acc() -> FinalClassRadar {
|
||||
Self {
|
||||
name: "Max".to_owned(),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,71 +0,0 @@
|
|||
// Workspace: config
|
||||
// File: config/src/make.rs
|
||||
//! Makepdf generation structs
|
||||
|
||||
use clap::ValueEnum;
|
||||
use std::{collections::HashMap, fmt::Debug, sync::LazyLock};
|
||||
|
||||
/// List all blocktype
|
||||
pub static HELP_BLOCK_SELECTION: LazyLock<String> = LazyLock::new(|| {
|
||||
let mut targets = BLOCK_PROGRESSION
|
||||
.keys()
|
||||
.map(|v| v.to_owned())
|
||||
.collect::<Vec<String>>();
|
||||
targets.sort();
|
||||
targets.join(", ").to_string()
|
||||
});
|
||||
|
||||
/// The verbosity level
|
||||
#[derive(ValueEnum, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub enum VerboseLevel {
|
||||
/// Shouldn't be printed no matter what
|
||||
None,
|
||||
/// Garbage
|
||||
Misc,
|
||||
/// Boxness, barely above Misc
|
||||
Box,
|
||||
/// Context info (Debug info)
|
||||
Context,
|
||||
/// Usefull info
|
||||
Info,
|
||||
/// Important warnings
|
||||
Warning,
|
||||
/// Errors encountered requiring user input
|
||||
Error,
|
||||
/// Uncatchable errors
|
||||
Critical,
|
||||
/// Interactive prompt context, only useful in interactive mode
|
||||
InteractiveContext,
|
||||
/// Literrally uncatchable things
|
||||
Uncatchable,
|
||||
}
|
||||
|
||||
/// All progress bar styles
|
||||
pub static BLOCK_PROGRESSION: LazyLock<HashMap<String, String>> = LazyLock::new(|| {
|
||||
let mut m = HashMap::new();
|
||||
m.insert("class".to_string(), "#>-".to_string());
|
||||
m.insert("cargo".to_string(), "#> ".to_string());
|
||||
m.insert("rough".to_string(), "█ ".to_string());
|
||||
m.insert("fine".to_string(), "█▉▊▋▌▍▎▏ ".to_string());
|
||||
m.insert("vert".to_string(), "█▇▆▅▄▃▂▁ ".to_string());
|
||||
m.insert("fade".to_string(), "█▓▒░ ".to_string());
|
||||
m.insert("block".to_string(), "█▛▌▖ ".to_string());
|
||||
m.insert("curse".to_string(), "▓▙▚▐▔ ▛▘▖▄▟▞▂█".to_string());
|
||||
m.insert("load".to_string(), " ⱠØ₳Đł₦₲ ".to_string());
|
||||
m.insert("cool".to_string(), "▰▱".to_string());
|
||||
m.insert("neo".to_string(), "▰═".to_string());
|
||||
m
|
||||
});
|
||||
|
||||
/// List of all alternative targets
|
||||
#[derive(ValueEnum, Debug, Clone)]
|
||||
pub enum MakeTargets {
|
||||
/// Make all targets
|
||||
All,
|
||||
/// Make a list of all optionals
|
||||
List,
|
||||
/// Make glossaries
|
||||
Glossaries,
|
||||
/// Make the working directory clean
|
||||
Clean,
|
||||
}
|
||||
|
|
@ -1,178 +0,0 @@
|
|||
// Workspace: config
|
||||
// File: config/src/monsters.rs
|
||||
//! The inner config for monster module
|
||||
//!
|
||||
#![allow(dead_code)]
|
||||
|
||||
use anyhow::Result;
|
||||
use clap::Args;
|
||||
use clap::Parser;
|
||||
use indexmap::IndexMap;
|
||||
use serde::{Deserialize, Deserializer};
|
||||
|
||||
/// The top‑level configuration – only a subcommand is needed here.
|
||||
#[derive(Parser, Debug)]
|
||||
#[command(
|
||||
name = "monster",
|
||||
author,
|
||||
version,
|
||||
about = "Export or balance monster data"
|
||||
)]
|
||||
pub struct MonsterConfig {
|
||||
/// Which action to perform
|
||||
#[command(subcommand)]
|
||||
pub target: MonsterTarget,
|
||||
}
|
||||
|
||||
/// The two actions the binary can take.
|
||||
#[derive(Debug, Parser)]
|
||||
pub enum MonsterTarget {
|
||||
/// Generate a tex file(s) with monster lists
|
||||
Export(ExportArgs),
|
||||
|
||||
/// Produce balancing diagnostics
|
||||
Balance(BalanceArgs),
|
||||
}
|
||||
|
||||
/// Common arguments
|
||||
#[derive(Debug, Args)]
|
||||
pub struct CommonDb {
|
||||
#[arg(
|
||||
short = 'd',
|
||||
long = "database",
|
||||
default_value = "./ravenous_databases/monsters.db",
|
||||
help = "Path to the SQLite monster database"
|
||||
)]
|
||||
/// Database to load from – shared by *both* commands.
|
||||
pub database: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Args)]
|
||||
/// Filter data
|
||||
pub struct CommonFilter {
|
||||
#[arg(
|
||||
long = "filter",
|
||||
default_value = "show_to_master = 1",
|
||||
help = "SQL‑like filter applied when querying monsters"
|
||||
)]
|
||||
/// Optional data filter – also shared by both commands.
|
||||
pub filter: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Args)]
|
||||
/// Export only arguments
|
||||
pub struct ExportArgs {
|
||||
/// Flatten the shared database flag into this command.
|
||||
#[clap(flatten)]
|
||||
pub db: CommonDb,
|
||||
|
||||
/// Flatten the shared filter flag into this command.
|
||||
#[clap(flatten)]
|
||||
pub filter: CommonFilter,
|
||||
|
||||
/// Path where the tex files will be written
|
||||
#[arg(long, default_value = "./Bestiaire/")]
|
||||
pub destination: String,
|
||||
|
||||
/// Export *all* monsters (full_bestiaire.tex)
|
||||
#[arg(long, default_value_t = false)]
|
||||
pub master: bool,
|
||||
|
||||
/// Export only player‑usable monsters
|
||||
#[arg(long, default_value_t = false)]
|
||||
pub player: bool,
|
||||
|
||||
/// Export both `master` and `player`
|
||||
#[arg(long, default_value_t = false)]
|
||||
pub all: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Args)]
|
||||
/// Balance only arguments
|
||||
pub struct BalanceArgs {
|
||||
/// Flatten the shared database flag into this command.
|
||||
#[clap(flatten)]
|
||||
pub db: CommonDb,
|
||||
|
||||
/// Flatten the shared filter flag into this command.
|
||||
#[clap(flatten)]
|
||||
pub filter: CommonFilter,
|
||||
|
||||
/// Show the raw balancing numbers
|
||||
#[arg(long, default_value_t = false)]
|
||||
pub show_extra: bool,
|
||||
|
||||
/// Show even the balanced numbers
|
||||
#[arg(long, default_value_t = false)]
|
||||
pub show_balanced: bool,
|
||||
|
||||
/// Show detailed profiles for each monster
|
||||
#[arg(long, default_value_t = false)]
|
||||
pub show_profiles: bool,
|
||||
}
|
||||
/// Configuration data for generating a monster sheet.
|
||||
///
|
||||
/// The values are plain LaTeX fragments stored in the `[monster]` section of a `.toml`
|
||||
#[allow(dead_code)]
|
||||
#[derive(Deserialize)]
|
||||
pub struct MonsterMarkup {
|
||||
/// Color map
|
||||
#[serde(deserialize_with = "parse_monster_color")]
|
||||
pub color_table: MonsterColor,
|
||||
|
||||
/// Default color
|
||||
pub default_color: String,
|
||||
|
||||
/// Common part of monsters
|
||||
pub common_part: String,
|
||||
|
||||
/// Master part of monsters
|
||||
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
|
||||
pub inner: IndexMap<String, String>,
|
||||
}
|
||||
|
||||
impl std::ops::Deref for MonsterColor {
|
||||
type Target = IndexMap<String, String>;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.inner
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse the monster colors from a toml
|
||||
fn parse_monster_color<'de, D>(deserializer: D) -> Result<MonsterColor, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
let color = String::deserialize(deserializer)?;
|
||||
Ok(MonsterColor {
|
||||
inner: color
|
||||
.lines()
|
||||
.filter_map(|line| {
|
||||
let line = line.trim();
|
||||
if line.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
// Split at the first ':' only.
|
||||
let mut parts = line.splitn(2, ':');
|
||||
let key = parts.next()?.trim().to_string();
|
||||
let value = parts.next().map(|v| v.trim()).ok_or(()).ok()?;
|
||||
|
||||
Some((key, value.to_owned()))
|
||||
})
|
||||
.collect(),
|
||||
})
|
||||
}
|
||||
|
|
@ -1,65 +0,0 @@
|
|||
// Workspace: config
|
||||
// File: config/src/tablegen.rs
|
||||
//! Table generation structs
|
||||
|
||||
use clap::{Args, ValueEnum};
|
||||
use serde::Deserialize;
|
||||
|
||||
/// An enumeration representing different target types.
|
||||
#[derive(ValueEnum, Debug, Clone)]
|
||||
pub enum TableGenerationTarget {
|
||||
/// Processes all classes
|
||||
Classes,
|
||||
/// Processes all the craft tables
|
||||
Craft,
|
||||
/// Processes only the given files
|
||||
Files,
|
||||
/// Processes all the known targets
|
||||
All,
|
||||
}
|
||||
|
||||
/// Configuration options for processing TSV files and generating LaTeX tables.
|
||||
#[derive(Debug, Args)]
|
||||
pub struct TableArgs {
|
||||
/// Wether to export all files (if used), or output everything to stdout
|
||||
#[arg(short)]
|
||||
pub export: bool,
|
||||
|
||||
/// The kind of tables to operate on: classes, craft or files followed by a list of files
|
||||
pub kind: TableGenerationTarget,
|
||||
/// A vector of strings representing the names of TSV files to process.
|
||||
pub filenames: Vec<String>,
|
||||
}
|
||||
|
||||
// This config can contain unconstructed code for compatibility purposes
|
||||
#[allow(dead_code)]
|
||||
#[derive(Deserialize)]
|
||||
/// The Craft configs
|
||||
pub struct Craft {
|
||||
/// The food header string formatter
|
||||
pub header_food: String,
|
||||
/// The alchemy header string formatter
|
||||
pub header_alchemy: String,
|
||||
/// The forge header string formatter
|
||||
pub header_forge: String,
|
||||
/// The mtrap header string formatter
|
||||
pub header_mtrap: String,
|
||||
/// The weapons header string formatter
|
||||
pub header_weapons: String,
|
||||
/// The armors header string formatter
|
||||
pub header_armors: String,
|
||||
/// The gadgets header string formatter
|
||||
pub header_gadgets: String,
|
||||
/// The potions header string formatter
|
||||
pub header_potions: String,
|
||||
/// The traps header string formatter
|
||||
pub header_traps: String,
|
||||
/// The table end string formatter
|
||||
pub end: String,
|
||||
/// The long table end string formatter
|
||||
pub end_long: String,
|
||||
/// The long sideways table end string formatter
|
||||
pub end_long_side: String,
|
||||
/// The no_headers table end string formatter
|
||||
pub end_empty: String,
|
||||
}
|
||||
|
|
@ -1,10 +0,0 @@
|
|||
[package]
|
||||
name = "fast_class"
|
||||
version.workspace = true
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
config = {workspace = true}
|
||||
cli_parser = {workspace = true}
|
||||
anyhow = {workspace = true}
|
||||
facet = "0.46.5"
|
||||
|
|
@ -1,139 +0,0 @@
|
|||
//! # Class & Tool Utility
|
||||
//!
|
||||
//! This module defines the core data structures used for representing classes in the
|
||||
//! game's balancing engine. Each class is a collection of metrics and a list of
|
||||
//! skill tiers. The structures are intentionally lightweight and designed to be
|
||||
//! serialisable with the `Facet` derive macro (used for JSON/YAML/CBOR export).
|
||||
//!
|
||||
//! The following concepts are modeled:
|
||||
//!
|
||||
//! * **`RavClass`** - The top-level representation of a playable class.
|
||||
//! * **`Metrics`** - A set of performance indicators that can be used for
|
||||
//! balancing decisions.
|
||||
//! * **`SkillTier`** - A grouping of skills that are unlocked at a given level.
|
||||
//! * **`Skill`** - An individual skill with its own cost, type, and effect
|
||||
//! description.
|
||||
//! * **`Cost`** - The resources required to cast a skill. The enum uses
|
||||
//! `repr(C)` for ABI-compatibility with C-based tools.
|
||||
//! * **`TType`** - A canonical representation of a skill's type (e.g. passive,
|
||||
//! active, crowd-control). This enum is defined for readability but the
|
||||
//! current `Skill::t_type` field uses raw `u8` values - see the note in
|
||||
//! `Skill` for guidance on converting between the two.
|
||||
//!
|
||||
//! The module is free of external dependencies except for `facet`, which provides
|
||||
//! the procedural macro used for deriving serialisation support.
|
||||
|
||||
use anyhow::Result;
|
||||
use cli_parser::Config;
|
||||
use config::fast_tables::FastTableConfig;
|
||||
use facet::Facet;
|
||||
|
||||
/// Represents a playable class in the game.
|
||||
///
|
||||
/// A `RavClass` contains the public metadata of a class (name, image, description),
|
||||
/// a set of *metrics* that quantify its strengths and weaknesses, and a list of
|
||||
/// `SkillTier`s that hold the actual abilities.
|
||||
///
|
||||
/// The metrics are interpreted as scores between `0.0` and `5.0`. They are used
|
||||
/// by the balancing engine to calculate power-level, but the struct itself does
|
||||
/// not enforce this range; callers must validate it if required.
|
||||
#[derive(Facet, Debug, Clone, Default)]
|
||||
pub struct RavClass {
|
||||
/// Human-readable name of the class.
|
||||
pub name: String,
|
||||
/// Path or URL to the class icon.
|
||||
pub image: String,
|
||||
/// Short flavor description.
|
||||
pub description: String,
|
||||
/// Quantitative metrics used for balancing.
|
||||
pub radar: Metrics,
|
||||
/// Ordered list of skill tiers. Typically one tier per level.
|
||||
pub techniques: Vec<SkillTier>,
|
||||
}
|
||||
|
||||
/// Metrics that quantify a class's capabilities.
|
||||
///
|
||||
/// All fields are `f32` values that usually lie in the range `[0.0, 1.0]`. The
|
||||
/// semantics of each metric are intentionally simple: higher values mean the
|
||||
/// class is better at that aspect. The struct derives `Default` via `Facet`,
|
||||
/// which sets every metric to `0.0`.
|
||||
#[derive(Facet, Debug, Clone, Default)]
|
||||
pub struct Metrics {
|
||||
pub survivability: f32,
|
||||
pub damage: f32,
|
||||
pub mobility: f32,
|
||||
pub alterations: f32,
|
||||
pub support: f32,
|
||||
pub crowd_control: f32,
|
||||
pub quality_of_live: f32,
|
||||
}
|
||||
|
||||
/// A grouping of skills unlocked at a particular level.
|
||||
///
|
||||
/// Each `SkillTier` contains a vector of `Skill`. The ordering of tiers matters
|
||||
/// for progression; callers should keep the slice sorted by the level that the
|
||||
/// tier unlocks.
|
||||
#[derive(Facet, Debug, Clone, Default)]
|
||||
pub struct SkillTier {
|
||||
/// Skills available at the tier's level.
|
||||
pub skills: Vec<Skill>,
|
||||
}
|
||||
|
||||
/// A single skill that a class can use.
|
||||
///
|
||||
/// The struct is intentionally flexible: it stores the skill name, level,
|
||||
/// type(s), cost(s), and an effect description. Some fields are stored as
|
||||
/// primitive types to keep the data compact, but helper functions can
|
||||
/// translate between those primitives and the more descriptive enums.
|
||||
#[derive(Facet, Debug, Clone, Default)]
|
||||
pub struct Skill {
|
||||
/// The display name of the skill.
|
||||
pub name: String,
|
||||
/// The skill level (e.g. 1-10).
|
||||
pub level: usize,
|
||||
/// Raw type identifiers.
|
||||
pub t_type: Vec<TType>,
|
||||
/// List of costs required to activate the skill.
|
||||
pub cost: Vec<Cost>,
|
||||
/// Human-readable effect description.
|
||||
pub effect: String,
|
||||
}
|
||||
|
||||
/// The resource cost required to cast a skill.
|
||||
#[derive(Facet, Debug, Clone, PartialEq, Eq)]
|
||||
#[repr(C)]
|
||||
pub enum Cost {
|
||||
Energy(u8),
|
||||
Blood(u8),
|
||||
}
|
||||
|
||||
/// Canonical representation of a skill's type.
|
||||
#[derive(Facet, Debug, Clone, PartialEq, Eq)]
|
||||
#[repr(C)]
|
||||
pub enum TType {
|
||||
Passive,
|
||||
Active,
|
||||
Exclusive,
|
||||
CC,
|
||||
Grab,
|
||||
Unique,
|
||||
}
|
||||
|
||||
pub trait Exportable {
|
||||
fn to_tex(&self) -> String;
|
||||
}
|
||||
|
||||
pub trait Graphable {
|
||||
fn to_graph(&self) -> String;
|
||||
}
|
||||
|
||||
pub fn make_better_gen(args: &FastTableConfig, config: &Config) -> Result<()> {
|
||||
let _ = args;
|
||||
let _ = config;
|
||||
todo!()
|
||||
}
|
||||
// Subcommands:
|
||||
// dashboard [classes, alchemy, cooking, forge] --filter name=Archer
|
||||
// export [classes, ] --filter name=Archer
|
||||
// graph [classes, alch] --filter
|
||||
//
|
||||
|
|
@ -1,12 +0,0 @@
|
|||
[package]
|
||||
name = "formatter"
|
||||
version.workspace = true
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
config = {workspace = true}
|
||||
cli_parser = {workspace = true}
|
||||
regex = {workspace = true}
|
||||
serde = {workspace = true}
|
||||
toml = {workspace = true}
|
||||
anyhow = {workspace = true}
|
||||
|
|
@ -1,99 +0,0 @@
|
|||
//! A simple formatter that reads patterns from a TOML file,
|
||||
//! applies them to stdin, and writes the formatted text to stdout.
|
||||
use anyhow::{Context, Result};
|
||||
use cli_parser::Config;
|
||||
use config::formatter::FormatterConfig;
|
||||
use regex::Regex;
|
||||
use serde::Deserialize;
|
||||
use std::fs;
|
||||
use std::io::{self, Read};
|
||||
|
||||
/// The base config for the project
|
||||
const SAMPLE_CONFIG: &str = r#"# Base config, loaded from .fmtconfig.tml
|
||||
[[patterns]]
|
||||
regex = "\\p{Pd}"
|
||||
replacement = "-"
|
||||
|
||||
[[patterns]]
|
||||
regex = "[\u2212]"
|
||||
replacement = "-"
|
||||
|
||||
[[patterns]]
|
||||
regex = "[\u2018\u2019\u201A\u201B\u02BC\u02BB\u00B4\uFF40\uFF07]"
|
||||
replacement = "'"
|
||||
|
||||
[[patterns]]
|
||||
regex = "[\\u00AD\\u200B\\u200C\\u200D\\uFEFF\\u2060-\\u2064\\uFE00-\\uFE0F]"
|
||||
replacement = ""
|
||||
|
||||
[[patterns]]
|
||||
regex = "[\\u202F]"
|
||||
replacement = " "
|
||||
"#;
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
/// A simple regex replacement config
|
||||
struct RegexConfig {
|
||||
/// The list of pattterns of replacement
|
||||
patterns: Vec<Pattern>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
/// The inner structure for a regex replacement pattern
|
||||
struct Pattern {
|
||||
/// A regex matching a formatting error
|
||||
regex: String,
|
||||
/// The replacement string
|
||||
replacement: String,
|
||||
}
|
||||
|
||||
/// Format a file according to the formatting guidelines
|
||||
pub fn format_file(args: &FormatterConfig, _config: &Config) -> Result<()> {
|
||||
// If --config was requested, print the sample config and exit.
|
||||
if args.config {
|
||||
println!("{}", SAMPLE_CONFIG);
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// // ------------------------------------------------------------------
|
||||
// // 1. Read and parse the .fmtconfig.toml file.
|
||||
// // ------------------------------------------------------------------
|
||||
|
||||
let toml_text = fs::read_to_string(".fmtconfig.toml")
|
||||
.context("Failed to read .fmtconfig.toml")
|
||||
.unwrap_or(SAMPLE_CONFIG.to_string());
|
||||
|
||||
let config: RegexConfig =
|
||||
toml::from_str(&toml_text).context("Failed to parse .fmtconfig.toml")?;
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// 2. Read the entire stdin into a string.
|
||||
// ------------------------------------------------------------------
|
||||
let mut input = String::new();
|
||||
if args.stdin {
|
||||
io::stdin()
|
||||
.read_to_string(&mut input)
|
||||
.context("Failed to read stdin")?;
|
||||
} else {
|
||||
unimplemented!("Use --stdin")
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// 3. Apply the patterns sequentially.
|
||||
// ------------------------------------------------------------------
|
||||
let mut output = input;
|
||||
for pat in &config.patterns {
|
||||
// Compile the regex lazily; panic on bad patterns in this demo.
|
||||
let re = Regex::new(&pat.regex)?;
|
||||
output = re
|
||||
.replace_all(&output, pat.replacement.as_str())
|
||||
.into_owned();
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// 4. Write the result to stdout.
|
||||
// ------------------------------------------------------------------
|
||||
print!("{}", output);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
|
@ -1,8 +0,0 @@
|
|||
//! This workspace_crate is a Rust library designed to Format latex documents on save.
|
||||
|
||||
#![warn(missing_docs, clippy::missing_docs_in_private_items)]
|
||||
// Internal modules
|
||||
mod formating;
|
||||
//
|
||||
// Re Export
|
||||
pub use formating::format_file;
|
||||
|
|
@ -1,15 +0,0 @@
|
|||
[package]
|
||||
name = "graphs"
|
||||
version.workspace = true
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
config = {workspace = true}
|
||||
cli_parser = {workspace = true}
|
||||
anyhow = {workspace = true}
|
||||
charts-rs = { version = "0.7", features = ["image-encoder"] }
|
||||
serde = {workspace = true}
|
||||
csv = {workspace = true}
|
||||
ron = {workspace = true}
|
||||
glob = {workspace = true}
|
||||
phf = {workspace = true}
|
||||
|
|
@ -1,19 +0,0 @@
|
|||
[package]
|
||||
name = "make"
|
||||
version.workspace = true
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
config = {workspace = true}
|
||||
cli_parser = {workspace = true}
|
||||
anyhow = {workspace = true}
|
||||
regex = {workspace = true}
|
||||
serde = {workspace = true}
|
||||
toml = {workspace = true}
|
||||
tokio = {workspace = true}
|
||||
dynfmt = {workspace = true}
|
||||
indexmap = {workspace = true}
|
||||
|
||||
indicatif = { version = "0.18.6", features = ["rayon"] }
|
||||
logos = "0.16.1"
|
||||
console = "0.16.4"
|
||||
|
|
@ -1,26 +0,0 @@
|
|||
[package]
|
||||
name = "monsters"
|
||||
version.workspace = true
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
config = {workspace = true}
|
||||
cli_parser = {workspace = true}
|
||||
more_fields = {workspace = true}
|
||||
anyhow = {workspace = true}
|
||||
indexmap = {workspace = true}
|
||||
serde = {workspace = true}
|
||||
rusqlite = {workspace = true}
|
||||
serde_rusqlite = {workspace = true}
|
||||
serde_json = {workspace = true}
|
||||
handlebars = {workspace = true}
|
||||
strum = {workspace = true}
|
||||
probability = {workspace = true}
|
||||
comfy-table = "7.2.2"
|
||||
colored = "3.1.1"
|
||||
# derive_more = "2.1.1"
|
||||
|
||||
[dev-dependencies]
|
||||
regex = {workspace = true}
|
||||
pretty_assertions = {workspace = true}
|
||||
clap = {workspace = true}
|
||||
|
|
@ -1,51 +0,0 @@
|
|||
//! # Monsters Module
|
||||
//!
|
||||
//! The `monsters` crate orchestrates the processing of *ravenous* monster data.
|
||||
//!
|
||||
//! It can:
|
||||
//! * **Parse** raw monster definitions into ergonomic Rust structs.
|
||||
//! * Perform **balancing** calculations to keep encounters fair.
|
||||
//! * **Show** concise, human‑readable summaries in the terminal.
|
||||
//! * **Export** processed data as LaTeX/TeX for printing or further editing.
|
||||
//!
|
||||
//! All functionality is exposed through a single entry point:
|
||||
//! [`monsters_dispatch`]. The dispatcher interprets command‑line arguments
|
||||
//! (`MonsterConfig`) and delegates to the appropriate sub‑routine (clean, export or show).
|
||||
//!
|
||||
|
||||
use crate::{monster_analysis::show_balancing_data, monster_export::generate_monsters_tex};
|
||||
|
||||
use config::monsters::MonsterTarget;
|
||||
|
||||
use anyhow::Context;
|
||||
mod monster_analysis;
|
||||
mod monster_database;
|
||||
mod monster_export;
|
||||
mod monster_render;
|
||||
pub mod monster_structs;
|
||||
|
||||
use anyhow::Result;
|
||||
use cli_parser::Config;
|
||||
use config::monsters::MonsterConfig;
|
||||
use rusqlite::Connection;
|
||||
|
||||
/// Dispatches the chosen monster action.
|
||||
pub fn monsters_dispatch(args: &MonsterConfig, config: &Config) -> Result<()> {
|
||||
// use config::monsters::MonsterTarget;
|
||||
|
||||
match args.target {
|
||||
// MonsterTarget::Clean => unimplemented!("implement cleaning logic"),
|
||||
MonsterTarget::Export(ref args) => {
|
||||
let connection = Connection::open(&args.db.database)
|
||||
.context(format!("Opening database {}", args.db.database))?;
|
||||
generate_monsters_tex(args, config, connection)?
|
||||
}
|
||||
// MonsterTarget::Show => unimplemented!("implement show logic"),
|
||||
MonsterTarget::Balance(ref args) => {
|
||||
let connection = Connection::open(&args.db.database)
|
||||
.context(format!("Opening database {}", args.db.database))?;
|
||||
show_balancing_data(args, config, connection)?
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
|
@ -1,65 +0,0 @@
|
|||
//! Monster export module
|
||||
#![allow(dead_code)]
|
||||
|
||||
use comfy_table::modifiers;
|
||||
use config::monsters::BalanceArgs;
|
||||
use indexmap::IndexMap;
|
||||
|
||||
use crate::{
|
||||
Config, Connection,
|
||||
monster_analysis::monster_analysis_structs::DefenseMode,
|
||||
monster_database::{fetch_all_creature_data, fetch_all_player_data},
|
||||
monster_render::ToCell,
|
||||
monster_structs::{PlayerBalancing, ProfileStance},
|
||||
};
|
||||
pub mod attack_analysis;
|
||||
pub mod defense_analysis;
|
||||
pub mod helpers;
|
||||
pub mod monster_analysis_structs;
|
||||
|
||||
/// Shows balancing information for monsters and players.
|
||||
pub fn show_balancing_data(
|
||||
args: &BalanceArgs,
|
||||
config: &Config,
|
||||
connection: Connection,
|
||||
) -> Result<(), anyhow::Error> {
|
||||
let _ = args;
|
||||
let data = fetch_all_creature_data(&connection, config, args.filter.filter.as_deref())?;
|
||||
let player_data = fetch_all_player_data(&connection, config)?;
|
||||
|
||||
for creature in data {
|
||||
// println!("{}", creature.name);
|
||||
let mut table = comfy_table::Table::new();
|
||||
table
|
||||
.load_preset(comfy_table::presets::UTF8_FULL_CONDENSED)
|
||||
.apply_modifier(modifiers::UTF8_ROUND_CORNERS)
|
||||
.set_width(120)
|
||||
.set_content_arrangement(comfy_table::ContentArrangement::Dynamic);
|
||||
table.add_row(vec![
|
||||
creature.id.to_cell(),
|
||||
match creature.balancing.monster_groupsize {
|
||||
1. => creature.name.clone(),
|
||||
n => format!("{} x {}", creature.name, n),
|
||||
}
|
||||
.to_cell()
|
||||
.fg(comfy_table::Color::Blue), // .add_attribute(comfy_table::Attribute::Reverse),
|
||||
]);
|
||||
|
||||
println!("{table}");
|
||||
let player_level = &creature.balancing.profile_hse;
|
||||
let available_profiles = player_data
|
||||
.clone()
|
||||
.into_iter()
|
||||
.filter(|v| &v.profile_hse == player_level)
|
||||
.collect::<Vec<PlayerBalancing>>();
|
||||
|
||||
let profiles: IndexMap<ProfileStance, PlayerBalancing> = available_profiles
|
||||
.into_iter()
|
||||
.map(|profile| (profile.profile_stance, profile))
|
||||
.collect();
|
||||
|
||||
defense_analysis::display_player_attacks(args, &creature, &profiles, DefenseMode::Worst);
|
||||
defense_analysis::display_monster_attacks(args, creature, &profiles, DefenseMode::Best);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
|
@ -1,142 +0,0 @@
|
|||
use crate::{
|
||||
monster_analysis::{
|
||||
helpers,
|
||||
monster_analysis_structs::{
|
||||
self, ArmorBreakCategory, DamageCategory, DefenseMode, Showcase,
|
||||
},
|
||||
},
|
||||
monster_structs::{PlayerBalancing, ProfileStance},
|
||||
};
|
||||
use config::monsters::BalanceArgs;
|
||||
use indexmap::IndexMap;
|
||||
use more_fields::FieldsAsSlice;
|
||||
use std::cmp::max;
|
||||
|
||||
/// Returns the Balancing profile, and eventually the other profiles as well
|
||||
pub fn all_attacks(
|
||||
args: &BalanceArgs,
|
||||
attack: &monster_analysis_structs::MonsterBalancingAttack,
|
||||
victims: &IndexMap<ProfileStance, PlayerBalancing>,
|
||||
mode: DefenseMode,
|
||||
) -> Vec<DamageReport> {
|
||||
let mut balancing = vec![
|
||||
attack_player(
|
||||
attack,
|
||||
&victims[&attack.target_stance],
|
||||
mode,
|
||||
Showcase::Balancing,
|
||||
)
|
||||
.unwrap(),
|
||||
];
|
||||
if !args.show_balanced
|
||||
&& balancing[0].damage_category == attack.target_damage
|
||||
&& balancing[0].armor_category == attack.target_ab
|
||||
{
|
||||
return Vec::new();
|
||||
}
|
||||
if !args.show_extra {
|
||||
return balancing;
|
||||
}
|
||||
let mut v = victims
|
||||
.iter()
|
||||
.filter(|&(stance, _)| *stance != attack.target_stance) // keep only non‑targets
|
||||
.map(|(_, victim)| attack_player(attack, victim, mode, Showcase::Display))
|
||||
.collect::<Option<Vec<DamageReport>>>()
|
||||
.unwrap();
|
||||
|
||||
balancing.append(&mut v);
|
||||
balancing
|
||||
}
|
||||
|
||||
pub fn attack_player(
|
||||
attack: &monster_analysis_structs::MonsterBalancingAttack,
|
||||
victim: &PlayerBalancing,
|
||||
mode: DefenseMode,
|
||||
showcase: Showcase,
|
||||
) -> Option<DamageReport> {
|
||||
// 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),
|
||||
} + victim.specialty_def;
|
||||
|
||||
let bin = helpers::binomial_dice_distribution(threshold, victim.successes_def);
|
||||
let avg_successes_left: f64 = bin
|
||||
.iter()
|
||||
.map(|(dice, p)| (attack.successes - dice) as f64 * p)
|
||||
.sum::<f64>();
|
||||
let avg_damage_incomming: f64 = bin
|
||||
.iter()
|
||||
.map(|(dices, p)| {
|
||||
helpers::how_much_with_succeses(&attack.damage, attack.successes - dices) as f64 * p
|
||||
})
|
||||
.sum::<f64>();
|
||||
let damage_incoming = avg_damage_incomming;
|
||||
let mut damage_tanked =
|
||||
(damage_incoming - (victim.protection + victim.strength) as f64).max(0.0);
|
||||
let mut armor_loss =
|
||||
(damage_incoming - victim.protection as f64).clamp(0.0, attack.armor_break as f64);
|
||||
if avg_successes_left > 0. {
|
||||
armor_loss += attack.antimaterial as f64;
|
||||
damage_tanked += attack.armor_pierce.min(victim.protection) as f64;
|
||||
}
|
||||
let report = DamageReport {
|
||||
damage_incoming,
|
||||
damage_tanked,
|
||||
armor_loss,
|
||||
successes_left: avg_successes_left,
|
||||
damage_category: DamageCategory::from_percent(damage_tanked 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,
|
||||
showcase,
|
||||
fatigue: attack.fatigue,
|
||||
stance: victim.profile_stance,
|
||||
};
|
||||
Some(report)
|
||||
}
|
||||
|
||||
#[derive(Debug, FieldsAsSlice)]
|
||||
pub struct DamageReport {
|
||||
pub name: String,
|
||||
#[INTEGER(name = "dmg_inc")]
|
||||
pub damage_incoming: f64,
|
||||
#[INTEGER(name = "F")]
|
||||
pub fatigue: i64,
|
||||
#[INTEGER(name = "r_left")]
|
||||
pub successes_left: f64,
|
||||
#[INTEGER(name = "dmg_tak")]
|
||||
pub damage_tanked: f64,
|
||||
#[TEXT(name = "dmg_cat")]
|
||||
pub damage_category: DamageCategory,
|
||||
#[TEXT(name = "dmg_expt")]
|
||||
pub damage_expected: DamageCategory,
|
||||
#[INTEGER(name = "arm_loss")]
|
||||
pub armor_loss: f64,
|
||||
#[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 stance: ProfileStance,
|
||||
#[SKIP]
|
||||
pub attack_successes: i64,
|
||||
#[SKIP]
|
||||
pub showcase: monster_analysis_structs::Showcase,
|
||||
}
|
||||
|
|
@ -1,424 +0,0 @@
|
|||
use crate::{
|
||||
monster_analysis::{
|
||||
DefenseMode, attack_analysis,
|
||||
helpers::{binomial_dice_distribution, how_much_with_succeses},
|
||||
monster_analysis_structs::{self, Showcase},
|
||||
},
|
||||
monster_render::ToTable,
|
||||
monster_structs::{CreatureBodyPart, FullMonster, PlayerBalancing, ProfileHSE, ProfileStance},
|
||||
};
|
||||
use config::monsters::BalanceArgs;
|
||||
use indexmap::IndexMap;
|
||||
use more_fields::FieldsAsSlice;
|
||||
use std::ops::AddAssign;
|
||||
|
||||
pub(crate) fn display_player_attacks(
|
||||
args: &BalanceArgs,
|
||||
creature: &FullMonster,
|
||||
profiles: &IndexMap<ProfileStance, PlayerBalancing>,
|
||||
mode: DefenseMode,
|
||||
) {
|
||||
let _ = mode;
|
||||
let r = report_from_profile(args, creature, profiles);
|
||||
println!("{}", r.to_table());
|
||||
}
|
||||
|
||||
fn report_from_profile(
|
||||
args: &BalanceArgs,
|
||||
creature: &FullMonster,
|
||||
profiles: &IndexMap<ProfileStance, PlayerBalancing>,
|
||||
) -> Vec<DefenseReport> {
|
||||
creature
|
||||
.body_parts
|
||||
.body_parts
|
||||
.iter()
|
||||
.flat_map(|body_part| {
|
||||
match args.show_extra {
|
||||
true => vec![
|
||||
(ProfileStance::Neutral, Showcase::Display),
|
||||
(ProfileStance::Defensive, Showcase::Balancing),
|
||||
(ProfileStance::Offensive, Showcase::Balancing),
|
||||
],
|
||||
false => vec![(ProfileStance::Neutral, Showcase::Display)],
|
||||
}
|
||||
.into_iter()
|
||||
.map(|(p, show)| damage_report_on_part(creature, &profiles[&p], body_part, show))
|
||||
.collect::<Vec<DefenseReport>>()
|
||||
})
|
||||
.collect::<Vec<DefenseReport>>()
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct ChunkIter {
|
||||
remaining: f64,
|
||||
}
|
||||
|
||||
impl ChunkIter {
|
||||
fn new(remaining: f64) -> Self {
|
||||
Self { remaining }
|
||||
}
|
||||
}
|
||||
|
||||
impl std::ops::Deref for ChunkIter {
|
||||
type Target = f64;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.remaining
|
||||
}
|
||||
}
|
||||
|
||||
impl Iterator for ChunkIter {
|
||||
type Item = f64;
|
||||
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
if self.remaining >= 1.0 {
|
||||
self.remaining -= 1.0;
|
||||
Some(1.0)
|
||||
} else if self.remaining > 0.0 {
|
||||
// Last piece – whatever is left.
|
||||
let r = self.remaining;
|
||||
self.remaining = 0.0;
|
||||
Some(r)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct DamageTransfer<'a> {
|
||||
body_part: &'a CreatureBodyPart,
|
||||
profile: &'a PlayerBalancing,
|
||||
max_parried: i64,
|
||||
phase: Phases,
|
||||
strength: i64,
|
||||
}
|
||||
fn damage_report_on_part(
|
||||
creature: &FullMonster,
|
||||
profile: &PlayerBalancing,
|
||||
body_part: &CreatureBodyPart,
|
||||
display: Showcase,
|
||||
) -> DefenseReport {
|
||||
// Every round need to eliminate X dices from the pool
|
||||
let mut dice_left_to_parry = creature.balancing.average_defensive_successes;
|
||||
let players = ChunkIter::new(creature.balancing.player_groupsize);
|
||||
let mut total_damage_done_p1 = DamageDealtByPlayer::default();
|
||||
let mut total_damage_done_p2 = DamageDealtByPlayer::default();
|
||||
|
||||
for player_chunk in players {
|
||||
let max_parried = dice_left_to_parry.min(profile.successes_off);
|
||||
let mut damage_done_p1 = damage_done_to_part(&DamageTransfer {
|
||||
body_part,
|
||||
profile,
|
||||
max_parried,
|
||||
phase: Phases::P1,
|
||||
strength: creature.stats.strength,
|
||||
});
|
||||
let mut damage_done_p2 = damage_done_to_part(&DamageTransfer {
|
||||
body_part,
|
||||
profile,
|
||||
max_parried,
|
||||
phase: Phases::P2,
|
||||
strength: creature.stats.strength,
|
||||
});
|
||||
dice_left_to_parry = (dice_left_to_parry - max_parried).max(0);
|
||||
if player_chunk < 1. {
|
||||
damage_done_p1.mult(player_chunk);
|
||||
damage_done_p2.mult(player_chunk);
|
||||
}
|
||||
total_damage_done_p1 += damage_done_p1;
|
||||
total_damage_done_p2 += damage_done_p2;
|
||||
}
|
||||
|
||||
let damage_done_p1 = total_damage_done_p1;
|
||||
let damage_done_p2 = total_damage_done_p2;
|
||||
let ratio = 1.0;
|
||||
// let damage_done_p1 = damage_done_to_part(body_part, profile, dice_left_to_parry, Phases::P1);
|
||||
// let damage_done_p2 = damage_done_to_part(body_part, profile, dice_left_to_parry, Phases::P2);
|
||||
// let ratio = creature.balancing.monster_groupsize / creature.balancing.player_groupsize;
|
||||
|
||||
let time_to_p2 = ratio * body_part.life_points_p1.unwrap() as f64 / damage_done_p1.hp_t;
|
||||
let time_to_kill = ratio
|
||||
* (
|
||||
//body_part.life_points_p1.unwrap() as f64 / damage_done_p1.hp_t +
|
||||
body_part.life_points_p2.unwrap_or(0) as f64 / damage_done_p2.hp_t
|
||||
);
|
||||
let time_to_armorbreak = ratio * (body_part.integrity_p1.unwrap() as f64 / damage_done_p1.ab_t);
|
||||
let time_to_kill_through = ratio
|
||||
* (body_part.life_points_p1.unwrap() as f64
|
||||
/ (damage_done_p1.damage_through - creature.stats.strength as f64).max(0.)
|
||||
+ body_part.life_points_p2.unwrap_or(0) as f64
|
||||
/ (damage_done_p2.damage_through - creature.stats.strength as f64).max(0.));
|
||||
DefenseReport {
|
||||
id: creature.balancing.creature_id,
|
||||
name: creature.name.clone(),
|
||||
part_name: body_part.body_part_name.clone(),
|
||||
profile_hse: creature.balancing.profile_hse.clone(),
|
||||
time_to_p2,
|
||||
time_to_p2_target: creature.balancing.time_to_p2,
|
||||
time_to_armorbreak,
|
||||
time_to_player_kill: creature.balancing.time_to_player_kill,
|
||||
monster_groupsize: creature.balancing.monster_groupsize,
|
||||
player_groupsize: creature.balancing.player_groupsize,
|
||||
time_to_kill,
|
||||
time_to_kill_target: creature.balancing.time_to_kill,
|
||||
damage_per_turn_p1: damage_done_p1.hp_t,
|
||||
damage_per_turn_p2: damage_done_p2.hp_t,
|
||||
health_p1: body_part.life_points_p1.unwrap(),
|
||||
health_p2: body_part.life_points_p2.unwrap_or(0),
|
||||
time_to_armorbreak_target: creature.balancing.time_to_armorbreak,
|
||||
armor_break_per_turn: damage_done_p1.ab_t,
|
||||
integrity_p1: body_part.integrity_p1.unwrap(),
|
||||
damage_through_p1: damage_done_p1.damage_through,
|
||||
damage_through_p2: damage_done_p2.damage_through,
|
||||
time_to_kill_through,
|
||||
target_stance: profile.profile_stance,
|
||||
showcase: display,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn resist_physical(part: &CreatureBodyPart, mode: DefenseMode) -> i64 {
|
||||
let res = [&part.slash, &part.blunt, &part.piercing]
|
||||
.into_iter()
|
||||
.map(value_resist);
|
||||
match mode {
|
||||
DefenseMode::Best => res.max().unwrap_or(0),
|
||||
DefenseMode::Worst => res.min().unwrap_or(0),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn value_resist(resist: &Option<String>) -> i64 {
|
||||
match resist {
|
||||
None => 0,
|
||||
Some(s) => {
|
||||
let mut sum = 0;
|
||||
for c in s.chars() {
|
||||
match c {
|
||||
'+' => sum += 2,
|
||||
'-' => sum -= 2,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
sum
|
||||
}
|
||||
}
|
||||
}
|
||||
pub fn damage_done_to_part(info: &DamageTransfer) -> DamageDealtByPlayer {
|
||||
let part = info.body_part;
|
||||
let profile = info.profile;
|
||||
let dice_parried = info.max_parried;
|
||||
let phase = info.phase;
|
||||
let threshold = match phase {
|
||||
Phases::P1 => part.threshold_p1,
|
||||
Phases::P2 => part.threshold_p2,
|
||||
}
|
||||
.unwrap()
|
||||
+ profile.precision;
|
||||
let (_integrity, protection, resist) = match phase {
|
||||
Phases::P1 => (
|
||||
part.integrity_p1.unwrap(),
|
||||
part.protection_p1.unwrap(),
|
||||
resist_physical(part, DefenseMode::Worst) as f64,
|
||||
),
|
||||
Phases::P2 => (
|
||||
part.integrity_p2.unwrap(),
|
||||
part.protection_p2.unwrap(),
|
||||
resist_physical(part, DefenseMode::Worst) as f64,
|
||||
),
|
||||
};
|
||||
let damage_profile: Vec<i64> = (1..profile.max_successes_off)
|
||||
.map(|v| (v as f64 * profile.damage_per_s) as i64)
|
||||
.collect();
|
||||
// Pick the best damage out of all scenarios:
|
||||
// Scenario A : One big hit
|
||||
// Scenario B : Two half hits
|
||||
let dices = (profile.successes_off - dice_parried).clamp(0, profile.successes_off);
|
||||
let damage_a = (damage_with_profile(&damage_profile, threshold, dices) - resist).max(0.);
|
||||
let damage_b1 = (damage_with_profile(&damage_profile, threshold, dices / 2) - resist).max(0.);
|
||||
let damage_b2 =
|
||||
(damage_with_profile(&damage_profile, threshold, dices - dices / 2) - resist).max(0.);
|
||||
let dt_a = (damage_a - protection as f64 - info.strength as f64).max(0.);
|
||||
let dt_b1 = (damage_b1 - protection as f64 - info.strength as f64).max(0.);
|
||||
let dt_b2 = (damage_b2 - protection as f64 - info.strength as f64).max(0.);
|
||||
|
||||
let ab_a = (damage_a - protection as f64).clamp(0., profile.armor_break as f64);
|
||||
let ab_b1 = (damage_b1 - protection as f64).clamp(0., profile.armor_break as f64);
|
||||
let ab_b2 = (damage_b2 - protection as f64).clamp(0., profile.armor_break as f64);
|
||||
let hp_t = damage_a.max(damage_b1 + damage_b2);
|
||||
let ab_t = ab_a.max(ab_b1 + ab_b2);
|
||||
let damage_through = dt_a.max(dt_b2 + dt_b1);
|
||||
|
||||
DamageDealtByPlayer {
|
||||
damage_a,
|
||||
damage_b1,
|
||||
damage_b2,
|
||||
ab_a,
|
||||
ab_b1,
|
||||
ab_b2,
|
||||
hp_t,
|
||||
ab_t,
|
||||
damage_through,
|
||||
}
|
||||
}
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub enum Phases {
|
||||
P1,
|
||||
P2,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct DamageDealtByPlayer {
|
||||
pub damage_a: f64,
|
||||
pub damage_b1: f64,
|
||||
pub damage_b2: f64,
|
||||
pub ab_a: f64,
|
||||
pub ab_b1: f64,
|
||||
pub ab_b2: f64,
|
||||
pub hp_t: f64,
|
||||
pub ab_t: f64,
|
||||
pub damage_through: f64,
|
||||
}
|
||||
impl AddAssign for DamageDealtByPlayer {
|
||||
fn add_assign(&mut self, rhs: Self) {
|
||||
self.damage_a += rhs.damage_a;
|
||||
self.damage_b1 += rhs.damage_b1;
|
||||
self.damage_b2 += rhs.damage_b2;
|
||||
self.ab_a += rhs.ab_a;
|
||||
self.ab_b1 += rhs.ab_b1;
|
||||
self.ab_b2 += rhs.ab_b2;
|
||||
self.hp_t += rhs.hp_t;
|
||||
self.ab_t += rhs.ab_t;
|
||||
self.damage_through += rhs.damage_through;
|
||||
}
|
||||
}
|
||||
|
||||
impl DamageDealtByPlayer {
|
||||
fn mult(&mut self, rhs: f64) {
|
||||
self.damage_a *= rhs;
|
||||
self.damage_b1 *= rhs;
|
||||
self.damage_b2 *= rhs;
|
||||
self.ab_a *= rhs;
|
||||
self.ab_b1 *= rhs;
|
||||
self.ab_b2 *= rhs;
|
||||
self.hp_t *= rhs;
|
||||
self.ab_t *= rhs;
|
||||
self.damage_through *= rhs;
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn damage_with_profile(damage_profile: &[i64], threshold: i64, dices: i64) -> f64 {
|
||||
let damage = binomial_dice_distribution(threshold, dices);
|
||||
damage
|
||||
.iter()
|
||||
.map(|(d, p)| how_much_with_succeses(damage_profile, *d) as f64 * p)
|
||||
.sum::<f64>()
|
||||
}
|
||||
|
||||
/// A snapshot of all defensive metrics for a single monster encounter.
|
||||
/// Each field has one of three semantic labels:
|
||||
/// * **Fixed** – inherent properties that do not change during the fight.
|
||||
/// * **Actual** – metrics computed from a simulation or run‑time analysis.
|
||||
/// * **Goal** – target values you want to achieve in an optimal strategy.
|
||||
#[derive(Debug, FieldsAsSlice)]
|
||||
pub struct DefenseReport {
|
||||
/// Unique identifier for the monster definition.
|
||||
#[SKIP]
|
||||
pub id: i64,
|
||||
/// Display name of the monster (human‑readable).
|
||||
#[SKIP]
|
||||
pub name: String,
|
||||
/// The part of the monster’s body that is currently active
|
||||
pub part_name: String,
|
||||
/// (Fixed) HSE profile of the hunter.
|
||||
#[SKIP(name = "Profile")]
|
||||
pub profile_hse: ProfileHSE,
|
||||
/// (Fixed) Stance of the player.
|
||||
#[SKIP(name = "Stance")]
|
||||
pub target_stance: ProfileStance,
|
||||
/// (Actual) Armor‑breaking damage per turn.
|
||||
/// This is the rate at which the monster’s armor is degraded during combat.
|
||||
#[INTEGER(name = "AbPT P1")]
|
||||
pub armor_break_per_turn: f64,
|
||||
/// (Actual) Turns until this monster’s armor breaks, i.e. the point
|
||||
/// at which it stops being able to mitigate incoming damage.
|
||||
#[INTEGER(name = "TT AB")]
|
||||
pub time_to_armorbreak: f64,
|
||||
/// Damage per turn while in phase 1.
|
||||
/// Used when the monster changes behaviour between phases.
|
||||
#[INTEGER(name = "DPT P1")]
|
||||
pub damage_per_turn_p1: f64,
|
||||
/// (Actual) Turns needed to reach phase 2.
|
||||
/// Computed from the monster’s health and damage output or from simulation data.
|
||||
#[REAL(name = "P1 🠲 P2")]
|
||||
pub time_to_p2: f64,
|
||||
/// (Goal) Desired turns to reach phase 2.
|
||||
/// If the current `time_to_p2` exceeds this value, the fight is considered inefficient.
|
||||
#[SKIP]
|
||||
pub time_to_p2_target: f64,
|
||||
/// Damage per turn while in phase 2.
|
||||
#[INTEGER(name = "DPT P2")]
|
||||
pub damage_per_turn_p2: f64,
|
||||
/// (Actual) Turns needed to kill the monster.
|
||||
/// Derived from its health and damage per turn or from a run‑time simulation.
|
||||
#[INTEGER(name = "P2 ➜ 🕇")]
|
||||
pub time_to_kill: f64,
|
||||
/// (Goal) Desired turns to kill the monster.
|
||||
/// If actual `time_to_kill` is larger, you may need to adjust attack power or strategy.
|
||||
#[SKIP]
|
||||
pub time_to_kill_target: f64,
|
||||
/// (Goal) Desired turns until the monster’s armor breaks.
|
||||
/// A lower value indicates a more aggressive strategy.
|
||||
#[SKIP(name = "ttAB")]
|
||||
pub time_to_armorbreak_target: f64,
|
||||
/// (Goal) Average turns to kill a single player
|
||||
#[SKIP(name = "ttPK")]
|
||||
pub time_to_player_kill: f64,
|
||||
/// (Fixed) The number of monsters in a single group.
|
||||
/// Usually `1`, but can be > 1 for bosses that spawn multiple instances.
|
||||
#[SKIP]
|
||||
pub monster_groupsize: f64,
|
||||
/// (Fixed) Number of players this fight was designed for.
|
||||
#[SKIP]
|
||||
pub player_groupsize: f64,
|
||||
/// (Fixed) Health points during phase 1.
|
||||
#[SKIP]
|
||||
pub health_p1: i64,
|
||||
/// (Fixed) Health points during phase 2.
|
||||
#[SKIP]
|
||||
pub health_p2: i64,
|
||||
/// (Fixed) Integrity points during phase 1, representing how many
|
||||
/// damage points the monster can take before losing its first phase.
|
||||
#[SKIP]
|
||||
pub integrity_p1: i64,
|
||||
/// (Actual) Damage going through the creature during p1
|
||||
#[SKIP]
|
||||
pub damage_through_p1: f64,
|
||||
/// (Actual) Damage going through the creature during p2
|
||||
#[SKIP]
|
||||
pub damage_through_p2: f64,
|
||||
/// (Actual) Time to kill through armor
|
||||
#[INTEGER(name = "P1 ⇝ P2 ⇝ 🕇")]
|
||||
pub time_to_kill_through: f64,
|
||||
/// (Misc) Display name or target of balancing
|
||||
#[SKIP]
|
||||
pub showcase: Showcase,
|
||||
}
|
||||
|
||||
pub(crate) fn display_monster_attacks(
|
||||
args: &BalanceArgs,
|
||||
creature: FullMonster,
|
||||
profiles: &IndexMap<ProfileStance, PlayerBalancing>,
|
||||
mode: DefenseMode,
|
||||
) {
|
||||
let attacks: Vec<monster_analysis_structs::MonsterBalancingAttack> = creature.into();
|
||||
if args.show_profiles {
|
||||
let table = attacks.to_table();
|
||||
println!("{table}");
|
||||
}
|
||||
|
||||
let mut res = Vec::new();
|
||||
for attack in attacks {
|
||||
let mut report = attack_analysis::all_attacks(args, &attack, profiles, mode);
|
||||
res.append(&mut report);
|
||||
}
|
||||
println!("{}", res.to_table());
|
||||
}
|
||||
|
|
@ -1,73 +0,0 @@
|
|||
use std::cmp::min;
|
||||
|
||||
use probability::distribution::Discrete;
|
||||
use probability::prelude::Binomial;
|
||||
|
||||
// Binomial damage distribution
|
||||
// As a (0s, p), (1s, p) etc
|
||||
// can be used to calc avg damage
|
||||
// with avg(dmg_with_successes(i)*j)
|
||||
/// Calculate the binomial distribution and average the damage from there
|
||||
pub(super) fn binomial_dice_distribution(threshold: i64, dices: i64) -> Vec<(i64, f64)> {
|
||||
let p = ((threshold as f64) / 10.).clamp(0. + 1E-10, 1. - 1E-10);
|
||||
let binomial = Binomial::new(dices as usize, p);
|
||||
|
||||
(0..(dices + 1) as usize)
|
||||
.map(|target_dices| {
|
||||
let probability_success = binomial.mass(target_dices);
|
||||
(target_dices as i64, probability_success)
|
||||
})
|
||||
.collect::<Vec<(i64, f64)>>()
|
||||
}
|
||||
|
||||
pub fn thld(r_succeses: i64, threshold_parry: i64) -> i64 {
|
||||
(r_succeses * min(threshold_parry, 10)) / 10
|
||||
}
|
||||
|
||||
pub fn how_much_with_succeses(damage: &[i64], succeses: i64) -> i64 {
|
||||
if succeses <= 0 {
|
||||
0
|
||||
} else {
|
||||
damage[(succeses - 1).clamp(0_i64, damage.len() as i64 - 1) as usize]
|
||||
}
|
||||
}
|
||||
/// Shorten a string so that its final length (including the three‑dot marker) does not exceed `size`.
|
||||
///
|
||||
/// If `size` is smaller than four the function simply truncates to that length
|
||||
/// (there’s no room for “…”).
|
||||
///
|
||||
/// # Parameters
|
||||
/// * `s` – The string slice to shorten.
|
||||
/// * `size` – Maximum length of the returned string, including the ellipsis.
|
||||
pub fn shorten_string(s: &str, size: usize) -> String {
|
||||
// If it already fits, just return a copy.
|
||||
if s.len() <= size {
|
||||
return s.to_owned();
|
||||
}
|
||||
|
||||
// No room for "…" + at least one char each side → just cut off.
|
||||
if size < 4 {
|
||||
return s.chars().take(size).collect();
|
||||
}
|
||||
|
||||
// How many chars we keep from the front / back?
|
||||
let usable = size - 3; // length available for real characters
|
||||
let half = usable / 2; // baseline number of chars per side
|
||||
let extra = usable % 2; // if odd, give one more to the front
|
||||
|
||||
let front_len = half + extra;
|
||||
let back_len = half;
|
||||
|
||||
// Grab the required portions.
|
||||
let front: String = s.chars().take(front_len).collect();
|
||||
let back: String = s
|
||||
.chars()
|
||||
.rev() // reverse for an easy “take last N”
|
||||
.take(back_len)
|
||||
.collect::<String>()
|
||||
.chars()
|
||||
.rev() // bring them back to normal order
|
||||
.collect();
|
||||
|
||||
format!("{}...{}", front, back)
|
||||
}
|
||||
|
|
@ -1,243 +0,0 @@
|
|||
use crate::monster_structs::{FullMonster, PlayerBalancing, ProfileStance};
|
||||
use more_fields::FieldsAsSlice;
|
||||
use std::str::FromStr;
|
||||
use strum::{Display, EnumString};
|
||||
|
||||
impl From<FullMonster> for Vec<MonsterBalancingAttack> {
|
||||
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: from_successes(sub_attack.success.as_ref()),
|
||||
armor_break: from_opt_i64(sub_attack.armor_break.as_ref()),
|
||||
action_cost: from_actions(sub_attack.cost_action.as_ref()),
|
||||
fatigue: from_opt_fatigue(sub_attack.damage_fatigue.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(),
|
||||
antimaterial: from_opt_i64(sub_attack.antimaterial.as_ref()),
|
||||
armor_pierce: from_opt_i64(sub_attack.armor_pierce.as_ref()),
|
||||
}
|
||||
})
|
||||
.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<i64>,
|
||||
#[INTEGER(name = "r")]
|
||||
pub successes: i64,
|
||||
#[INTEGER(name = "ab")]
|
||||
pub armor_break: i64,
|
||||
#[INTEGER(name = "A")]
|
||||
pub action_cost: i64,
|
||||
#[INTEGER(name = "F")]
|
||||
pub fatigue: 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,
|
||||
#[SKIP(name = "AM")]
|
||||
pub antimaterial: i64,
|
||||
#[SKIP(name = "AP")]
|
||||
pub armor_pierce: i64,
|
||||
}
|
||||
|
||||
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 {
|
||||
/// Malformed data
|
||||
#[default]
|
||||
Malformed,
|
||||
/// No lasting damage
|
||||
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 {
|
||||
/// Malformed data
|
||||
#[default]
|
||||
Malformed,
|
||||
/// No lasting damage
|
||||
None,
|
||||
/// Chip damage
|
||||
Chip,
|
||||
/// Moderate
|
||||
Moderate,
|
||||
/// High, above half
|
||||
High,
|
||||
/// Full destruction
|
||||
FullBreak,
|
||||
/// Complete overkill > 200%
|
||||
Overkill,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub enum Showcase {
|
||||
Display,
|
||||
Balancing,
|
||||
}
|
||||
|
||||
#[derive(Debug, Copy, Clone, Display)]
|
||||
pub enum DefenseMode {
|
||||
Best,
|
||||
Worst,
|
||||
}
|
||||
|
||||
impl ArmorBreakCategory {
|
||||
pub fn from_percent(value: f64) -> Self {
|
||||
match value {
|
||||
..0.01 => ArmorBreakCategory::None,
|
||||
0.01..0.3 => ArmorBreakCategory::Chip,
|
||||
0.3..0.5 => ArmorBreakCategory::Moderate,
|
||||
0.5..0.9 => ArmorBreakCategory::High,
|
||||
0.8..1.2 => ArmorBreakCategory::FullBreak,
|
||||
1.2.. => ArmorBreakCategory::Overkill,
|
||||
_ => ArmorBreakCategory::None,
|
||||
}
|
||||
}
|
||||
}
|
||||
impl From<Option<String>> for DamageCategory {
|
||||
fn from(value: Option<String>) -> Self {
|
||||
if let Some(value) = value {
|
||||
Self::from_str(&value).unwrap_or_default()
|
||||
} else {
|
||||
Self::Malformed
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Option<String>> for ArmorBreakCategory {
|
||||
fn from(value: Option<String>) -> Self {
|
||||
if let Some(value) = value {
|
||||
Self::from_str(&value).unwrap_or_default()
|
||||
} else {
|
||||
Self::Malformed
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Option<String>> for ProfileStance {
|
||||
fn from(value: Option<String>) -> 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<i64> {
|
||||
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_fatigue(str: Option<&String>) -> i64 {
|
||||
match str {
|
||||
Some(str) => str.replace("F", "").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,
|
||||
}
|
||||
}
|
||||
|
||||
impl DamageCategory {
|
||||
pub fn from_percent(percent: f64) -> Self {
|
||||
match percent {
|
||||
..0.01 => Self::None,
|
||||
0.01..0.25 => Self::Chip,
|
||||
0.25..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,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,165 +0,0 @@
|
|||
#![allow(dead_code)]
|
||||
|
||||
use crate::monster_structs::{
|
||||
self, CreatureReward, MonsterAllAttacks, MonsterRepetableInitRow, PlayerBalancing,
|
||||
};
|
||||
use crate::monster_structs::{
|
||||
CreatureBodyPart, CreatureData, CreatureListAttacks, CreatureStats, FullMonster,
|
||||
MonsterSingleAttack,
|
||||
};
|
||||
use anyhow::{Context, anyhow};
|
||||
use cli_parser::Config;
|
||||
use more_fields::FieldsAsSlice;
|
||||
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))?
|
||||
}};
|
||||
}
|
||||
|
||||
/// Fetch all data from the database
|
||||
pub(crate) fn fetch_all_creature_data(
|
||||
connection: &Connection,
|
||||
config: &Config,
|
||||
filter: Option<&str>,
|
||||
) -> Result<Vec<FullMonster>, anyhow::Error> {
|
||||
let list_creatures =
|
||||
generic_deserialize::<CreatureData>(connection, "creature", filter, Some("sort_id"))?;
|
||||
let mut finished_creatures = Vec::new();
|
||||
for creature in list_creatures.iter() {
|
||||
// println!("Working on {}@{}", creature.id, creature.name);
|
||||
let creature_stats: CreatureStats =
|
||||
fetch_one_field(connection, creature, "creature_stats")?;
|
||||
finished_creatures.push(FullMonster {
|
||||
id: creature.id,
|
||||
name: creature.name.clone(),
|
||||
init_full: MonsterRepetableInitRow::vec_from(
|
||||
&creature_stats.p1_init,
|
||||
&creature_stats.p2_init,
|
||||
&creature_stats.p1_actions,
|
||||
&creature_stats.p2_actions,
|
||||
),
|
||||
stats: creature_stats, // fetch_one_field(connection, creature, "creature_stats")?,
|
||||
all_attacks: MonsterAllAttacks::from_retrieved_data(
|
||||
&fetch_from!(
|
||||
MonsterSingleAttack,
|
||||
connection,
|
||||
creature,
|
||||
"creature_abilities",
|
||||
Some("phase, attack_group, ordering")
|
||||
),
|
||||
config,
|
||||
),
|
||||
attacks: CreatureListAttacks {
|
||||
attacks: fetch_from!(
|
||||
MonsterSingleAttack,
|
||||
connection,
|
||||
creature,
|
||||
"creature_abilities",
|
||||
Some("phase, attack_group, ordering")
|
||||
),
|
||||
},
|
||||
body_parts: monster_structs::CreatureListBodyParts {
|
||||
body_parts: fetch_from!(
|
||||
CreatureBodyPart,
|
||||
connection,
|
||||
creature,
|
||||
"creature_body_parts",
|
||||
None
|
||||
),
|
||||
},
|
||||
rewards: monster_structs::CreatureListRewards {
|
||||
rewards: fetch_from!(
|
||||
CreatureReward,
|
||||
connection,
|
||||
creature,
|
||||
"creature_rewards",
|
||||
None
|
||||
),
|
||||
},
|
||||
balancing: fetch_one_field(connection, creature, "creature_balancing")?,
|
||||
data: creature.clone(),
|
||||
});
|
||||
}
|
||||
Ok(finished_creatures)
|
||||
}
|
||||
|
||||
pub(crate) fn fetch_all_player_data(
|
||||
connection: &Connection,
|
||||
config: &Config,
|
||||
) -> Result<Vec<PlayerBalancing>, anyhow::Error> {
|
||||
let _ = config;
|
||||
generic_deserialize::<PlayerBalancing>(connection, "player_balancing", None, None)
|
||||
}
|
||||
|
||||
/// Fetches **the single** row that matches `creature` from the given `table_name`.
|
||||
///
|
||||
/// The query is performed through the `fetch_from!` macro, which returns a vector of
|
||||
/// values deserialised into `T`. If the resulting vector does not contain exactly
|
||||
/// one element an error is returned; otherwise the sole value is extracted.
|
||||
fn fetch_one_field<T: DeserializeOwned + FieldsAsSlice>(
|
||||
connection: &Connection,
|
||||
creature: &CreatureData,
|
||||
table_name: &str,
|
||||
) -> Result<T, anyhow::Error> {
|
||||
let mut creature_stats = fetch_from!(T, connection, creature, table_name, None);
|
||||
if creature_stats.len() != 1 {
|
||||
return Err(anyhow!(
|
||||
"The number of {} entries for the creature {} should be exactly one found {}",
|
||||
table_name,
|
||||
creature.name,
|
||||
creature_stats.len()
|
||||
));
|
||||
};
|
||||
Ok(creature_stats.pop().unwrap())
|
||||
}
|
||||
|
||||
/// 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)
|
||||
)
|
||||
}
|
||||
|
|
@ -1,169 +0,0 @@
|
|||
//! Monster export module
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use cli_parser::Config;
|
||||
use config::monsters::ExportArgs;
|
||||
use handlebars::{Handlebars, handlebars_helper};
|
||||
use indexmap::IndexMap;
|
||||
use rusqlite::Connection;
|
||||
use std::{fmt::Write, fs::File, io::Write as OtherWrite};
|
||||
|
||||
use crate::monster_database::fetch_all_creature_data;
|
||||
use crate::monster_structs::{MonsterAllAttacks, MonsterFullAttack, MonsterSingleAttack};
|
||||
|
||||
/// Load a template from a struct field into a `templates` collection.
|
||||
///
|
||||
/// $templates – the variable that holds the template collection
|
||||
/// $cfg_path – any path (e.g. `config`, `self.cfg`, …) that points to a
|
||||
/// struct containing the field we want
|
||||
/// $name – the identifier of the field / template name
|
||||
macro_rules! template_load {
|
||||
($templates:ident, $cfg_path:expr, $name:ident) => {{
|
||||
$templates
|
||||
.register_template_string(
|
||||
stringify!($name), // "intro"
|
||||
&$cfg_path.$name, // &config.monster.intro
|
||||
)
|
||||
.context(concat!("Registering ", stringify!($name), " template"))? // ? propagates errors
|
||||
}};
|
||||
}
|
||||
|
||||
handlebars_helper!(plus: |x:i64 ,y:Option<i64>| x+y.unwrap_or(0));
|
||||
handlebars_helper!(threshold_bonus: |threshold:i64, size:i64| {
|
||||
let mal = (threshold-6-size).min(-2);
|
||||
let bon = threshold-mal-6;
|
||||
format!("{:+}{:+}",mal,bon)
|
||||
});
|
||||
|
||||
fn load_templates(config: &Config) -> Result<Handlebars<'_>> {
|
||||
let mut templates = Handlebars::new();
|
||||
template_load!(templates, &config.monster, common_part);
|
||||
template_load!(templates, &config.monster, master_part);
|
||||
templates.register_helper("plus", Box::new(plus));
|
||||
templates.register_helper("threshold_bonus", Box::new(threshold_bonus));
|
||||
Ok(templates)
|
||||
}
|
||||
|
||||
/// Export a tex with the given config and arguments
|
||||
pub fn generate_monsters_tex(
|
||||
args: &ExportArgs,
|
||||
config: &Config,
|
||||
connection: Connection,
|
||||
) -> std::result::Result<(), anyhow::Error> {
|
||||
let all_monsters = fetch_all_creature_data(&connection, config, args.filter.filter.as_deref())?;
|
||||
let templates = load_templates(config)?;
|
||||
println!("Processing");
|
||||
let mut m_out = String::new();
|
||||
let mut p_out = String::new();
|
||||
|
||||
for creature in &all_monsters {
|
||||
if !creature.data.show_to_master.is_none_or(|v| v == 0) {
|
||||
println!(" > {}", creature.name);
|
||||
};
|
||||
write!(p_out, "{}", templates.render("common_part", &creature)?)?;
|
||||
if args.master || args.all {
|
||||
write!(m_out, "{}", templates.render("common_part", &creature)?)?;
|
||||
write!(m_out, "{}", templates.render("master_part", &creature)?)?;
|
||||
}
|
||||
}
|
||||
|
||||
if args.player || args.all {
|
||||
println!("Generating Player Bestiaire");
|
||||
let path = format!("./{}/player_bestiaire.tex", args.destination);
|
||||
let mut f = File::create(&path).context(format!("Opening file {}", path))?;
|
||||
write!(f, "{}", p_out).context(format!("Writing {}", path))?;
|
||||
}
|
||||
if args.master || args.all {
|
||||
println!("Generating Master Bestiaire");
|
||||
let path = format!("./{}/master_bestiaire.tex", args.destination);
|
||||
let mut f = File::create(&path).context(format!("Opening file {}", path))?;
|
||||
write!(f, "{}", m_out).context(format!("Writing {}", path))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
impl MonsterAllAttacks {
|
||||
pub fn from_retrieved_data(
|
||||
original_data: &[MonsterSingleAttack],
|
||||
config: &Config,
|
||||
) -> MonsterAllAttacks {
|
||||
let mut initial_phases: IndexMap<&String, Vec<&MonsterSingleAttack>> = IndexMap::new();
|
||||
let mut phases: IndexMap<String, Vec<MonsterFullAttack>> = IndexMap::new();
|
||||
// Intermediate split with hashmaps
|
||||
for atk in original_data {
|
||||
if let Some(values) = initial_phases.get_mut(&atk.phase) {
|
||||
values.push(atk);
|
||||
} else {
|
||||
initial_phases.insert(&atk.phase, vec![atk]);
|
||||
}
|
||||
}
|
||||
for (phase, phase_atks) in initial_phases.iter() {
|
||||
let mut grouped_attacks: IndexMap<&Option<String>, Vec<&MonsterSingleAttack>> =
|
||||
IndexMap::new();
|
||||
let phase_name = phase.to_string();
|
||||
phases.insert(phase_name.clone(), Vec::new());
|
||||
// Pregroup attacks
|
||||
for &atk in phase_atks {
|
||||
if let Some(values) = grouped_attacks.get_mut(&atk.attack_group) {
|
||||
values.push(atk);
|
||||
} else {
|
||||
grouped_attacks.insert(&atk.attack_group, vec![atk]);
|
||||
}
|
||||
}
|
||||
// Ungroup them to have nice bundles
|
||||
for (group, atk) in grouped_attacks {
|
||||
if group.is_some() {
|
||||
let monster_first_atk = atk.first().unwrap();
|
||||
let color = color(monster_first_atk, config);
|
||||
let group_attack = MonsterFullAttack {
|
||||
color,
|
||||
attacklist: atk.iter().map(|&v| v.clone()).collect(),
|
||||
size: atk.len() + number_of_description(monster_first_atk),
|
||||
description_final: monster_first_atk
|
||||
.description_all
|
||||
.clone()
|
||||
.unwrap_or_default(),
|
||||
};
|
||||
// println!("group: {:#?}", group_attack.description_final);
|
||||
phases.get_mut(&phase_name).unwrap().push(group_attack);
|
||||
} else {
|
||||
for single_atk in atk {
|
||||
// println!("single: {:#?}", single_atk.description_all);
|
||||
phases
|
||||
.get_mut(&phase_name)
|
||||
.unwrap()
|
||||
.push(MonsterFullAttack {
|
||||
color: color(single_atk, config),
|
||||
attacklist: vec![single_atk.clone()],
|
||||
size: 1 + number_of_description(&single_atk),
|
||||
description_final: single_atk
|
||||
.description_all
|
||||
.clone()
|
||||
.unwrap_or_default(),
|
||||
});
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
Self { phases }
|
||||
}
|
||||
}
|
||||
|
||||
fn color(atk: &MonsterSingleAttack, config: &Config) -> String {
|
||||
config
|
||||
.monster
|
||||
.color_table
|
||||
.inner
|
||||
.get(&atk.attack_type)
|
||||
.unwrap_or(&config.monster.default_color)
|
||||
.clone()
|
||||
}
|
||||
|
||||
/// The number of description fields
|
||||
fn number_of_description(monster_first_atk: &&MonsterSingleAttack) -> usize {
|
||||
if monster_first_atk.description_all.is_some() {
|
||||
1
|
||||
} else {
|
||||
0
|
||||
}
|
||||
}
|
||||
|
|
@ -1,363 +0,0 @@
|
|||
use crate::monster_analysis::{
|
||||
defense_analysis::DefenseReport,
|
||||
helpers::{self, shorten_string},
|
||||
monster_analysis_structs::Showcase,
|
||||
};
|
||||
use comfy_table::{Color, Table, *};
|
||||
|
||||
use crate::{
|
||||
monster_analysis::{
|
||||
attack_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 {
|
||||
fn to_cell(&self) -> Cell;
|
||||
}
|
||||
|
||||
pub trait ToRow {
|
||||
fn to_row(&self) -> Row;
|
||||
}
|
||||
pub trait ToTable {
|
||||
fn to_table(&self) -> Table;
|
||||
}
|
||||
|
||||
impl<T> ToTable for Vec<T>
|
||||
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.fatigue.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![
|
||||
self.profile_hse.to_cell(),
|
||||
self.profile_stance.to_cell(),
|
||||
Cell::new(format!("{:?}", self.damage_per_s)),
|
||||
Cell::new(format!("{:?}", self.successes_off)),
|
||||
Cell::new(format!("{:?}", self.protection)),
|
||||
Cell::new(format!("{:?}", self.strength)),
|
||||
Cell::new(format!("{:?}", self.integrity)),
|
||||
Cell::new(format!("{:?}", self.health)),
|
||||
]
|
||||
.into()
|
||||
}
|
||||
}
|
||||
|
||||
// macro_rules! show_if {
|
||||
// ($self:ident, $content:expr) => {{
|
||||
// match $self.showcase {
|
||||
// Showcase::Display => String::new().to_cell(),
|
||||
// Showcase::Balancing => $content,
|
||||
// }
|
||||
// }};
|
||||
// }
|
||||
macro_rules! dim_if_not {
|
||||
($self:ident, $content:expr) => {{
|
||||
match $self.showcase {
|
||||
Showcase::Display => $content
|
||||
// .add_attribute(Attribute::Dim)
|
||||
.add_attribute(Attribute::NoReverse),
|
||||
// .fg(Color::DarkGrey)
|
||||
Showcase::Balancing => $content,
|
||||
}
|
||||
}};
|
||||
}
|
||||
macro_rules! attr_if_not {
|
||||
($self:ident, $content:expr, $attribute:expr) => {{
|
||||
match $self.showcase {
|
||||
Showcase::Display => $content
|
||||
// .add_attribute(Attribute::Dim)
|
||||
.add_attribute($attribute),
|
||||
// .fg(Color::DarkGrey)
|
||||
Showcase::Balancing => $content,
|
||||
}
|
||||
}};
|
||||
}
|
||||
impl ToRow for DamageReport {
|
||||
fn to_row(&self) -> Row {
|
||||
vec![
|
||||
match self.showcase {
|
||||
Showcase::Balancing => format!(
|
||||
"[{}]{}",
|
||||
self.stance.to_string().chars().nth(0).unwrap_or(' '),
|
||||
shorten_string(&self.name, 15)
|
||||
)
|
||||
.to_cell()
|
||||
.fg(Color::Green),
|
||||
Showcase::Display => self.stance.to_string().to_cell().fg(Color::DarkGrey),
|
||||
},
|
||||
dim_if_not!(
|
||||
self,
|
||||
format!(
|
||||
"{:.1} [{:.1}r]",
|
||||
self.damage_incoming, self.attack_successes,
|
||||
)
|
||||
.to_cell()
|
||||
),
|
||||
attr_if_not!(
|
||||
self,
|
||||
format!("{}", self.fatigue,)
|
||||
.to_cell()
|
||||
.add_attribute(match self.fatigue == 0 {
|
||||
true => Attribute::Hidden,
|
||||
false => Attribute::NoHidden,
|
||||
}),
|
||||
Attribute::Hidden
|
||||
),
|
||||
dim_if_not!(
|
||||
self,
|
||||
format!("{:.1} [>{:.1}]", self.successes_left, self.threshold)
|
||||
.to_cell()
|
||||
.fg(if self.successes_left > 0.0 {
|
||||
Color::Blue
|
||||
} else {
|
||||
Color::Red
|
||||
})
|
||||
),
|
||||
dim_if_not!(
|
||||
self,
|
||||
format!("{:.1}/{:.1}", self.damage_tanked, self.player_health)
|
||||
.to_cell()
|
||||
.fg(self.damage_category.get_color())
|
||||
),
|
||||
dim_if_not!(
|
||||
self,
|
||||
self.damage_category.to_cell().add_attribute(
|
||||
if self.damage_expected != self.damage_category {
|
||||
Attribute::Reverse
|
||||
} else {
|
||||
Attribute::Dim
|
||||
},
|
||||
)
|
||||
),
|
||||
attr_if_not!(self, self.damage_expected.to_cell(), Attribute::Hidden),
|
||||
dim_if_not!(
|
||||
self,
|
||||
format!("{:.1}/{:.1}", self.armor_loss, self.player_integrity)
|
||||
.to_cell()
|
||||
.fg(self.armor_category.get_color())
|
||||
),
|
||||
dim_if_not!(
|
||||
self,
|
||||
self.armor_category.to_cell().add_attribute(
|
||||
if self.armor_expected != self.armor_category {
|
||||
Attribute::Reverse
|
||||
} else {
|
||||
Attribute::Dim
|
||||
},
|
||||
)
|
||||
),
|
||||
attr_if_not!(self, self.armor_expected.to_cell(), Attribute::Hidden),
|
||||
]
|
||||
.into()
|
||||
}
|
||||
}
|
||||
impl ToCell for DamageCategory {
|
||||
fn to_cell(&self) -> Cell {
|
||||
Into::<Cell>::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,
|
||||
DamageCategory::Malformed => Color::Black,
|
||||
}
|
||||
}
|
||||
}
|
||||
impl ToCell for ArmorBreakCategory {
|
||||
fn to_cell(&self) -> Cell {
|
||||
Into::<Cell>::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::Green,
|
||||
ArmorBreakCategory::Moderate => Color::Blue,
|
||||
ArmorBreakCategory::High => Color::Yellow,
|
||||
ArmorBreakCategory::FullBreak => Color::Red,
|
||||
ArmorBreakCategory::Overkill => Color::DarkRed,
|
||||
ArmorBreakCategory::Malformed => Color::Black,
|
||||
}
|
||||
}
|
||||
}
|
||||
impl ToCell for i64 {
|
||||
fn to_cell(&self) -> Cell {
|
||||
format!("{}", self).into()
|
||||
}
|
||||
}
|
||||
impl ToCell for Vec<i64> {
|
||||
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 {
|
||||
ProfileHSE::Lowest => Into::<Cell>::into(format!("{self:?}")).fg(Color::DarkRed),
|
||||
ProfileHSE::Low => Into::<Cell>::into(format!("{self:?}")).fg(Color::Red),
|
||||
ProfileHSE::Mid => Into::<Cell>::into(format!("{self:?}")).fg(Color::Yellow),
|
||||
ProfileHSE::High => Into::<Cell>::into(format!("{self:?}")).fg(Color::Green),
|
||||
ProfileHSE::Highest => Into::<Cell>::into(format!("{self:?}")).fg(Color::Blue),
|
||||
ProfileHSE::HighestPlus => Into::<Cell>::into(format!("{self:?}")).fg(Color::DarkBlue),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ToCell for ProfileStance {
|
||||
fn to_cell(&self) -> Cell {
|
||||
match self {
|
||||
ProfileStance::Defensive => Into::<Cell>::into(format!("{self:?}")).fg(Color::Blue),
|
||||
ProfileStance::Offensive => Into::<Cell>::into(format!("{self:?}")).fg(Color::Red),
|
||||
ProfileStance::Neutral => Into::<Cell>::into(format!("{self:?}")).fg(Color::Yellow),
|
||||
ProfileStance::NoDefense => Into::<Cell>::into(format!("{self:?}")).fg(Color::DarkRed),
|
||||
}
|
||||
}
|
||||
}
|
||||
// 🠰
|
||||
impl ToRow for DefenseReport {
|
||||
fn to_row(&self) -> comfy_table::Row {
|
||||
let row: Vec<Cell> = vec![
|
||||
// format!("{:?}", self.id).to_cell(),
|
||||
match self.showcase {
|
||||
Showcase::Display => {
|
||||
helpers::shorten_string(&self.part_name.to_string(), 18).to_cell()
|
||||
}
|
||||
Showcase::Balancing => self.target_stance.to_cell().fg(Color::DarkGrey),
|
||||
},
|
||||
dim_if_not!(
|
||||
self,
|
||||
format!("{:.1?}/{}", self.armor_break_per_turn, self.integrity_p1)
|
||||
.to_cell()
|
||||
.fg(Color::DarkGrey)
|
||||
),
|
||||
dim_if_not!(
|
||||
self,
|
||||
compare_vals("t", self.time_to_armorbreak, self.time_to_armorbreak_target)
|
||||
),
|
||||
dim_if_not!(
|
||||
self,
|
||||
format!("{:.1?}/{}", self.damage_per_turn_p1, self.health_p1)
|
||||
.to_cell()
|
||||
.fg(Color::DarkGrey)
|
||||
),
|
||||
dim_if_not!(
|
||||
self,
|
||||
compare_vals("t", self.time_to_p2, self.time_to_p2_target)
|
||||
),
|
||||
dim_if_not!(
|
||||
self,
|
||||
format!("{:.1?}/{}", self.damage_per_turn_p2, self.health_p2)
|
||||
.to_cell()
|
||||
.fg(Color::DarkGrey)
|
||||
),
|
||||
dim_if_not!(
|
||||
self,
|
||||
compare_vals("t", self.time_to_kill, self.time_to_kill_target)
|
||||
),
|
||||
dim_if_not!(
|
||||
self,
|
||||
format!(
|
||||
"[{:.0} & {:.0}] ⇝ {}",
|
||||
self.damage_through_p1,
|
||||
self.damage_per_turn_p2,
|
||||
fmt_target(self.time_to_kill_through)
|
||||
)
|
||||
.to_cell()
|
||||
.fg(Color::DarkGrey)
|
||||
),
|
||||
];
|
||||
row.into()
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn fmt_target(v: f64) -> String {
|
||||
const TOO_MUCH: f64 = 1_000_000_000_000_000.0;
|
||||
const TRILLION: f64 = 1_000_000_000_000.0;
|
||||
const BILLION: f64 = 1_000_000_000.0;
|
||||
const MILLION: f64 = 1_000_000.0;
|
||||
const THOUSAND: f64 = 1_000.0;
|
||||
|
||||
match v {
|
||||
_ if v >= TOO_MUCH => "⇑⇑⇑⇑T".to_string(),
|
||||
_ if v >= TRILLION => format!("⇑{:.1}T", v / TRILLION),
|
||||
_ if v >= BILLION => format!("⇑{:.1}B", v / BILLION),
|
||||
_ if v >= MILLION => format!("⇑{:.1}M", v / MILLION),
|
||||
_ if v >= THOUSAND => format!("⇑{:.1}k", v / THOUSAND),
|
||||
_ => format!("{:.1}", v),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn compare_vals(unit: &str, actual: f64, target: f64) -> Cell {
|
||||
let pct_diff = ((actual - target).abs() / target) * 100.0; // % diff
|
||||
// let actual = 100000000000.;
|
||||
let actual = if pct_diff > 1.0 {
|
||||
fmt_target(actual)
|
||||
} else {
|
||||
format!("{:.1?}", actual)
|
||||
};
|
||||
format!("{}/{:.0?}{}", actual, target, unit)
|
||||
.to_cell()
|
||||
.fg(pct_diff_to_colour(pct_diff))
|
||||
}
|
||||
|
||||
/// Turn percent‑difference into one of four hard‑coded colours.
|
||||
pub(crate) fn pct_diff_to_colour(pct_diff: f64) -> Color {
|
||||
match pct_diff {
|
||||
p if p < 20.0 => Color::Green,
|
||||
p if p < 30.0 => Color::Blue,
|
||||
p if p < 40.0 => Color::Red,
|
||||
_ => Color::DarkRed,
|
||||
}
|
||||
}
|
||||
|
|
@ -1,546 +0,0 @@
|
|||
//! # Monster Structures
|
||||
//!
|
||||
//! 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
|
||||
//! ```text
|
||||
//! FullMonster → MonsterStats
|
||||
//! ↘ MonsterAttacks → Vec<MonsterSingleAttack>
|
||||
//! ↗ MonsterResistances → Vec<MonsterSingleResistance>
|
||||
//! ```
|
||||
//!
|
||||
#![allow(dead_code)]
|
||||
|
||||
use indexmap::IndexMap;
|
||||
use more_fields::FieldsAsSlice;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use strum::{Display, EnumString};
|
||||
|
||||
/// Full data, including monster_data & balancing data
|
||||
pub struct FullData {}
|
||||
|
||||
/// A monster ready for consumption by other modules.
|
||||
///
|
||||
/// This struct is extremely export centric
|
||||
#[derive(Serialize)]
|
||||
pub struct FullMonster {
|
||||
/// Unique identifier, derived when the monster is instantiated.
|
||||
pub id: i64,
|
||||
|
||||
/// Monster’s name.
|
||||
pub name: String,
|
||||
|
||||
/// Serialized generic data directly copied from the database table.
|
||||
pub data: CreatureData,
|
||||
|
||||
/// Weird init & actions repeat
|
||||
pub init_full: Vec<MonsterRepetableInitRow>,
|
||||
|
||||
/// Collection of attacks, wrapped in a helper that exposes useful functions.
|
||||
pub attacks: CreatureListAttacks,
|
||||
|
||||
/// Merge of all attacks in a convenient-ish hashmap
|
||||
pub all_attacks: MonsterAllAttacks,
|
||||
|
||||
/// Collection of resistances, wrapped in a helper for convenient iteration.
|
||||
pub body_parts: CreatureListBodyParts,
|
||||
|
||||
/// Collection of all the rewards, wraped in a helper for iteration.
|
||||
pub rewards: CreatureListRewards,
|
||||
|
||||
/// Serialized stats directly copied from the database table.
|
||||
pub stats: CreatureStats,
|
||||
|
||||
/// Serialized balancing data
|
||||
pub balancing: CreatureBalancing,
|
||||
}
|
||||
|
||||
/// One row from the `creature` table.
|
||||
#[derive(Debug, Clone, PartialEq, 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,
|
||||
#[TEXT]
|
||||
pub denomination: Option<String>,
|
||||
/// The calamity type of the creature
|
||||
#[TEXT]
|
||||
pub calamity: String,
|
||||
/// The image describing the creature
|
||||
#[TEXT]
|
||||
pub image: String,
|
||||
/// The HSE danger level
|
||||
#[REAL]
|
||||
pub danger_level: f64,
|
||||
/// The footprints and such
|
||||
#[TEXT]
|
||||
pub traces: Option<String>,
|
||||
/// Type of habitat
|
||||
#[TEXT]
|
||||
pub habitat: Option<String>,
|
||||
/// Wether a dismorphism exists
|
||||
#[TEXT]
|
||||
pub dysmorphism: Option<String>,
|
||||
/// Monster size
|
||||
#[TEXT]
|
||||
pub size: Option<String>,
|
||||
/// Generic color describing the creature
|
||||
#[TEXT]
|
||||
pub colors: Option<String>,
|
||||
/// Default reaction to human presence
|
||||
#[TEXT]
|
||||
pub default_human_reaction: Option<String>,
|
||||
/// Known variants
|
||||
#[TEXT]
|
||||
pub variants: Option<String>,
|
||||
/// General habits
|
||||
#[TEXT]
|
||||
pub habits: Option<String>,
|
||||
/// Generic creature description
|
||||
#[TEXT]
|
||||
pub description: Option<String>,
|
||||
/// Annotations
|
||||
#[TEXT]
|
||||
pub annotations: Option<String>,
|
||||
/// Annotations GM
|
||||
#[TEXT]
|
||||
pub annotations_master: Option<String>,
|
||||
/// The battle plan of the creature
|
||||
#[TEXT]
|
||||
pub battle_plan: Option<String>,
|
||||
/// The graph of intents (image)
|
||||
#[TEXT]
|
||||
pub intent_graph: Option<String>,
|
||||
/// Wether to show it to players
|
||||
#[INTEGER]
|
||||
pub show_to_master: Option<i64>,
|
||||
/// Wether to show it to masters
|
||||
#[INTEGER]
|
||||
pub show_to_players: Option<i64>,
|
||||
}
|
||||
|
||||
/// A helper wrapper around all rewards
|
||||
#[derive(Serialize)]
|
||||
pub struct CreatureListRewards {
|
||||
pub rewards: Vec<CreatureReward>,
|
||||
}
|
||||
|
||||
/// One row from the `rewards` table.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, FieldsAsSlice)]
|
||||
pub struct CreatureReward {
|
||||
/// The id of the creature that owns the reward (FOREIGN KEY to `creature_data.id`).
|
||||
#[INTEGER]
|
||||
pub creature_id: i64,
|
||||
/// Full name of the reward.
|
||||
#[TEXT]
|
||||
pub name: String,
|
||||
/// Category of the ability
|
||||
#[TEXT]
|
||||
pub category: String,
|
||||
/// The cost of the reward
|
||||
#[TEXT]
|
||||
pub cost: Option<String>,
|
||||
/// Effect of the ability
|
||||
pub effect: String,
|
||||
}
|
||||
|
||||
/// A helper wrapper around all attacks belonging to a monster.
|
||||
///
|
||||
/// The inner vector holds individual attack rows (`MonsterSingleAttack`);
|
||||
/// helper methods on this struct (not shown here) can split or aggregate
|
||||
/// these rows into more ergonomic data structures.
|
||||
#[derive(Serialize)]
|
||||
pub struct CreatureListAttacks {
|
||||
/// All attack rows for the monster, as read from the database.
|
||||
pub attacks: Vec<MonsterSingleAttack>,
|
||||
}
|
||||
|
||||
/// A helper wrapper around all resistances belonging to a monster.
|
||||
///
|
||||
/// The inner vector contains `MonsterSingleResistance` entries; methods
|
||||
/// on this struct can provide iterators or lookup functions that are
|
||||
/// easier to consume than raw rows.
|
||||
#[derive(Serialize)]
|
||||
pub struct CreatureListBodyParts {
|
||||
/// All resistance rows for the monster, as read from the database.
|
||||
pub body_parts: Vec<CreatureBodyPart>,
|
||||
}
|
||||
|
||||
/// Represents a single attack entry as deserialized from the database.
|
||||
#[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,
|
||||
/// Prerequisite necessesary for the attack to resolve.
|
||||
#[INTEGER]
|
||||
pub prerequisites: Option<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<String>,
|
||||
/// Armor_break of the ability.
|
||||
#[INTEGER]
|
||||
pub armor_break: Option<i64>,
|
||||
/// armor_pierce of the ability.
|
||||
#[INTEGER]
|
||||
pub armor_pierce: Option<i64>,
|
||||
/// antimaterial of the ability.
|
||||
#[INTEGER]
|
||||
pub antimaterial: Option<i64>,
|
||||
/// Action‑point cost (used in systems where actions and fatigue are separate).
|
||||
#[INTEGER]
|
||||
pub cost_action: Option<String>,
|
||||
/// 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<String>,
|
||||
/// 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,
|
||||
/// The number of success for the attack
|
||||
#[TEXT]
|
||||
pub success: Option<String>,
|
||||
/// The description of the whole attack
|
||||
#[TEXT]
|
||||
pub description_all: Option<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>,
|
||||
/// Target level of damage
|
||||
pub target_damage_category: Option<String>,
|
||||
/// Target level of damage
|
||||
pub target_ab_category: Option<String>,
|
||||
/// Target stance of players
|
||||
pub target_stance: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default, FieldsAsSlice)]
|
||||
/// All different body parts and their different resists
|
||||
pub struct CreatureBodyPart {
|
||||
#[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>,
|
||||
#[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>,
|
||||
}
|
||||
|
||||
/// Convenient wrapper to allow fetching easily resists to show
|
||||
pub struct GroupedResists {
|
||||
inner: IndexMap<String, Vec<Option<String>>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, FieldsAsSlice)]
|
||||
/// All creature stats used in combat calculations.
|
||||
pub struct CreatureStats {
|
||||
#[INTEGER]
|
||||
pub creature_id: i64,
|
||||
#[TEXT]
|
||||
pub p1_init: MonsterInitString,
|
||||
#[TEXT]
|
||||
pub p2_init: MonsterInitString,
|
||||
#[TEXT]
|
||||
pub p1_actions: MonsterInitString,
|
||||
#[TEXT]
|
||||
pub p2_actions: MonsterInitString,
|
||||
#[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 physical_bonus_dmg: i64,
|
||||
#[INTEGER]
|
||||
pub elemental_bonus_dmg: Option<i64>,
|
||||
#[INTEGER]
|
||||
pub resistance_transcendentale: i64,
|
||||
#[INTEGER]
|
||||
pub size_bonus_to_hit: 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,
|
||||
}
|
||||
/// Balancing metadata for a creature.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, FieldsAsSlice)]
|
||||
pub struct CreatureBalancing {
|
||||
#[INTEGER]
|
||||
pub creature_id: i64,
|
||||
#[TEXT]
|
||||
/// (Fixed) HSE profile of the monster (see `ProfileHSE`).
|
||||
pub profile_hse: ProfileHSE,
|
||||
#[REAL]
|
||||
/// (Goal) Turns needed to reach phase 2.
|
||||
pub time_to_p2: f64,
|
||||
#[REAL]
|
||||
/// (Goal) Turns needed to kill from phase 2.
|
||||
pub time_to_kill: f64,
|
||||
#[REAL]
|
||||
/// (Goal) Turns until the monster’s armor breaks.
|
||||
pub time_to_armorbreak: f64,
|
||||
#[REAL]
|
||||
/// (GOAL) Avg. turns to kill a single target.
|
||||
pub time_to_player_kill: f64,
|
||||
#[REAL]
|
||||
/// (FIXED) Size of a single monster group (usually one).
|
||||
pub monster_groupsize: f64,
|
||||
#[REAL]
|
||||
/// (FIXED) The number of players this fight was designed for
|
||||
pub player_groupsize: f64,
|
||||
#[INTEGER]
|
||||
/// (FIXED) The average number of defence dice the creature will be using
|
||||
pub average_defensive_successes: i64,
|
||||
}
|
||||
|
||||
/// Balancing info on all the player depending on their level
|
||||
///
|
||||
/// All this info is FIXED and calculated based on average game data
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, FieldsAsSlice)]
|
||||
pub struct PlayerBalancing {
|
||||
#[INTEGER]
|
||||
/// HSE profile of the player (see `ProfileHSE`).
|
||||
pub profile_hse: ProfileHSE,
|
||||
#[INTEGER]
|
||||
/// Stance used in this datapoint.
|
||||
pub profile_stance: ProfileStance,
|
||||
#[INTEGER]
|
||||
/// Damage dealt per success.
|
||||
pub damage_per_s: f64,
|
||||
#[INTEGER]
|
||||
/// Number of offensive successes per round.
|
||||
pub successes_off: i64,
|
||||
#[INTEGER]
|
||||
/// Maximum number of offensive successes per round.
|
||||
pub max_successes_off: i64,
|
||||
#[INTEGER]
|
||||
/// Number of deffensive successes per round.
|
||||
pub successes_def: i64,
|
||||
#[INTEGER]
|
||||
/// Amount of protection (e.g., armor) the player has.
|
||||
pub protection: i64,
|
||||
#[INTEGER]
|
||||
/// Strength stat of the player.
|
||||
pub strength: i64,
|
||||
#[INTEGER]
|
||||
/// Integrity / hit‑point reserve of the player.
|
||||
pub integrity: i64,
|
||||
#[INTEGER]
|
||||
/// Current health points.
|
||||
pub health: i64,
|
||||
#[INTEGER]
|
||||
/// Current precision.
|
||||
pub precision: i64,
|
||||
#[INTEGER]
|
||||
/// Current deffensive specialty.
|
||||
pub specialty_def: i64,
|
||||
#[INTEGER]
|
||||
/// Current armor_break.
|
||||
pub armor_break: i64,
|
||||
}
|
||||
|
||||
#[derive(
|
||||
Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default, EnumString, Hash, Display,
|
||||
)]
|
||||
/// Player stance preference used for balance tables.
|
||||
pub enum ProfileStance {
|
||||
Defensive,
|
||||
Offensive,
|
||||
NoDefense,
|
||||
#[default]
|
||||
Neutral,
|
||||
}
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
/// Hunter Star Equivalent (roughly level+skill) profile used throughout the system.
|
||||
pub enum ProfileHSE {
|
||||
Lowest,
|
||||
Low,
|
||||
Mid,
|
||||
High,
|
||||
Highest,
|
||||
HighestPlus,
|
||||
}
|
||||
|
||||
// ----------- HERE BE WARCRIMES -------------
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
|
||||
#[serde(transparent)]
|
||||
/// A custom string used to avoid work
|
||||
pub struct MonsterInitString {
|
||||
inner: String,
|
||||
}
|
||||
|
||||
/// A monster init row (entire)
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
pub struct MonsterRepetableInitRow {
|
||||
pub turn: usize,
|
||||
pub p1_value: String,
|
||||
pub p1_actions: String,
|
||||
pub p2_value: String,
|
||||
pub p2_actions: String,
|
||||
}
|
||||
impl MonsterRepetableInitRow {
|
||||
pub fn vec_from(
|
||||
p1_vals: &MonsterInitString,
|
||||
p2_vals: &MonsterInitString,
|
||||
p1_acts: &MonsterInitString,
|
||||
p2_acts: &MonsterInitString,
|
||||
) -> Vec<Self> {
|
||||
let p1_vals = MonsterRepetableInitValue::from(p1_vals);
|
||||
let p2_vals = MonsterRepetableInitValue::from(p2_vals);
|
||||
let p1_acts = MonsterRepetableInitValue::from(p1_acts);
|
||||
let p2_acts = MonsterRepetableInitValue::from(p2_acts);
|
||||
p1_acts
|
||||
.inner
|
||||
.iter()
|
||||
.zip(p2_acts.inner.iter())
|
||||
.zip(p1_vals.inner.iter())
|
||||
.zip(p2_vals.inner.iter())
|
||||
.enumerate()
|
||||
.map(|(turn, (((p1_actions, p2_actions), p1_value), p2_value))| {
|
||||
MonsterRepetableInitRow {
|
||||
p1_value: p1_value.clone(),
|
||||
p1_actions: p1_actions.clone(),
|
||||
p2_value: p2_value.clone(),
|
||||
p2_actions: p2_actions.clone(),
|
||||
turn: turn + 1,
|
||||
}
|
||||
})
|
||||
.collect::<Vec<Self>>()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
/// A repeteable init string
|
||||
pub struct MonsterRepetableInitValue {
|
||||
inner: Vec<String>,
|
||||
}
|
||||
|
||||
impl From<&MonsterInitString> for MonsterRepetableInitValue {
|
||||
fn from(value: &MonsterInitString) -> Self {
|
||||
Self {
|
||||
inner: value.inner.split(',').map(|s| s.to_string()).collect(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Serialize for MonsterInitString {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: serde::Serializer,
|
||||
{
|
||||
let mut c = self.inner.split(',');
|
||||
serializer.collect_str(
|
||||
c.next()
|
||||
.unwrap_or_else(|| panic!("Trying to split {} by ','", self.inner)),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// The full list of all monster attacks
|
||||
///
|
||||
/// Split by phasing
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
pub struct MonsterAllAttacks {
|
||||
// #[serde(flatten)]
|
||||
// #[serde(with = "indexmap::map::serde_seq")]
|
||||
pub phases: IndexMap<String, Vec<MonsterFullAttack>>,
|
||||
}
|
||||
/// A single attack, grouping all sub attacks
|
||||
/// Also extract extra info to allow easier insertions
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct MonsterFullAttack {
|
||||
pub attacklist: Vec<MonsterSingleAttack>,
|
||||
pub color: String,
|
||||
pub size: usize,
|
||||
pub description_final: String,
|
||||
}
|
||||
|
|
@ -1,125 +0,0 @@
|
|||
// Workspace: more_fields
|
||||
// File: more_fields/src/lib.rs
|
||||
//! Get all the fields as a Vec<("attribute", "type")>
|
||||
//! Note that this map is implemented without self, allowing us to use it only as a generic,
|
||||
//! 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)];
|
||||
}
|
||||
|
||||
/// 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;
|
||||
|
||||
// /// Concrete array type, e.g. `[Value; 5]`.
|
||||
// type Array: AsRef<Vec<Self::Item>>;
|
||||
|
||||
fn instance_as_array(&self) -> Vec<Self::Item>;
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use crate::FieldsAsSlice;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[allow(dead_code)]
|
||||
#[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,
|
||||
}
|
||||
#[test]
|
||||
fn test_derive_impl() {
|
||||
println!("{:?}", Bob::attributes_slice());
|
||||
// assert!(
|
||||
let b_hash = vec![
|
||||
("field_ouane", "TEXT"),
|
||||
("field_2", "INTEGER"),
|
||||
("field_3", "BLOB"),
|
||||
("field_4", "NULL"),
|
||||
("field_5", "REAL"),
|
||||
("field_6", "TEXT"),
|
||||
];
|
||||
|
||||
assert_eq!(Bob::attributes_slice(), b_hash);
|
||||
}
|
||||
use crate::InstanceAsArray;
|
||||
|
||||
#[allow(dead_code)]
|
||||
#[derive(Debug, PartialEq)]
|
||||
enum Value {
|
||||
Integer(i64),
|
||||
Text(String),
|
||||
}
|
||||
|
||||
impl From<i32> for Value {
|
||||
fn from(v: i32) -> Self {
|
||||
Value::Integer(v as i64)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<String> 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());
|
||||
// }
|
||||
}
|
||||
|
|
@ -1,184 +0,0 @@
|
|||
// Workspace: more_fields_macro
|
||||
// File: more_fields_macro/src/lib.rs
|
||||
//! A very simple proc macro in chage of giving a field slice over ("name","sql_type")
|
||||
//! This macro is a fork of the excellent work of : <https://crates.io/crates/struct_iterable>
|
||||
//!
|
||||
//! Other ressources include:
|
||||
//! - <https://github.com/rust-lang/reference/blob/master/src/procedural-macros.md#attribute-macros>
|
||||
//! - <https://docs.rs/syn/latest/syn/struct.Attribute.html>
|
||||
//! - <https://docs.rs/syn/latest/syn/struct.Attribute.html#parsing-from-tokens-to-attribute>
|
||||
//! - <https://docs.rs/syn/latest/syn/struct.Ident.html>
|
||||
//!
|
||||
// use proc_macro::TokenStream;
|
||||
// use quote::quote;
|
||||
// use syn::{Data, DeriveInput, Fields, parse_macro_input};
|
||||
extern crate proc_macro;
|
||||
|
||||
use proc_macro::TokenStream;
|
||||
use quote::quote;
|
||||
use syn::{Data, DeriveInput, Fields, parse_macro_input};
|
||||
|
||||
/// The macro can now be used on structs that have a mix of the
|
||||
/// following field‑level attributes:
|
||||
/// * INTEGER, NULL, REAL, TEXT, BLOB → SQLite column type
|
||||
/// * SKIP → omit this field from the slice
|
||||
///
|
||||
/// Example usage
|
||||
///
|
||||
/// ```ignore
|
||||
/// #[derive(FieldsAsSlice)]
|
||||
/// struct Person {
|
||||
/// #[INTEGER] id: i32,
|
||||
/// #[TEXT] name: String,
|
||||
/// #[SKIP] secret_code: String, // will not appear in `attributes_slice()`
|
||||
/// }
|
||||
/// ```
|
||||
#[proc_macro_derive(FieldsAsSlice, attributes(INTEGER, NULL, REAL, TEXT, BLOB, SKIP))]
|
||||
pub fn derive_iterable(input: TokenStream) -> TokenStream {
|
||||
let input = parse_macro_input!(input as DeriveInput);
|
||||
let struct_name = input.ident;
|
||||
|
||||
// collect named fields only
|
||||
let fields = match input.data {
|
||||
Data::Struct(data_struct) => match data_struct.fields {
|
||||
Fields::Named(f_named) => f_named.named,
|
||||
_ => panic!("Only structs with named fields are supported"),
|
||||
},
|
||||
_ => panic!("Only structs are supported"),
|
||||
};
|
||||
|
||||
// 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| {
|
||||
// Skip fields marked with #[SKIP]
|
||||
if field.attrs.iter().any(|a| a.path().is_ident("SKIP")) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let mut sqlite_type = "TEXT".to_string();
|
||||
let mut exported_name = field
|
||||
.ident
|
||||
.as_ref()
|
||||
.expect("Expected named field")
|
||||
.to_string();
|
||||
|
||||
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",
|
||||
struct_name.to_string().to_ascii_uppercase()
|
||||
);
|
||||
let const_name = syn::Ident::new(&const_name_str, proc_macro::Span::call_site().into());
|
||||
|
||||
// Finally emit the implementation
|
||||
let expanded = quote! {
|
||||
/// Generated slice containing `(field_name, sqlite_type)` pairs.
|
||||
///
|
||||
/// The slice is `static` so it can be used in zero‑alloc scenarios.
|
||||
const #const_name: &[(&str, &str)] = &[
|
||||
#(#fields_iter),*
|
||||
];
|
||||
|
||||
impl FieldsAsSlice for #struct_name {
|
||||
fn attributes_slice<'a>() -> &'static [(&'static str, &'static str)] {
|
||||
&#const_name
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
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<Type> = 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)
|
||||
}
|
||||
|
|
@ -1,23 +0,0 @@
|
|||
# cargo-features = ["codegen-backend"]
|
||||
[package]
|
||||
name = "ravenous-tools"
|
||||
version.workspace = true
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
tablegen = {workspace = true}
|
||||
graphs = {workspace = true}
|
||||
cli_parser = {workspace = true}
|
||||
stats = {workspace = true}
|
||||
make = {workspace = true}
|
||||
fast_class = {workspace = true}
|
||||
anyhow = {workspace = true}
|
||||
toml = {workspace = true}
|
||||
clap = {workspace = true}
|
||||
tokio = {workspace = true}
|
||||
formatter = {workspace = true}
|
||||
weaponry = {workspace = true}
|
||||
monsters = {workspace = true}
|
||||
|
||||
[package.metadata.cargo-machete]
|
||||
ignored = ["tokio"]
|
||||
|
|
@ -1,12 +0,0 @@
|
|||
[package]
|
||||
name = "stats"
|
||||
version.workspace = true
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
config = {workspace = true}
|
||||
cli_parser = {workspace = true}
|
||||
anyhow = {workspace = true}
|
||||
csv = {workspace = true}
|
||||
debug_print = "1.0.0"
|
||||
serde = {workspace = true}
|
||||
|
|
@ -1,18 +0,0 @@
|
|||
[package]
|
||||
name = "tablegen"
|
||||
version.workspace = true
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
cli_parser = {workspace = true}
|
||||
config = {workspace = true}
|
||||
anyhow = {workspace = true}
|
||||
csv = {workspace = true}
|
||||
dynfmt = {workspace = true}
|
||||
glob = {workspace = true}
|
||||
regex = {workspace = true}
|
||||
regex_static = {workspace = true}
|
||||
serde = {workspace = true}
|
||||
clap = {workspace = true}
|
||||
phf = { version = "0.13.1", features = ["macros"] }
|
||||
|
||||
|
|
@ -1,8 +0,0 @@
|
|||
[last_run_clean]
|
||||
run_status = "Success"
|
||||
lines_parsed = 57
|
||||
coverage = 60.03
|
||||
|
||||
[last_run_clean.run_duration]
|
||||
secs = 19
|
||||
nanos = 961545465
|
||||
|
|
@ -1,41 +0,0 @@
|
|||
[package]
|
||||
name = "weaponry"
|
||||
version.workspace = true
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
config = {workspace = true}
|
||||
cli_parser = {workspace = true}
|
||||
more_fields = {workspace = true}
|
||||
regex = {workspace = true}
|
||||
csv = {workspace = true}
|
||||
serde = {workspace = true}
|
||||
comfy-table = "7.2.2"
|
||||
probability = {workspace = true}
|
||||
rusqlite = {workspace = true}
|
||||
serde_rusqlite = {workspace = true}
|
||||
serde_json = {workspace = true}
|
||||
handlebars = {workspace = true}
|
||||
strum = {workspace = true}
|
||||
thiserror = "2.0.18"
|
||||
charming = { version = "0.4.0", features = [] }
|
||||
|
||||
[dev-dependencies]
|
||||
regex = {workspace = true}
|
||||
pretty_assertions = {workspace = true}
|
||||
clap = {workspace = true}
|
||||
|
||||
fastrand = "2.4.1"
|
||||
criterion = { version = "0.8" }
|
||||
logos = "^0.16"
|
||||
rayon = "1.12.0"
|
||||
|
||||
[[bench]]
|
||||
name = "iter_creation"
|
||||
harness = false
|
||||
|
||||
[features]
|
||||
dev-analysis = [] # gate for the feature flag
|
||||
|
||||
# [lints.rust]
|
||||
# unexpected_cfgs = { level = "warn", check-cfg = ['cfg(tarpaulin_include)'] }
|
||||
|
|
@ -1,156 +0,0 @@
|
|||
// Workspace: weaponry
|
||||
// File: weaponry/src/analysis.rs
|
||||
//! The one stop shop for analysis
|
||||
|
||||
use std::{cmp::Ordering, path::Path};
|
||||
|
||||
use cli_parser::Config;
|
||||
use config::analysis::AnalysisConfig;
|
||||
|
||||
use crate::{
|
||||
error::FatalEquipementError,
|
||||
interfaces::{Reportable, Scenario, ToAnalysis, ToCSV},
|
||||
weaponry_structs::{
|
||||
CrossRecipeScenario, RefinedEquipement, RefinedEquipementList,
|
||||
equipement_scenario::ConfigEquipementScenario,
|
||||
},
|
||||
};
|
||||
|
||||
/// Launch the analysis of the selected data and export it to html for human processing
|
||||
pub fn launch_analysis(args: &AnalysisConfig, config: &Config) -> Result<(), FatalEquipementError> {
|
||||
match args.target {
|
||||
config::analysis::AnalysisTarget::Weapon => create_graphs(
|
||||
args,
|
||||
config,
|
||||
Box::new(|e: &RefinedEquipement| {
|
||||
e.inner.category_base.as_ref().is_some_and(|v| {
|
||||
!matches!(v, crate::weaponry_structs::WeaponBaseShape::Shields)
|
||||
&& !matches!(v, crate::weaponry_structs::WeaponBaseShape::Armors)
|
||||
})
|
||||
}),
|
||||
),
|
||||
config::analysis::AnalysisTarget::Armors => create_graphs(
|
||||
args,
|
||||
config,
|
||||
Box::new(|e: &RefinedEquipement| {
|
||||
e.inner
|
||||
.category_base
|
||||
.as_ref()
|
||||
.is_some_and(|v| matches!(v, crate::weaponry_structs::WeaponBaseShape::Armors))
|
||||
}),
|
||||
),
|
||||
config::analysis::AnalysisTarget::Shields => create_graphs(
|
||||
args,
|
||||
config,
|
||||
Box::new(|e: &RefinedEquipement| {
|
||||
e.inner
|
||||
.category_base
|
||||
.as_ref()
|
||||
.is_some_and(|v| matches!(v, crate::weaponry_structs::WeaponBaseShape::Shields))
|
||||
}),
|
||||
),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Create all graphs with
|
||||
fn create_graphs(args: &AnalysisConfig, config: &Config, filter: DynamicFilterType) {
|
||||
let save_path = args.path.clone().unwrap_or("data/first_data".into());
|
||||
let scenarios = CrossRecipeScenario::new_with_config(ConfigEquipementScenario {
|
||||
table_name: "Equipements".into(),
|
||||
db_path: config.data_generation.database.clone(),
|
||||
shape: (!args.no_shapes).then_some(()),
|
||||
materials: args.materials,
|
||||
nature: (!args.no_natures).then_some(()),
|
||||
finishing: args.finishing.then_some(()),
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
let mut refined_list = scenarios
|
||||
.generate_refined_recipes()
|
||||
.unwrap()
|
||||
// .inner_filter(|e| (e.advanced.max_damage_per_attack > 0.))
|
||||
.inner_filter(filter);
|
||||
|
||||
match cmd_to_filter(&args.sort) {
|
||||
Ok(cmd) => {
|
||||
refined_list.inner_sort(cmd);
|
||||
}
|
||||
Err(FatalEquipementError::CLIParseError(a)) => {
|
||||
println!("Argument incorrect '{a}'. Ignoring the sort.")
|
||||
}
|
||||
Err(e) => panic!("{e}"),
|
||||
}
|
||||
refined_list.write_html(&save_path).unwrap();
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
/// Export as a csv a refine equipement list
|
||||
///
|
||||
/// Rarely used and likely on it's way to deprecation
|
||||
fn export_as_csv(refined_list: &RefinedEquipementList, save_path: &str) {
|
||||
println!("{}", refined_list.get_report(Some("Refined List")));
|
||||
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)]
|
||||
type DynamicSortType = Box<dyn FnMut(&RefinedEquipement, &RefinedEquipement) -> Ordering>;
|
||||
|
||||
/// A dynamic filter type
|
||||
type DynamicFilterType = Box<dyn FnMut(&RefinedEquipement) -> bool>;
|
||||
|
||||
/// Create a filter from a user typed filter
|
||||
///
|
||||
/// This informal implementation function as a mini language,
|
||||
/// without any form of formalism, consistency or fixed API
|
||||
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 {
|
||||
(false, og_entry)
|
||||
};
|
||||
|
||||
macro_rules! return_if_starts_with {
|
||||
($iden:ident) => {
|
||||
if stringify!($iden).starts_with(entry) {
|
||||
return match category {
|
||||
true => Ok(Box::new(crate::sort_by_cat_then!($iden))),
|
||||
false => Ok(Box::new(crate::sort_by!($iden))),
|
||||
};
|
||||
};
|
||||
};
|
||||
}
|
||||
return_if_starts_with!(max_damage_per_attack);
|
||||
return_if_starts_with!(armor_break_per_attack);
|
||||
return_if_starts_with!(expected_armor_break_per_attack);
|
||||
return_if_starts_with!(avg_damage_2a_safe);
|
||||
return_if_starts_with!(avg_damage_2a_huge_hit);
|
||||
return_if_starts_with!(speed);
|
||||
return_if_starts_with!(scenario_damage);
|
||||
return_if_starts_with!(defensive);
|
||||
return_if_starts_with!(earlygame_sustained_damage_per_turn);
|
||||
return_if_starts_with!(midgame_sustained_damage_per_turn);
|
||||
return_if_starts_with!(endgame_sustained_damage_per_turn);
|
||||
return_if_starts_with!(variance);
|
||||
return_if_starts_with!(variance_pct);
|
||||
Err(FatalEquipementError::CLIParseError(og_entry.to_string()))
|
||||
}
|
||||
|
|
@ -1,53 +0,0 @@
|
|||
// 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(()),
|
||||
})?;
|
||||
|
||||
// let filter = Box::new(|_: &RefinedEquipement| true);
|
||||
let refined_list = scenarios.generate_refined_recipes()?;
|
||||
// .inner_filter(filter);
|
||||
|
||||
let tex = refined_list.to_tex(config)?;
|
||||
|
||||
let name = format!("{}/gen-forge-table.tex", args.export);
|
||||
println!("Writing to file {name}");
|
||||
let mut f = fs::File::create(name)?;
|
||||
writeln!(f, "{}", tex)?;
|
||||
Ok(())
|
||||
}
|
||||
|
|
@ -1,87 +0,0 @@
|
|||
// Workspace: weaponry
|
||||
// File: weaponry/src/strategy.rs
|
||||
//! All different algorythms and strategies to create a weapon
|
||||
//!
|
||||
//! These strategies can lock a parameter to allow a more fine tuned balancing
|
||||
//! or balancing specifically one parameter (balancing materials, balencing finishes etc..)
|
||||
//! These strategies must take into account the level of the fighter (hence his precision) and of the craftsman (hence a difficulty diminution)
|
||||
//!
|
||||
#![allow(dead_code)]
|
||||
|
||||
/// Generation strategy, how to generate all the data, instead of a full permutation
|
||||
pub enum EquipementStrategy {
|
||||
/// Full permutation, generate all possible outcomes
|
||||
GenerateAll,
|
||||
/// Generate all the named equipements
|
||||
GenerateNamed,
|
||||
/// Do not add finishing touches
|
||||
NoFinishes,
|
||||
}
|
||||
|
||||
/// Which material to select
|
||||
pub enum MaterialsStrategy {
|
||||
/// Add all materials to the mix
|
||||
AllMaterials,
|
||||
/// Add only tier one material
|
||||
OnlyTier1,
|
||||
/// Add only easy materials
|
||||
OnlyEasy,
|
||||
/// Add only cheap materials
|
||||
OnlyCheap,
|
||||
/// Add only one material
|
||||
OnlyOne,
|
||||
}
|
||||
|
||||
/// Filter to apply after the generation
|
||||
pub enum EquipementFilter {
|
||||
/// Don't filter anything
|
||||
All,
|
||||
/// Filter all outliers
|
||||
Outiliers,
|
||||
/// Filter in all the named
|
||||
Named,
|
||||
}
|
||||
|
||||
// /// D
|
||||
// struct Gen<T>
|
||||
// where
|
||||
// T: Send,
|
||||
// {
|
||||
// /// E
|
||||
// elem: Vec<T>,
|
||||
// }
|
||||
|
||||
// impl<T: Send> ParallelIterator for Gen<T> {
|
||||
// type Item = T;
|
||||
|
||||
// fn drive_unindexed<C>(self, consumer: C) -> C::Result
|
||||
// where
|
||||
// C: rayon::iter::plumbing::UnindexedConsumer<Self::Item>,
|
||||
// {
|
||||
// let _ = consumer;
|
||||
// todo!()
|
||||
// }
|
||||
// }
|
||||
// /// Default full generation strategy
|
||||
// pub fn default_generation() -> impl ParallelIterator {
|
||||
// Gen::<u8> { elem: Vec::new() }
|
||||
// }
|
||||
/// Default full generation strategy
|
||||
pub fn default_generation<T: Copy>(a: Vec<T>, b: Vec<T>) -> Vec<(T, T)> {
|
||||
a.iter()
|
||||
.flat_map(|e| b.iter().map(|f| (*e, *f)).collect::<Vec<(T, T)>>())
|
||||
// .collect::<Vec<Vec<(T, T)>>>()
|
||||
// .flatten()
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn test_creator() {
|
||||
let t = default_generation(vec![1, 2, 3], vec![5, 6, 7]);
|
||||
println!("{:?}", t);
|
||||
// panic!()
|
||||
}
|
||||
}
|
||||
|
|
@ -1,437 +0,0 @@
|
|||
// Workspace: weaponry
|
||||
// File: weaponry/src/weaponry_structs/equipement_impl_basics.rs
|
||||
// TODO: At some point a trait might want to be used to use these into instead of calling it directly
|
||||
// : Doing so would ensure all prerequists are met
|
||||
// : Another way of doing so might be to instead use Into<Combinable> instead
|
||||
// : Another way would be to add a filter field that would allow or not the combinaison and abstract all
|
||||
// logic that would be into doing multi traits things
|
||||
//! Implementations to transform all Specialized equipement into a generic Equipement
|
||||
//! A specific implementation could be preferable, but this simplicity might allow for easier developpement
|
||||
|
||||
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::{
|
||||
fmt::{Debug, Display},
|
||||
rc::Rc,
|
||||
};
|
||||
|
||||
use super::{
|
||||
Equipement, InitialEquipementList,
|
||||
equipement_advanced_repr::RefinedEquipementList,
|
||||
equipement_structs::{
|
||||
EqFinishing, EqMaterial, EqNature, EqShape, filter_id_unique_and_right_category,
|
||||
},
|
||||
};
|
||||
|
||||
impl From<EqShape> for Equipement {
|
||||
fn from(val: EqShape) -> Self {
|
||||
Self {
|
||||
stats: val.stats,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<EqMaterial> for Equipement {
|
||||
fn from(val: EqMaterial) -> Self {
|
||||
Self {
|
||||
stats: val.stats,
|
||||
filter_function: FilterFunction::new(filter_id_unique_and_right_category()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<EqNature> for Equipement {
|
||||
fn from(val: EqNature) -> Self {
|
||||
Self {
|
||||
stats: val.stats,
|
||||
// Checks that the nature is compatible with the previous iteration
|
||||
filter_function: FilterFunction::new(filter_id_unique_and_right_category()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<EqFinishing> for Equipement {
|
||||
fn from(val: EqFinishing) -> Self {
|
||||
Self {
|
||||
stats: val.stats,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for Equipement {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "{}", self.stats)
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for InnerEquipementStats {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
let mut table = Table::new();
|
||||
table.apply_modifier(UTF8_ROUND_CORNERS);
|
||||
table.add_row(vec![format!(
|
||||
"Ids: {}, Names:{}",
|
||||
self.id
|
||||
.iter()
|
||||
.fold(String::new(), |res, new| format!("{res} {new}")),
|
||||
self.name.join(" & ")
|
||||
)]);
|
||||
table.add_row(vec![format!(
|
||||
"Rarity: {}, Cost {}, Difficulty: {}, Tier: {} [{}+{}]",
|
||||
self.rarity,
|
||||
self.cost,
|
||||
self.difficulty,
|
||||
self.tier,
|
||||
self.category_base
|
||||
.map_or_else(|| "ø".to_string(), |v| v.to_string()),
|
||||
self.category_size
|
||||
.clone()
|
||||
.map_or_else(|| "ø".to_string(), |v| v.to_string())
|
||||
)]);
|
||||
table.add_row_if(
|
||||
|_, _| self.damage > 0,
|
||||
vec![format!(
|
||||
"Damage: {}/+{} P:{}, AB:{} AM:{} A:{} [{}]",
|
||||
self.damage,
|
||||
self.p_damage,
|
||||
self.precision,
|
||||
self.armor_break,
|
||||
self.antimaterial,
|
||||
self.action_cost,
|
||||
self.clone()
|
||||
.damage_type
|
||||
.map_or_else(|| "ø".to_string(), |damage| damage.to_string())
|
||||
)],
|
||||
);
|
||||
table.add_row_if(
|
||||
|_, _| self.protection > 0,
|
||||
vec![format!("Prot:{} Int:{}", self.protection, self.integrity)],
|
||||
);
|
||||
table.add_row(vec![format!(
|
||||
"T1/T2 {:?}/{:?} Dodge:{} Parry:{} Speed:{} Stealth:{} Agility: {}",
|
||||
self.torque_one_handed,
|
||||
self.torque_two_handed,
|
||||
self.dodge,
|
||||
self.parry,
|
||||
self.speed,
|
||||
self.stealth,
|
||||
self.agility_bonus,
|
||||
)]);
|
||||
table.add_row_if(
|
||||
|_, _| (self.range > 0) | (self.armor_pierce > 0),
|
||||
vec![format!(
|
||||
"Rg:{}, AP:{}, Rel:{}",
|
||||
self.range,
|
||||
self.armor_pierce,
|
||||
self.reload_cost
|
||||
.map_or_else(|| "ø".to_string(), |v| format!("{v}"))
|
||||
)],
|
||||
);
|
||||
table.add_row_if(
|
||||
|_, _| !self.special.is_empty(),
|
||||
vec![
|
||||
self.special
|
||||
.iter()
|
||||
// .intersperse(&",".to_string())
|
||||
.fold(String::new(), |res, new| format!("{}; {}", res, new)),
|
||||
],
|
||||
);
|
||||
write!(f, "{table}")
|
||||
}
|
||||
}
|
||||
|
||||
// impl Display for InitialEquipementList {
|
||||
// fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
// for v in self.ref_inner() {
|
||||
// write!(f, "{v}")?;
|
||||
// }
|
||||
// Ok(())
|
||||
// }
|
||||
// }
|
||||
|
||||
impl Reportable for InitialEquipementList {
|
||||
fn get_report(&self, title: Option<&str>) -> String {
|
||||
let mut table = Table::new();
|
||||
table.apply_modifier(UTF8_ROUND_CORNERS);
|
||||
match title {
|
||||
Some(t) => table.add_row(vec![format!("[IEL] {t}")]),
|
||||
None => table.add_row(vec![format!("Initial Equipement List")]),
|
||||
};
|
||||
table.add_row(vec![format!("Rows: {}", self.inner.len())]);
|
||||
table.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
impl Reportable for RefinedEquipementList {
|
||||
fn get_report(&self, title: Option<&str>) -> String {
|
||||
let mut table = Table::new();
|
||||
table.apply_modifier(UTF8_ROUND_CORNERS);
|
||||
match title {
|
||||
Some(t) => table.add_row(vec![format!("[REL] {t}")]),
|
||||
None => table.add_row(vec![format!("Refined Equipement List")]),
|
||||
};
|
||||
table.add_row(vec![format!("Rows: {}", self.len())]);
|
||||
table.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Debug for FilterFunction<T> {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "Filter:{}", std::any::type_name::<Self>())
|
||||
}
|
||||
}
|
||||
impl<T> Default for FilterFunction<T> {
|
||||
fn default() -> Self {
|
||||
FilterFunction(Box::new(Rc::new(|_, _| true)))
|
||||
}
|
||||
}
|
||||
impl<T> PartialEq for FilterFunction<T> {
|
||||
#[cfg_attr(feature = "dev-analysis", coverage(off))] // INCORRECT: Error with line report
|
||||
fn eq(&self, _other: &Self) -> bool {
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
/// Add a new vector to a clone of a inner field
|
||||
macro_rules! add_to_vec {
|
||||
($self: expr, $rhs: expr) => {{
|
||||
let mut new = $self.clone();
|
||||
new.append(&mut $rhs.clone());
|
||||
new
|
||||
}};
|
||||
}
|
||||
|
||||
/// Adds either of the vectors or merge them
|
||||
macro_rules! add_two_options {
|
||||
($self: expr, $rhs: expr) => {{
|
||||
match ($self.as_ref(), $rhs.as_ref()) {
|
||||
(None, None) => None,
|
||||
(None, Some(a)) => Some(a.clone()),
|
||||
(Some(a), None) => Some(a.clone()),
|
||||
(Some(a), Some(b)) => Some(a.clone() + b.clone()),
|
||||
}
|
||||
}};
|
||||
}
|
||||
|
||||
/// Clones the first option that has some data
|
||||
macro_rules! first_correct_option {
|
||||
($self:expr, $rhs:expr) => {
|
||||
match ($self.as_ref(), $rhs.as_ref()) {
|
||||
(Some(a), _) => Some(a.clone()),
|
||||
(_, Some(b)) => Some(b.clone()),
|
||||
_ => None,
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/// 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,
|
||||
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,
|
||||
tier: self.tier + rhs.tier,
|
||||
damage: self.damage + rhs.damage,
|
||||
p_damage: self.p_damage + rhs.p_damage,
|
||||
precision: self.precision + rhs.precision,
|
||||
rmax: self.rmax + rhs.rmax,
|
||||
armor_break: self.armor_break + rhs.armor_break,
|
||||
armor_pierce: {
|
||||
if self.armor_pierce > 0
|
||||
|| matches!(self.category_base, Some(WeaponBaseShape::Ranged))
|
||||
{
|
||||
self.armor_pierce + rhs.armor_pierce
|
||||
} else {
|
||||
0
|
||||
}
|
||||
},
|
||||
antimaterial: self.antimaterial + rhs.antimaterial,
|
||||
damage_type: add_two_options!(self.damage_type, rhs.damage_type),
|
||||
protection: self.protection + rhs.protection,
|
||||
integrity: self.integrity + rhs.integrity,
|
||||
torque_two_handed: add_two_options!(self.torque_two_handed, rhs.torque_two_handed),
|
||||
torque_one_handed: add_two_options!(self.torque_one_handed, rhs.torque_one_handed),
|
||||
dodge: self.dodge + rhs.dodge,
|
||||
parry: self.parry + rhs.parry,
|
||||
speed: self.speed + rhs.speed,
|
||||
stealth: self.stealth + rhs.stealth,
|
||||
special: self.special.clone() + rhs.special.clone(), // Can be further optimized
|
||||
action_cost: self.action_cost + rhs.action_cost,
|
||||
reload_cost: self.reload_cost.or(rhs.reload_cost),
|
||||
range: self.range + rhs.range,
|
||||
agility_bonus: self.agility_bonus + rhs.agility_bonus,
|
||||
category_base: first_correct_option!(self.category_base, rhs.category_base),
|
||||
category_size: first_correct_option!(self.category_size, rhs.category_size),
|
||||
target_category: first_correct_option!(self.target_category, rhs.target_category),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::ops::Add for SpecialField {
|
||||
type Output = Self;
|
||||
|
||||
fn add(self, rhs: Self) -> Self::Output {
|
||||
let mut c = self.clone();
|
||||
c.append(&mut rhs.clone());
|
||||
c
|
||||
}
|
||||
}
|
||||
|
||||
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::{
|
||||
interfaces::{FilterFunction, RecipeCollection, Reportable},
|
||||
weaponry_structs::{
|
||||
Equipement, InitialEquipementList,
|
||||
equipement_advanced_repr::RefinedEquipementList,
|
||||
equipement_structs::{DatabaseEquipementStats, InnerEquipementStats},
|
||||
},
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn test_filter_weapons() {
|
||||
let _ = format!("{:?}", FilterFunction::<Equipement>::default());
|
||||
let r = FilterFunction::<Equipement>::new(&|_, _| false) == FilterFunction::default();
|
||||
assert!(r);
|
||||
}
|
||||
#[allow(dead_code)]
|
||||
/// A manually implemented hashmap of all values
|
||||
#[doc(hidden)]
|
||||
macro_rules! r {
|
||||
() => {
|
||||
fastrand::i8(1..20)
|
||||
};
|
||||
}
|
||||
impl InnerEquipementStats {
|
||||
/// Testing function to fuzz data
|
||||
pub fn random_new() -> Self {
|
||||
Self {
|
||||
id: vec![r!() as u8],
|
||||
range: (r!() - 10) as i16,
|
||||
damage: r!() - 10,
|
||||
p_damage: r!() - 10,
|
||||
protection: r!() - 10,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
impl DatabaseEquipementStats {
|
||||
/// Testing function to fuzz data
|
||||
pub fn random_new() -> Self {
|
||||
Self {
|
||||
id: r!() as u8,
|
||||
range: r!() - 19,
|
||||
damage: r!() - 10,
|
||||
p_damage: r!() - 10,
|
||||
protection: r!() - 10,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn test_format() {
|
||||
let equi = Equipement {
|
||||
stats: InnerEquipementStats::random_new(),
|
||||
..Default::default()
|
||||
};
|
||||
print!("{}", equi);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_report() {
|
||||
let eqlist = InitialEquipementList::from_vectored(vec![Equipement::default(); 10]);
|
||||
let feqlist: RefinedEquipementList = eqlist.clone().into();
|
||||
|
||||
println!("{}", feqlist.get_report(None));
|
||||
println!("{}", eqlist.get_report(None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_macros() {
|
||||
assert_eq!(first_correct_option!(None::<i8>, None::<i8>), None);
|
||||
assert_eq!(first_correct_option!(Some(3), None::<i8>), Some(3));
|
||||
assert_eq!(first_correct_option!(None::<i8>, Some(4)), Some(4));
|
||||
assert_eq!(first_correct_option!(Some(1), Some(3)), Some(1));
|
||||
|
||||
assert_eq!(add_two_options!(Some(1), Some(3)), Some(4));
|
||||
assert_eq!(add_two_options!(Some(3), None::<i8>), Some(3));
|
||||
assert_eq!(add_two_options!(None::<i8>, Some(4)), Some(4));
|
||||
|
||||
let a = vec![1, 2];
|
||||
let b = vec![3];
|
||||
|
||||
assert_eq!(add_to_vec!(a, b), vec![1, 2, 3]);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,18 +0,0 @@
|
|||
# Workflow
|
||||
A B C
|
||||
Database -> <Structs> -> <Weapons> -> Balancing data
|
||||
-> Exported data
|
||||
|
||||
# Description
|
||||
- A : Use structs defines in weaponry_structs
|
||||
: impl From<ForeignType> for all weapon parts
|
||||
- B : Every part can be converted to a weapon(ish)
|
||||
: Use the correct solver to add all parts
|
||||
- C1 : Use the traits to generate the tex data
|
||||
|
||||
|
||||
# Strategy
|
||||
Since the structs will become more than just weapons but will become craft afterwards, polymorphism is the key
|
||||
|
||||
The creation algorithm will pick a Strategy depending on the user's choice and build a final weapon depending on it
|
||||
The creation will implement an iterator to go with itertools / rayon ?
|
||||
|
|
@ -0,0 +1,14 @@
|
|||
[package]
|
||||
name = "graphs"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
config = {path = "../config"}
|
||||
cli_parser = {path = "../cli_parser"}
|
||||
anyhow = "1.0.95"
|
||||
charts-rs = "0.3.19"
|
||||
glob = "0.3.2"
|
||||
serde = { version = "1.0.217", features = ["derive", "alloc"] }
|
||||
csv = "1.3.1"
|
||||
ron = "0.8.1"
|
||||
|
|
@ -4,18 +4,15 @@
|
|||
//!
|
||||
//! - [`make_graphs`]: The main action dispatcher for graph generation and removal.
|
||||
|
||||
use charts_rs::{
|
||||
Box, Color, RadarChart, RadarIndicator, Series, get_or_try_init_fonts, svg_to_png_with_size,
|
||||
};
|
||||
use charts_rs::{Box, Color, RadarChart, RadarIndicator, Series, get_or_try_init_fonts};
|
||||
use cli_parser::Config;
|
||||
use config::graph::{FinalClassRadar, GraphConfig, GraphTargetType, LoadedClassRadar, RawRow};
|
||||
use config::graph::{GraphConfig, GraphTargetType};
|
||||
use glob::glob;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{
|
||||
fs::File,
|
||||
io::{Read, Write},
|
||||
iter,
|
||||
path::{Path, PathBuf},
|
||||
process::Command,
|
||||
};
|
||||
|
||||
|
|
@ -25,7 +22,6 @@ use anyhow::{Context, Result};
|
|||
pub fn make_graphs(args: &GraphConfig, _config: &Config) -> Result<()> {
|
||||
// Choose action to do
|
||||
match args.target {
|
||||
GraphTargetType::Load => load_graph(args),
|
||||
GraphTargetType::Generate => gen_graph(args),
|
||||
GraphTargetType::Remove => del_graphs(args),
|
||||
GraphTargetType::Init => init_graph_config(args),
|
||||
|
|
@ -48,7 +44,7 @@ fn init_graph_config(_args: &GraphConfig) -> Result<()> {
|
|||
/// Load the config if given of the default config if none
|
||||
fn load_graph_config(args: &GraphConfig) -> Result<MiniTheme> {
|
||||
if let Some(c) = &args.config {
|
||||
println!("[INFO] Reading config {}", c);
|
||||
println!("[INFO] Reading config {}", &c);
|
||||
let mut f = File::open(c).context("Opening config")?;
|
||||
let mut buf = String::new();
|
||||
f.read_to_string(&mut buf).context("Reading the config")?;
|
||||
|
|
@ -84,17 +80,10 @@ fn del_graphs(args: &GraphConfig) -> Result<()> {
|
|||
Ok(())
|
||||
}
|
||||
|
||||
/// Load graph data from classes
|
||||
fn load_graph(args: &GraphConfig) -> Result<()> {
|
||||
let _ = args;
|
||||
// load_categories_from_tsv("./test.csv")?;
|
||||
generate_csv()?;
|
||||
Ok(())
|
||||
}
|
||||
///Generate the graph and save it
|
||||
/// Generate the graph and save it
|
||||
fn gen_graph(args: &GraphConfig) -> Result<()> {
|
||||
// Import CSV
|
||||
let data = include_bytes!("../../../data/lmroman8-regular.ttf") as &[u8];
|
||||
let data = include_bytes!("../../data/lmroman8-regular.ttf") as &[u8];
|
||||
get_or_try_init_fonts(Some(vec![data])).unwrap();
|
||||
|
||||
let csv = import_csv(args)?;
|
||||
|
|
@ -104,21 +93,30 @@ fn gen_graph(args: &GraphConfig) -> Result<()> {
|
|||
let cfg = load_graph_config(args)?;
|
||||
|
||||
for graph in csv.values {
|
||||
let path_svg = format!("{}/{}.svg", args.destination, graph.name);
|
||||
let path_png = format!("{}/{}.png", args.destination, graph.name);
|
||||
// println!("{:?} {:#?}", maxv, graph);
|
||||
// let path = format!("{}/{}.png", args.destination, &graph.name);
|
||||
let path_svg = format!("{}/{}.svg", args.destination, &graph.name);
|
||||
let path_png = format!("{}/{}.png", args.destination, &graph.name);
|
||||
println!("[INFO] Processing {}", path_svg);
|
||||
|
||||
let mut f = File::create(&path_svg)?;
|
||||
let mut r = RadarChart::new([graph].to_vec(), maxv.to_vec());
|
||||
cfg.apply_to(&mut r);
|
||||
|
||||
println!("Writing to {}", path_svg);
|
||||
let context = r.svg().context("Converting to SVG")?;
|
||||
f.write_all(context.as_bytes())?;
|
||||
f.write_all(r.svg().context("Converting to SVG")?.as_bytes())?;
|
||||
|
||||
let png = svg_to_png_with_size(&context, Some(860), Some(560)).context("Writing png")?;
|
||||
let mut f = File::create(path_png)?;
|
||||
f.write_all(&png).context("Writing png")?;
|
||||
let mut cmd = Command::new("convert");
|
||||
cmd.arg("--size")
|
||||
.arg("800x600")
|
||||
.arg(&path_svg)
|
||||
.arg(path_png);
|
||||
println!("[INFO] Using convert cli to convert to png");
|
||||
if let Err(e) = cmd.output() {
|
||||
println!(
|
||||
"[ERRR] An error has occured when converting the file {} to png \n {:#?}",
|
||||
path_svg, e
|
||||
)
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
|
@ -133,77 +131,6 @@ fn import_csv(args: &GraphConfig) -> Result<GraphValues> {
|
|||
cleanup_csv(rdr)
|
||||
}
|
||||
|
||||
/// Generate the csv from all the classes
|
||||
fn generate_csv() -> Result<()> {
|
||||
// Acquire the data from all classes
|
||||
let list_class = list_dir("Tables/??? - *.tsv");
|
||||
let mut final_class_list = Vec::with_capacity(list_class.len() + 1);
|
||||
// Very ugly space reservation for the last operation, need to check if no way of skipping an element is possible
|
||||
final_class_list.push(FinalClassRadar::default());
|
||||
|
||||
for single_class in list_class {
|
||||
let class_name = &single_class
|
||||
.file_name()
|
||||
.context("Extracting old name")?
|
||||
.to_str()
|
||||
.context("Generating new name")?[12..]
|
||||
.strip_suffix(".tsv")
|
||||
.context("Stripping extention")?;
|
||||
let categories =
|
||||
load_categories_from_tsv(single_class.clone()).context("Loading from csv")?;
|
||||
final_class_list.push(FinalClassRadar::from_radar_with_name(
|
||||
class_name.to_string(),
|
||||
categories,
|
||||
))
|
||||
}
|
||||
// Calculate all the max values
|
||||
final_class_list[0] = final_class_list
|
||||
.iter()
|
||||
.fold(FinalClassRadar::default_for_acc(), |a, b| a.find_max(b));
|
||||
|
||||
let mut wtr = csv::WriterBuilder::new()
|
||||
.has_headers(true)
|
||||
.from_path("Images/Radar/radar.csv")
|
||||
.context("Creating CSV output file")?;
|
||||
|
||||
// println!("{:?}", final_class_list);
|
||||
for cv in &final_class_list {
|
||||
wtr.serialize(cv).context("Writing CSV record")?;
|
||||
}
|
||||
|
||||
wtr.flush().context("Flushing CSV writer")?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Reads a TSV file that either has the header line shown above or
|
||||
/// just raw data rows, and returns a `Vec<Categories>`.
|
||||
pub fn load_categories_from_tsv<P: AsRef<Path>>(path: P) -> Result<LoadedClassRadar> {
|
||||
// `has_headers(false)` tells the csv crate to *not* treat the first row as a header.
|
||||
// We’ll do the header check ourselves.
|
||||
let file = File::open(path)?;
|
||||
let mut rdr = csv::ReaderBuilder::new()
|
||||
.has_headers(false)
|
||||
.delimiter(b'\t')
|
||||
.double_quote(false)
|
||||
.escape(Some(b'\\'))
|
||||
.flexible(true)
|
||||
.comment(Some(b'#'))
|
||||
.from_reader(file);
|
||||
|
||||
let mut sum = LoadedClassRadar::default();
|
||||
for result in rdr.deserialize() {
|
||||
let result: RawRow = result?;
|
||||
if result.technique.starts_with("Tier ") {
|
||||
// Getto way of knowing we have a new tier, that we ignore
|
||||
} else if (result.technique == "Technique") | result.technique.is_empty() {
|
||||
// Skip this entry
|
||||
} else {
|
||||
sum = sum + result.into();
|
||||
}
|
||||
}
|
||||
Ok(sum)
|
||||
}
|
||||
|
||||
/// The data for all graphs
|
||||
struct GraphValues {
|
||||
/// The max values of a graph
|
||||
|
|
@ -279,15 +206,15 @@ impl MiniTheme {
|
|||
/// The default theme for out tool
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
font_family: "Latin Modern Roman".to_string(),
|
||||
font_family: "LMRoman8".to_string(),
|
||||
margin: Box {
|
||||
left: 10.0,
|
||||
left: -10.0,
|
||||
top: 20.0,
|
||||
right: 90.0,
|
||||
bottom: 60.0,
|
||||
right: 70.0,
|
||||
bottom: 0.0,
|
||||
},
|
||||
width: 860.0,
|
||||
height: 560.0,
|
||||
width: 720.0,
|
||||
height: 440.0,
|
||||
grid_stroke_color: Color {
|
||||
r: 77,
|
||||
g: 69,
|
||||
|
|
@ -374,15 +301,3 @@ pub struct MiniTheme {
|
|||
// pub table_body_colors: Vec<Color>,
|
||||
// pub table_border_color: Color,
|
||||
}
|
||||
|
||||
/// List all files matching a pattern in the given directory
|
||||
#[inline]
|
||||
fn list_dir(pattern: &str) -> Vec<PathBuf> {
|
||||
// println!("{}", pattern);
|
||||
// println!("{:?}", glob(pattern));
|
||||
|
||||
glob(pattern)
|
||||
.expect("Failed to read glob pattern")
|
||||
.flatten()
|
||||
.collect()
|
||||
}
|
||||
|
|
@ -1,7 +1,3 @@
|
|||
[data_generation]
|
||||
# This value should be overwriten by a relative path
|
||||
database = "./ravenous_databases/weapons.db"
|
||||
|
||||
[classes]
|
||||
header = '''\begin{}[
|
||||
presep = 0pt, postsep = 0pt,
|
||||
|
|
@ -145,223 +141,3 @@ end_long_side = ''' \hline
|
|||
\end{longtblr}
|
||||
\end{center}\end{landscape}'''
|
||||
end_empty = ""
|
||||
|
||||
[monster]
|
||||
common_part = '''
|
||||
{{#with data}}
|
||||
\section{ {{{~name~}}} }
|
||||
\begin{tblr}{
|
||||
vspan=even, hspan=minimal,
|
||||
colspec={X[-1] X[-1]},
|
||||
cell{1}{1}={c=2}{c},
|
||||
}
|
||||
|
||||
{{#if image}}\includegraphics[height=5cm]{ {{{~image~}}} } & \\ {{/if}}
|
||||
& \\
|
||||
Nom & {{{name}}} \\
|
||||
{{#if denomination}}Dénomination & {{{denomination}}} \\
|
||||
{{/if}}{{#if calamity}}Calamité & {{{calamity}}} \\
|
||||
{{/if}}{{#if danger_level}}Niveau de danger (HSE) & {{{danger_level}}} \\
|
||||
{{/if}}& \\
|
||||
{{#if habitat}}Habitat & \SetCell{font=\footnotesize} {{{habitat}}} \\
|
||||
{{/if}}{{#if dysmorphism}}Dysmorphisme & \SetCell{font=\footnotesize} {{{dysmorphism}}} \\
|
||||
{{/if}}{{#if colors}}Couleurs & \SetCell{font=\footnotesize} {{{colors}}} \\
|
||||
{{/if}}{{#if default_human_reaction}}Réaction à l'homme & \SetCell{font=\footnotesize} {{{default_human_reaction}}} \\
|
||||
{{/if}}{{#if variants}}Variantes & \SetCell{font=\footnotesize} {{{variants}}}\\
|
||||
{{/if}}{{#if size}}Taille & \SetCell{font=\footnotesize} {{{size}}}\\
|
||||
{{/if}}{{#if traces}}Traces & \SetCell{font=\footnotesize} {{{traces}}}\\
|
||||
{{/if}}{{#if habits}}Mœurs & \SetCell{font=\footnotesize} {{{habits}}} \\
|
||||
{{/if}}\end{tblr}
|
||||
\vfill
|
||||
\begin{tblr}{
|
||||
colspec={X[-1]},
|
||||
hline{2,4,6},
|
||||
row{2,4,6}={font=\footnotesize}
|
||||
}
|
||||
{{#if description}}\textbf{Description} \\
|
||||
{{{description}}} \\ {{/if}}
|
||||
{{#if annotations}}\textbf{Annotations} \\
|
||||
{{{annotations}}} \\ {{/if}}
|
||||
\textbf{Récompenses} \\
|
||||
\end{tblr}
|
||||
\begin{tblr}{
|
||||
colspec={X[1] X[1,c] X[2,c] X[3,j]},
|
||||
vspan=even, hspan=minimal,
|
||||
row{1-Z}={font=\footnotesize},
|
||||
rows={m},
|
||||
} {{/with}}{{#with stats}}
|
||||
\SetCell[c=3]{j} Sang (base, combat, dépeçage) & & & {{{blood_base}}}, {{{blood_battle}}}, {{{blood_carve}}} \\ {{/with}}{{#with rewards}}{{#each rewards}}
|
||||
{{{name}}} & {{{category}}} & {{#if cost}} {{{cost}}} & {{{effect}}} {{else}} \SetCell[c=2]{j} {{{effect}}} & {{/if}} \\ {{/each}}{{/with}}
|
||||
\end{tblr}
|
||||
\vfill
|
||||
\pagebreak
|
||||
'''
|
||||
master_part = '''
|
||||
\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
|
||||
{{#with stats as |s|}}
|
||||
{{#each ../body_parts.body_parts}}
|
||||
\SetCell{font=\footnotesize} {{{body_part_name}}} & ${{{threshold_p1}}} ${\tiny ({{{threshold_bonus threshold_p1 ../../stats/size_bonus_to_hit~}}}) } & ${{{plus s.strength protection_p1}}}[{{{protection_p1}}}]$ & \SetCell{r,f}\tiny ${{{integrity_p1}}} $ & \SetCell{r,f}\tiny ${{{life_points_p1}}} $ & ${{{threshold_p2}}} ${\tiny ({{{threshold_bonus threshold_p1 ../../stats/size_bonus_to_hit~}}}) } & ${{{plus s.strength protection_p1}}}[{{{protection_p1}}}]$ & \SetCell{r,f}\tiny ${{{integrity_p2}}} $ & \SetCell{r,f}\tiny ${{{life_points_p2}}} $\\
|
||||
{{/each}}
|
||||
{{/with}}
|
||||
{{#if data.annotations_master}}
|
||||
\hline
|
||||
\SetCell[c=9]{j,h} {\textbf{Notes} \\ {{{data.annotations_master}}}}\\
|
||||
{{/if}}
|
||||
\hline
|
||||
\end{tblr}
|
||||
\begin{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},
|
||||
}
|
||||
& & & & & & & & & & & & & \\
|
||||
\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}}} $ & ${{{piercing}}} $ & ${{{blunt}}} $ & ${{{celestial}}} $ & ${{{fire}}} $ & ${{{earth}}} $ & ${{{wood}}} $ & ${{{magma}}} $ & ${{{celeste}}} $ & ${{{water}}} $ & ${{{wind}}} $ & ${{{ice}}} $ & ${{{thunder}}} $ \\
|
||||
{{/each}}
|
||||
\end{tblr}
|
||||
\end{center}
|
||||
|
||||
\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 {{#if elemental_bonus}}c{{/if}}},
|
||||
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 & & & & & Extra & \\
|
||||
\cline{2-3} \cline{4-5} \cline{7-13} \cline{15-18} \cline{20-{{#if stats.elemental_bonus_dmg}}22{{else}}21{{/if}} }
|
||||
\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{Res. \symtranscendental} & \rb{Bon. Phy} {{#if stats.elemental_bonus_dmg}}& \rb{Bon. Élém} {{/if}} \\
|
||||
{{#each init_full}}
|
||||
{{#if @index}}
|
||||
\SetCell{font=\footnotesize} $i_{{(plus @index 1)}} $ & ${{{p1_value}}} $ & ${{{p1_actions}}}$ & ${{{p2_value}}} $ & ${{{p2_actions}}}$ \\
|
||||
{{else}}
|
||||
{{#with ../stats~}}
|
||||
\SetCell{font=\footnotesize} $i_1 $ & ${{{p1_init}}} $ & ${{{p1_actions}}} $ & ${{{p2_init}}} $ & ${{{p1_actions}}} $ & & ${{{strength}}} $ & ${{{perception}}} $ & ${{{willpower}}} $ & ${{{alteration_resistance}}} $ & ${{{torque}}} $ & ${{{awareness}}} $ & ${{{fatigue}}} $ & & ${{{mvt_walk}}} $ & ${{{mvt_trot}}} $ & ${{{mvt_run}}} $ & ${{{mvt_flight}}} $ & & ${{{resistance_transcendentale}}} $ & ${{{physical_bonus_dmg}}} $ {{#if elemental_bonus_dmg}} & ${{elemental_bonus_dmg}} $ {{/if}} \\
|
||||
{{/with}}
|
||||
{{/if}}
|
||||
{{/each}}
|
||||
\end{tblr}
|
||||
\vfill
|
||||
|
||||
{{#if (len all_attacks.phases)}}
|
||||
\pagebreak
|
||||
{\scriptsize
|
||||
\begin{longtblr}{
|
||||
colspec={X[0.05] X[2.5,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[4,l] X[0.3,c] X[0.3,c]},
|
||||
hspan=minimal,
|
||||
colsep=2pt,
|
||||
row{2}={font=\tiny},
|
||||
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} \\
|
||||
{{else}}
|
||||
\SetCell[c=13]{white} \textsc{ {{{~@key~}}} } & & & & & & & & & & \\
|
||||
{{/if}}
|
||||
{{#each phase as | attack_group |}}
|
||||
\hline
|
||||
{{#each attack_group.attacklist}}
|
||||
\SetCell{bg={{{../color}}}} & {{{name}}} & {{{attack_type}}} & {{{prerequisites}}} & {{{targetting}}} & {{{cost_fatigue}}} & {{{cost_action}}} & {{{element}}} & {{{damage_fatigue}}} & {{{damage_regular}}} {{{success}}} & {{#if armor_break}} {{{armor_break}}}\arbreakk{} {{/if}}{{#if armor_pierce}} {{{armor_pierce}}}\arpierce{} {{/if}}{{#if antimaterial}} {{{antimaterial}}}\antimateriel{} {{/if}} {{{effects}}} & {{{threshold_parry}}} & {{{threshold_dodge}}} \\
|
||||
{{/each}}
|
||||
{{#if description_final}}\SetCell{bg={{{color}}}} & \SetCell[c=12]{j} {{{description_final}}} & & & & & & & & & & \\
|
||||
{{/if}} \hline
|
||||
{{/each}}
|
||||
{{/each}}
|
||||
\end{longtblr}
|
||||
}
|
||||
\vfill
|
||||
{{/if}}
|
||||
{{#with data}}
|
||||
\pagebreak
|
||||
\begin{tblr}{
|
||||
colspec={X[7] {{#if intent_graph}}|X[3] {{/if~}} },
|
||||
rowspec={X[c] X[j,h,8cm]},
|
||||
hline{2},
|
||||
row{2}={font=\footnotesize},
|
||||
}
|
||||
Plan de combat {{#if intent_graph}}& Graphique d'intentions{{/if}} \\
|
||||
{{{battle_plan}}} {{#if intent_graph}}& {{{intent_graph}}}{{/if}} \\
|
||||
\end{tblr}
|
||||
\vfill
|
||||
\pagebreak
|
||||
{{/with}}
|
||||
'''
|
||||
color_table='''
|
||||
ATK: ravred
|
||||
MVT: ravblu
|
||||
DEF: ravgrn
|
||||
PAS: ravgrnL
|
||||
REV: ravgrn
|
||||
CLM: ravgrnD
|
||||
TRA: ravora
|
||||
ASE: ravred
|
||||
STA: ravwhi
|
||||
CMB: ravred
|
||||
FLR: ravred
|
||||
GRB: ravred
|
||||
TBU: ravredD
|
||||
TSH: ravredD
|
||||
TBZ: ravredD
|
||||
CLV: ravred
|
||||
AOE: ravred
|
||||
WID: ravred
|
||||
WIP: ravredD
|
||||
SZO: ravwhi
|
||||
SIT: ravwhi
|
||||
SRG: ravpur
|
||||
HRG: ravpur
|
||||
BAD: ravora
|
||||
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} & \arbreakk & \protection & \integrite & $\mathbb{T}$2 & $\mathbb{T}$1 & {Modes} & {Esq.} & {Par.} & {Vit.} & {Disc.} & {Spécial} & {\aLvl} & {\aCst} \\
|
||||
\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~}} } & \ddlvl{ {{~cost~}} } \\
|
||||
{{#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} \\
|
||||
|
|
|
|||
|
|
@ -0,0 +1,18 @@
|
|||
[package]
|
||||
name = "make"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
config = {path = "../config"}
|
||||
cli_parser = {path = "../cli_parser"}
|
||||
dynfmt = { version = "0.1.5", features = ["curly"] }
|
||||
indicatif = { version = "0.17.11", features = ["rayon"] }
|
||||
logos = "0.15.0"
|
||||
tokio = "1.43.0"
|
||||
anyhow = "1.0.95"
|
||||
indexmap = "2.7.1"
|
||||
regex = "1.11.1"
|
||||
serde = { version = "1.0.217", features = ["derive", "alloc"] }
|
||||
console = "0.15.10"
|
||||
toml = "0.8.20"
|
||||
|
|
@ -30,16 +30,15 @@ use tokio::{
|
|||
process::Command,
|
||||
};
|
||||
|
||||
use anyhow::{Context, Result, anyhow};
|
||||
use anyhow::{Result, anyhow};
|
||||
|
||||
use crate::makepdf_functions::{
|
||||
BuilderParseResult, make_clean, make_file, make_glossaries, make_list,
|
||||
};
|
||||
use crate::makepdf_structs::{
|
||||
BuildInfo, COL_INFO, COL_NORMAL, LineType, Status, TXT_BOXX, TXT_CNTX, TXT_CRIT, TXT_ERRR,
|
||||
TXT_INFO, TXT_MISC, TXT_UKNW, TXT_WARN,
|
||||
};
|
||||
use crate::{
|
||||
makepdf_functions::{BuilderParseResult, make_clean, make_file, make_glossaries, make_list},
|
||||
makepdf_structs::TXT_ICTX,
|
||||
};
|
||||
|
||||
/// Make a pdf spawning a subprocess
|
||||
pub fn make_pdf(args: &MakeConfig, _config: &Config) -> Result<()> {
|
||||
|
|
@ -62,7 +61,7 @@ pub fn make_pdf(args: &MakeConfig, _config: &Config) -> Result<()> {
|
|||
Some(MakeTargets::Clean) => make_clean(args),
|
||||
None => {
|
||||
let file = make_file(args);
|
||||
launch_subprocess(args, file).context("Launching PdfLatex")?;
|
||||
launch_subprocess(args, file).unwrap();
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
|
|
@ -79,7 +78,7 @@ async fn launch_subprocess(
|
|||
args: &MakeConfig,
|
||||
rebuild_target: BuilderParseResult,
|
||||
) -> Result<Status> {
|
||||
let mut cmd = Command::new(&args.latex_command);
|
||||
let mut cmd = Command::new("pdflatex");
|
||||
let mut status = Status::zero();
|
||||
|
||||
let started = Instant::now();
|
||||
|
|
@ -103,7 +102,7 @@ async fn launch_subprocess(
|
|||
// Specify that we want the command's standard output piped back to us.
|
||||
cmd.stdout(Stdio::piped());
|
||||
|
||||
let mut child = cmd.spawn().context("Failed to spawn command")?;
|
||||
let mut child = cmd.spawn().expect("Failed to spawn command");
|
||||
|
||||
let stdout = child
|
||||
.stdout
|
||||
|
|
@ -268,10 +267,6 @@ fn checkline(
|
|||
return Ok(());
|
||||
}
|
||||
|
||||
if final_line.vlvl() >= VerboseLevel::Error {
|
||||
let v = final_line.clone();
|
||||
let _ = status.first_error.set(v);
|
||||
}
|
||||
match &final_line.vlvl() {
|
||||
VerboseLevel::None => (),
|
||||
VerboseLevel::Misc => pb.println(format!(
|
||||
|
|
@ -289,15 +284,6 @@ fn checkline(
|
|||
*TXT_CNTX,
|
||||
COL_NORMAL.apply_to(final_line)
|
||||
)), // Context tends to be shit ))?
|
||||
VerboseLevel::InteractiveContext => {
|
||||
if !args.non_interactive {
|
||||
pb.println(format!(
|
||||
"{} {:?}",
|
||||
*TXT_ICTX,
|
||||
COL_NORMAL.apply_to(final_line)
|
||||
))
|
||||
}
|
||||
}
|
||||
VerboseLevel::Info => {
|
||||
status.info += 1;
|
||||
pb.println(format!(
|
||||
|
|
@ -331,7 +317,7 @@ fn checkline(
|
|||
))
|
||||
}
|
||||
VerboseLevel::Uncatchable => {
|
||||
status.errors += 1;
|
||||
// status.errors += 1;
|
||||
pb.println(format!(
|
||||
"{} {}",
|
||||
*TXT_UKNW,
|
||||
|
|
@ -339,6 +325,5 @@ fn checkline(
|
|||
))
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
|
@ -89,7 +89,7 @@ pub(super) fn make_file(args: &MakeConfig) -> BuilderParseResult {
|
|||
}
|
||||
|
||||
BuilderParseResult {
|
||||
new_name: format!("{:?}", path),
|
||||
new_name: format!("{:?}", &path),
|
||||
chapt_list: chapters,
|
||||
}
|
||||
}
|
||||
|
|
@ -301,9 +301,9 @@ pub(super) fn make_clean(args: &MakeConfig) {
|
|||
for s in list_suff {
|
||||
// The most ghetto *** I've done so far
|
||||
// cmd.arg(format!("{}{}", &target, s));
|
||||
cmd.arg(format!("{}_build{}", target, s));
|
||||
cmd.arg(format!("{}_build{}", &target, s));
|
||||
}
|
||||
cmd.arg(format!("{}_build{}", target, ".tex"));
|
||||
cmd.arg(format!("{}_build{}", &target, ".tex"));
|
||||
// println!("{:?}", cmd);
|
||||
if let Err(e) = cmd.output() {
|
||||
println!(
|
||||
|
|
@ -7,7 +7,6 @@ use config::make::VerboseLevel;
|
|||
use logos::Logos;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{
|
||||
cell::OnceCell,
|
||||
io::{Read, Write},
|
||||
sync::LazyLock,
|
||||
time::{Duration, Instant},
|
||||
|
|
@ -47,9 +46,6 @@ pub(super) static TXT_BOXX: LazyLock<String> =
|
|||
/// Filler box for the [CNTX] text box
|
||||
pub(super) static TXT_CNTX: LazyLock<String> =
|
||||
LazyLock::new(|| format!("{}", COL_CONTEXT.apply_to(&"[CNTX]")));
|
||||
/// Filler box for the [CNTX] text box
|
||||
pub(super) static TXT_ICTX: LazyLock<String> =
|
||||
LazyLock::new(|| format!("{}", COL_CONTEXT.apply_to(&"[ICTX]")));
|
||||
/// Filler box for the [INFO] text box
|
||||
pub(super) static TXT_INFO: LazyLock<String> =
|
||||
LazyLock::new(|| format!("{}", COL_INFO.apply_to(&"[INFO]")));
|
||||
|
|
@ -142,7 +138,7 @@ impl BuildInfo {
|
|||
|
||||
/// The line encountered
|
||||
// #[allow(unused)]
|
||||
#[derive(Debug, Logos, PartialEq, Clone)]
|
||||
#[derive(Debug, Logos, PartialEq)]
|
||||
#[logos(skip r"[) ]+")]
|
||||
pub(super) enum LineType {
|
||||
/// The tex building mode : entering extended mode
|
||||
|
|
@ -229,31 +225,15 @@ pub(super) enum LineType {
|
|||
// #[regex(r"[\) ]*\(\./[A-z/]+\.tex", |lex| lex.slice().split("(").nth(1).unwrap_or("").to_string())]
|
||||
// #[regex(r"[\) ]*(\[[0-9]+\] )?\(\./[A-z/-_]+\.tex", |lex| lex.slice().split("(").nth(1).unwrap_or("").to_string())]
|
||||
// #[regex(r"[\) 0-9\[\]]*\(\./[A-z/-_]+\.tex", |lex| lex.slice().split("(").nth(1).unwrap_or("").to_string())]
|
||||
#[regex(r"\(\./[A-z/0-9_-]+\.(gls|tex)", |lex| lex.slice().split("(").nth(1).unwrap_or("").to_string())]
|
||||
#[regex(r"\(\./[A-z/_-]+\.(gls|tex)", |lex| lex.slice().split("(").nth(1).unwrap_or("").to_string())]
|
||||
EnteringDocument(String),
|
||||
|
||||
/// Info on the loading of a library
|
||||
#[regex(r"Library \(\w+\)[^\n]+", |lex| split_by(":",&lex.slice()[8..]), allow_greedy=true)]
|
||||
#[regex(r"Library \(\w+\)[^\n]+", |lex| split_by(":",&lex.slice()[8..]))]
|
||||
Library((String, String)),
|
||||
|
||||
/// Glossary will not be built
|
||||
#[token("This document will not have a glossary.")]
|
||||
#[token("Remove .makeglossaries if you don't want any glossaries.")]
|
||||
NoGlossary,
|
||||
|
||||
#[regex(r"No file [^$]+\.gls\.", |lex| lex.slice().replace("No file ", ""))]
|
||||
/// The glossary file wasn't found
|
||||
NoGlossaryFile(String),
|
||||
|
||||
#[regex(
|
||||
r" ?\)?<?/usr/share/texlive/texmf.dist/fonts/type1/public/fontawesome5[^\n]+",
|
||||
allow_greedy = true
|
||||
)]
|
||||
/// The fontawesome package has loaded it's fonts
|
||||
FontAwesome,
|
||||
|
||||
/// The warning generated by a package
|
||||
#[regex(r"Package [A-z_-]+ Warning: [^\n]+", |lex| split_by(":",lex.slice()), allow_greedy=true)]
|
||||
#[regex(r"Package [A-z_-]+ Warning: [^\n]+", |lex| split_by(":",lex.slice()))]
|
||||
PackageWarningPrs((String, String)),
|
||||
|
||||
/// A package warning, with normal warning level
|
||||
|
|
@ -263,18 +243,9 @@ pub(super) enum LineType {
|
|||
LowPackageWarning((String, String)),
|
||||
|
||||
/// The warning context generated by a package
|
||||
#[regex(r"\([A-z_-]+\) [^\n]+", |lex| split_by(")",&lex.slice()[1..]), allow_greedy=true)]
|
||||
#[regex(r"\([A-z_-]+\) [^\n]+", |lex| split_by(")",&lex.slice()[1..]))]
|
||||
PackageContext((String, String)),
|
||||
|
||||
/// You should read the LaTex manual
|
||||
#[token("See the pdftex.def package documentation for explanation.", |lex| lex.slice().to_string())]
|
||||
#[token("See the LaTeX manual or LaTeX Companion for explanation.", |lex| lex.slice().to_string())]
|
||||
HelpGiven(String),
|
||||
|
||||
/// Interactive prompt
|
||||
#[token("Type H for immediate help.")]
|
||||
Prompt,
|
||||
|
||||
/// Loading (Load something)
|
||||
#[regex(r"(\)+ )?\(/usr[^)]*", |lex| lex.slice().split("/").last().unwrap_or("").to_string())]
|
||||
Loading(String),
|
||||
|
|
@ -297,10 +268,9 @@ pub(super) enum LineType {
|
|||
#[token("Transcript written on")]
|
||||
Log,
|
||||
|
||||
/// Useless help line
|
||||
#[regex(r"\.\.\.")]
|
||||
Garbage,
|
||||
|
||||
// /// Barely parsable data
|
||||
// #[regex(r"\)+")]
|
||||
// Garbage,
|
||||
/// Empty line, to discard
|
||||
Empty,
|
||||
|
||||
|
|
@ -315,76 +285,44 @@ pub(super) enum LineType {
|
|||
/// Transcript
|
||||
#[token("(see the transcript file for additional information)")]
|
||||
Transcript,
|
||||
// /// Known Errors
|
||||
|
||||
// ! Package pdftex.def Error: File `./Images/Bestiaire/Mjonn Alpha des Brumes.jpg' not found: using draft setting. // ! LaTeX Error: \begin{tblr} on input line 587 ended by \end{longtblr}.
|
||||
// /// Unmatch begin and end environement
|
||||
// #[token("! LeTex Error")]
|
||||
// UnmatchedSequences,
|
||||
// /// A \ something was used without being defined
|
||||
// #[token("! Undefined control sequence.")]
|
||||
// UndefinedControlSequence,
|
||||
|
||||
// /// Error Context
|
||||
// #[regex(r"l\.\d+ [^\n]+", |lex| split_by(" ",lex.slice()), allow_greedy=true) ]
|
||||
// #[regex(r".+\[^\]+", |lex| split_by("\\",lex.slice()), allow_greedy=true) ]
|
||||
// #[regex(" +\\[^\n]+", |lex|{("".to_string(),lex.slice().trim_start().to_string())},allow_greedy = true)]
|
||||
// // #[regex(r"\(\./[A-z/_-]+\.(gls|tex)", |lex| lex.slice().split("(").nth(1).unwrap_or("").to_string())]
|
||||
// ErrorContext((String, String)),
|
||||
}
|
||||
|
||||
impl LineType {
|
||||
/// Decides all verbose levels, for output
|
||||
pub(super) fn vlvl(&self) -> VerboseLevel {
|
||||
match &self {
|
||||
LineType::PageGen => VerboseLevel::None,
|
||||
LineType::Empty => VerboseLevel::None,
|
||||
|
||||
LineType::LowPackageWarning(_) => VerboseLevel::Box,
|
||||
LineType::BoxFullness(_) => VerboseLevel::Box,
|
||||
|
||||
LineType::Mode => VerboseLevel::Misc,
|
||||
LineType::Info(_) => VerboseLevel::Misc,
|
||||
LineType::StartingSequence => VerboseLevel::Misc,
|
||||
LineType::EndSequence => VerboseLevel::Misc,
|
||||
LineType::MPSConverter => VerboseLevel::Misc,
|
||||
LineType::Chapter(_) => VerboseLevel::Context,
|
||||
LineType::MissingReference(_) => VerboseLevel::Warning,
|
||||
LineType::PdfTexVersion(_) => VerboseLevel::Misc,
|
||||
LineType::Context(_) => VerboseLevel::Misc,
|
||||
LineType::LaTexVersion => VerboseLevel::Misc,
|
||||
LineType::WriteMode => VerboseLevel::Misc,
|
||||
LineType::DocumentClass => VerboseLevel::Misc,
|
||||
LineType::EnteringDocument(_) => VerboseLevel::Info,
|
||||
LineType::Library(_) => VerboseLevel::Context,
|
||||
LineType::PackageContext(_) => VerboseLevel::Warning,
|
||||
LineType::Loading(_) => VerboseLevel::Context,
|
||||
LineType::Unknown(_) => VerboseLevel::Uncatchable,
|
||||
LineType::PageGen => VerboseLevel::None,
|
||||
LineType::Output => VerboseLevel::Misc,
|
||||
LineType::Log => VerboseLevel::Misc,
|
||||
LineType::Empty => VerboseLevel::None,
|
||||
LineType::GeometryResolution => VerboseLevel::Misc,
|
||||
LineType::GeometryFound => VerboseLevel::Misc,
|
||||
LineType::Transcript => VerboseLevel::Misc,
|
||||
|
||||
LineType::EnteringDocument(_) => VerboseLevel::Info,
|
||||
|
||||
LineType::Library(_) => VerboseLevel::Context,
|
||||
LineType::Chapter(_) => VerboseLevel::Context,
|
||||
LineType::Loading(_) => VerboseLevel::Context,
|
||||
|
||||
LineType::MissingReference(_) => VerboseLevel::Warning,
|
||||
LineType::PackageContext(_) => VerboseLevel::Warning,
|
||||
LineType::Warning(_) => VerboseLevel::Warning,
|
||||
LineType::PackageWarning(_) => VerboseLevel::Warning,
|
||||
|
||||
LineType::Unknown(_) => VerboseLevel::Uncatchable,
|
||||
|
||||
LineType::LowPackageWarning(_) => VerboseLevel::Box,
|
||||
LineType::BoxFullness(_) => VerboseLevel::Box,
|
||||
LineType::Warning(_) => VerboseLevel::Warning,
|
||||
LineType::WarningPrs => VerboseLevel::Critical,
|
||||
LineType::MissingReferencePrs => VerboseLevel::Critical,
|
||||
LineType::BoxFullnessPrs => VerboseLevel::Critical,
|
||||
LineType::PackageWarningPrs(_) => VerboseLevel::Critical,
|
||||
LineType::NoGlossary => VerboseLevel::Warning,
|
||||
LineType::FontAwesome => VerboseLevel::Info,
|
||||
LineType::NoGlossaryFile(_) => VerboseLevel::Warning,
|
||||
LineType::HelpGiven(_) => VerboseLevel::Context,
|
||||
LineType::Prompt => VerboseLevel::InteractiveContext,
|
||||
LineType::Garbage => VerboseLevel::None,
|
||||
// LineType::ErrorContext(_) => VerboseLevel::Error,
|
||||
// LineType::UndefinedControlSequence => VerboseLevel::Error,
|
||||
// LineType::UnmatchedSequences => VerboseLevel::Error,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -392,10 +330,10 @@ impl LineType {
|
|||
/// Tries to split the token and return two string
|
||||
fn split_by(delim: &str, text: &str) -> Option<(String, String)> {
|
||||
let mut slice = text.split(delim);
|
||||
if let Some(one) = slice.next()
|
||||
&& let Some(two) = slice.next()
|
||||
{
|
||||
return Some((one.to_string(), two.trim_start().to_string()));
|
||||
if let Some(one) = slice.next() {
|
||||
if let Some(two) = slice.next() {
|
||||
return Some((one.to_string(), two.trim_start().to_string()));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
|
@ -408,8 +346,8 @@ pub(super) struct Status {
|
|||
pub(super) warnings: usize,
|
||||
/// Only makes sense with non-interactie builds
|
||||
pub(super) errors: usize,
|
||||
/// List of all recoverable
|
||||
pub(super) first_error: OnceCell<LineType>,
|
||||
// /// List of all recoverable
|
||||
// pub(super) v_errors: Vec<String>,
|
||||
}
|
||||
|
||||
impl Status {
|
||||
|
|
@ -419,7 +357,6 @@ impl Status {
|
|||
info: 0,
|
||||
warnings: 0,
|
||||
errors: 0,
|
||||
first_error: OnceCell::new(),
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -431,16 +368,6 @@ impl Status {
|
|||
file_info: BuilderParseResult,
|
||||
) {
|
||||
let col_bld = COL_INFO.clone().bold();
|
||||
if self.errors > 3 {
|
||||
println!(
|
||||
"{} {}",
|
||||
col_bld.apply_to("[RCAP]"),
|
||||
COL_NORMAL.apply_to(format!(
|
||||
"The first error encountered was: {:?}",
|
||||
self.first_error.get()
|
||||
))
|
||||
);
|
||||
}
|
||||
println!();
|
||||
println!(
|
||||
"{} {}",
|
||||
|
|
@ -7,7 +7,7 @@ version.workspace = true
|
|||
more_fields_macro = {path ="../more_fields_macro"}
|
||||
|
||||
[dev-dependencies]
|
||||
pretty_assertions = {workspace = true}
|
||||
pretty_assertions = "1.4.1"
|
||||
|
||||
[features]
|
||||
expand_macro = []
|
||||
|
|
@ -0,0 +1,66 @@
|
|||
// Workspace: more_fields
|
||||
// File: more_fields/src/lib.rs
|
||||
//! Get all the fields as a Vec<("attribute", "type")>
|
||||
//! Note that this map is implemented without self, allowing us to use it only as a generic,
|
||||
//! however this limitation is completely artificial
|
||||
|
||||
pub use more_fields_macro::FieldsAsSlice;
|
||||
|
||||
pub trait FieldsAsSlice {
|
||||
fn attributes_slice() -> &'static [(&'static str, &'static str)];
|
||||
}
|
||||
|
||||
// fn iter(&self) -> std::vec::IntoIter<(&'static str, &'static str)>;
|
||||
|
||||
// #[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,
|
||||
// }
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use crate::FieldsAsSlice;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[allow(dead_code)]
|
||||
#[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,
|
||||
}
|
||||
#[test]
|
||||
fn test_derive_impl() {
|
||||
println!("{:?}", Bob::attributes_slice());
|
||||
// assert!(
|
||||
let b_hash = vec![
|
||||
("field_ouane", "TEXT"),
|
||||
("field_2", "INTEGER"),
|
||||
("field_3", "BLOB"),
|
||||
("field_4", "NULL"),
|
||||
("field_5", "REAL"),
|
||||
("field_6", "TEXT"),
|
||||
];
|
||||
|
||||
assert_eq!(Bob::attributes_slice(), b_hash);
|
||||
}
|
||||
}
|
||||
|
|
@ -7,5 +7,5 @@ version.workspace = true
|
|||
proc-macro = true
|
||||
|
||||
[dependencies]
|
||||
quote = "1.0.46"
|
||||
syn = {version= "2.0.118", features=["full"]}
|
||||
quote = "1.0.38"
|
||||
syn = "2.0.98"
|
||||
|
|
@ -0,0 +1,83 @@
|
|||
// Workspace: more_fields_macro
|
||||
// File: more_fields_macro/src/lib.rs
|
||||
//! A very simple proc macro in chage of giving a field slice over ("name","sql_type")
|
||||
//! This macro is a fork of the excellent work of : <https://crates.io/crates/struct_iterable>
|
||||
//!
|
||||
//! Other ressources include:
|
||||
//! - <https://github.com/rust-lang/reference/blob/master/src/procedural-macros.md#attribute-macros>
|
||||
//! - <https://docs.rs/syn/latest/syn/struct.Attribute.html>
|
||||
//! - <https://docs.rs/syn/latest/syn/struct.Attribute.html#parsing-from-tokens-to-attribute>
|
||||
//! - <https://docs.rs/syn/latest/syn/struct.Ident.html>
|
||||
//!
|
||||
// use proc_macro::TokenStream;
|
||||
// use quote::quote;
|
||||
// use syn::{Data, DeriveInput, Fields, parse_macro_input};
|
||||
#![feature(coverage_attribute)]
|
||||
extern crate proc_macro;
|
||||
|
||||
use proc_macro::{Span, TokenStream};
|
||||
use quote::quote;
|
||||
use syn::DeriveInput;
|
||||
use syn::Ident;
|
||||
use syn::parse_macro_input;
|
||||
use syn::{Data, Fields};
|
||||
|
||||
#[coverage(off)]
|
||||
#[proc_macro_derive(FieldsAsSlice, attributes(INTEGER, NULL, REAL, TEXT, BLOB))]
|
||||
pub fn derive_iterable(input: TokenStream) -> TokenStream {
|
||||
let input = parse_macro_input!(input as DeriveInput);
|
||||
|
||||
let struct_name = input.ident;
|
||||
let fields = match input.data {
|
||||
Data::Struct(data_struct) => {
|
||||
// let list_attrs = input.attrs.iter().map(|v| v.path());
|
||||
match data_struct.fields {
|
||||
Fields::Named(fields_named) => fields_named.named,
|
||||
_ => panic!("Only structs with named fields are supported"),
|
||||
}
|
||||
}
|
||||
_ => panic!("Only structs are supported"),
|
||||
};
|
||||
|
||||
let fields_iter = fields.iter().map(|field| {
|
||||
let field_ident = &field.ident;
|
||||
let val = field
|
||||
.attrs
|
||||
.iter()
|
||||
.map(|v| v.path().get_ident())
|
||||
.next()
|
||||
.flatten()
|
||||
.cloned()
|
||||
.unwrap_or_else(|| syn::Ident::new("TEXT", Span::call_site().into()))
|
||||
.to_string();
|
||||
let field_name = field_ident.as_ref().unwrap().to_string();
|
||||
quote! {
|
||||
(#field_name, #val)
|
||||
}
|
||||
});
|
||||
|
||||
let name_of_static_str = struct_name.to_string().to_ascii_uppercase() + "_ATTR_SLICE";
|
||||
let name_of_static = Ident::new(&name_of_static_str, Span::call_site().into());
|
||||
|
||||
let expanded = quote! {
|
||||
/// Derived implementation of a (attribute, type) slice
|
||||
/// allowing a constant time serialisation & deserialisation into rusqlite
|
||||
const #name_of_static: &[(&str, &str)] = &[
|
||||
#(#fields_iter),*
|
||||
];
|
||||
|
||||
impl FieldsAsSlice for #struct_name {
|
||||
/// Gives a precompiled slice of the &[(fields: &str, sqlite_type: &str)]
|
||||
fn attributes_slice<'a>() -> &'static [(&'static str, &'static str)] {
|
||||
#name_of_static
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
TokenStream::from(expanded)
|
||||
}
|
||||
|
||||
// As an hashmap (incorrect as of no ordering)
|
||||
// let mut h = std::collections::HashMap::new();
|
||||
// #(h.insert(#fields_iter);)*
|
||||
// h
|
||||
|
|
@ -0,0 +1,21 @@
|
|||
# cargo-features = ["codegen-backend"]
|
||||
[package]
|
||||
name = "ravenous-tools"
|
||||
version = "0.1.4"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
tablegen = {path = "../tablegen"}
|
||||
graphs = {path = "../graphs"}
|
||||
cli_parser = {path = "../cli_parser"}
|
||||
# config = {path = "../config"}
|
||||
stats = {path = "../stats"}
|
||||
make = {path = "../make"}
|
||||
|
||||
anyhow = "1.0.95"
|
||||
clap = { version = "4.5.28", features = ["derive"] }
|
||||
tokio = { version = "1.43.0", features = ["full"] }
|
||||
toml = "0.8.20"
|
||||
|
||||
[package.metadata.cargo-machete]
|
||||
ignored = ["tokio"]
|
||||
|
|
@ -4,16 +4,14 @@
|
|||
//!
|
||||
#![warn(missing_docs)]
|
||||
#![warn(clippy::missing_docs_in_private_items)]
|
||||
#![feature(coverage_attribute)]
|
||||
#![coverage(off)]
|
||||
|
||||
use fast_class::make_better_gen;
|
||||
// Workspace
|
||||
use formatter::format_file;
|
||||
use graphs::make_graphs;
|
||||
use make::make_pdf;
|
||||
use monsters::monsters_dispatch;
|
||||
use stats::stat_solver;
|
||||
use tablegen::table_gen;
|
||||
use weaponry::{analysis::launch_analysis, export_tex::export_weapons};
|
||||
|
||||
// External imports
|
||||
use anyhow::{Context, Result};
|
||||
|
|
@ -27,7 +25,7 @@ use std::{
|
|||
fn main() -> Result<()> {
|
||||
let args = ParserCLIArgs::parse();
|
||||
let config_str = &fs::read_to_string("helper_config.toml")
|
||||
.unwrap_or(include_str!("../../../helper_config.toml").to_string());
|
||||
.unwrap_or(include_str!("../../helper_config.toml").to_string());
|
||||
let config: Config = toml::from_str(config_str).expect("Coudln't read the config file");
|
||||
match args.command {
|
||||
Commands::Tablegen(args) => table_gen(&args, &config),
|
||||
|
|
@ -35,11 +33,6 @@ fn main() -> Result<()> {
|
|||
Commands::Stats(args) => stat_solver(&args, &config),
|
||||
Commands::Make(args) => make_pdf(&args, &config),
|
||||
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),
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -1 +0,0 @@
|
|||
Subproject commit c5af8a89ccb47b4a4bd57412a13bec90809fc61a
|
||||
|
|
@ -1,225 +0,0 @@
|
|||
# Ravenous Tools - Spec-Schema
|
||||
|
||||
Each line defines a single requirement in a machine-readable format.
|
||||
The token `r[category.subcategory.item]` identifies the requirement; the following paragraph gives a human-friendly description.
|
||||
|
||||
m Bulk Operations
|
||||
r[bulk.export]
|
||||
The `export` command must be able to generate classes, parts or objects as requested
|
||||
|
||||
## Dashboard
|
||||
|
||||
r[dashboard.metrics.display]
|
||||
Dashboard must display aggregated statistics (total classes, average/SD for QOL, Damage, CC, Survivability, Mobility, Alterations, Support) in a terminal table.
|
||||
|
||||
r[dashboard.configuration]
|
||||
Dashboard must be able to read a user configuration with generic thresholds for validation.
|
||||
|
||||
r[dashboard.warnings]
|
||||
Dashboard must issue warnings for classes whose metrics exceed thresholds defined in the config (e.g., damage > 0.8).
|
||||
|
||||
r[dashboard.ascii-charts]
|
||||
Dashboard must be able to render ASCII charts (e.g., bar chart of average damage) using a terminal rendering crate.
|
||||
|
||||
|
||||
## TeX Export
|
||||
|
||||
r[tex.export]
|
||||
The `tex` command must generate a LaTeX file for one or more classes, escaping special characters and including optional headers.
|
||||
|
||||
r[tex.template]
|
||||
The `--template` flag must allow users to provide a custom LaTeX template that overrides the default.
|
||||
|
||||
r[tex.headers]
|
||||
The `--no-headers` flag must omit LaTeX header/footer when appending to an existing document.
|
||||
|
||||
r[tex.output-format]
|
||||
The `--out tex` option must write the output to the file system, respecting the target path and filename conventions.
|
||||
|
||||
## File Export
|
||||
r[file.export.radar]
|
||||
The tool must be able to display small inline graphs (radar) rendered to PNG/SVG for latex inclusion.
|
||||
|
||||
r[file.export]
|
||||
All elements (classes, items) must be compairable and exportable as graph
|
||||
|
||||
r[file.export.html]
|
||||
The tool must be able to export html graphs to compair elements
|
||||
|
||||
## Search / Filter
|
||||
|
||||
r[search.by-name]
|
||||
The `search --name` flag must return class names matching a full or partial string.
|
||||
|
||||
r[search.by-tag]
|
||||
The `search --tag` flag must filter classes containing a specified tag.
|
||||
|
||||
r[search.by-range]
|
||||
The `search` command must support numeric range filters (e.g., `--max-damage 60`) and return classes, objects or parts within the bounds.
|
||||
|
||||
## Graph Generation
|
||||
|
||||
r[graph.damage-senarios]
|
||||
The `graph` command must produce be able to produce several damage scenarios as graphs.
|
||||
|
||||
r[graph.comparison]
|
||||
The `graph comparison` command must produce a chart comparing a user-supplied list of classes.
|
||||
|
||||
r[graph.embeddable]
|
||||
Generated graph files must be referenceable from the TeX export via `\includegraphics`.
|
||||
|
||||
## Validation
|
||||
|
||||
r[validation.schema]
|
||||
All JSON files used must be be validated befor being used.
|
||||
|
||||
r[validation.error-report]
|
||||
Validation errors must identify the exact property and reason, formatted for readability.
|
||||
|
||||
r[validation.value-ranges]
|
||||
The schema must enforce required fields, type constraints, and acceptable numeric ranges for each stat.
|
||||
|
||||
## Help & Auto-Completion
|
||||
|
||||
r[help.full]
|
||||
`--help` for every sub-command must list all options, flags, and usage examples.
|
||||
|
||||
## Logging
|
||||
|
||||
r[logging.verbosity]
|
||||
The CLI must accept `--verbose` and `--quiet` flags to control log level.
|
||||
|
||||
r[logging.levels]
|
||||
Supported levels are `error`, `warn`, `info`, `debug`, and `trace`, matching the configuration defaults.
|
||||
|
||||
## Data Requirements
|
||||
|
||||
r[data.repo-path]
|
||||
The repository root must be configurable via `config/ravenous_tools_data.toml` under `repo_path`.
|
||||
|
||||
r[data.file-format]
|
||||
Each class must be stored as a single JSON file in `data/classes/`.
|
||||
|
||||
r[data.config]
|
||||
Global settings are stored in `config/ravenous_tools_data.toml` with fields for thresholds, templates, etc.
|
||||
|
||||
## Non-Functional Requirements
|
||||
|
||||
r[nonfunctional.extensibility]
|
||||
A plugin system exposing the `ravenous_tools_plugin` trait must allow third-party crates to add metrics or output formats.
|
||||
|
||||
r[nonfunctional.testing]
|
||||
Unit and integration tests must cover ≥90 % of code paths, verified via CI.
|
||||
|
||||
r[nonfunctional.ci]
|
||||
GitHub Actions workflow must run tests, linting, and build on each push/PR.
|
||||
|
||||
r[nonfunctional.documentation]
|
||||
All public APIs must be documented, and a comprehensive README with examples must be provided.
|
||||
|
||||
r[nonfunctional.logging-structured]
|
||||
All logs must be emitted in structured JSON-lines format for easy parsing.
|
||||
|
||||
## User-Story Requirements
|
||||
|
||||
r[userstory.balancer]
|
||||
Balancers must view the aggregated damage-per-HP ratio across all classes in the dashboard.
|
||||
|
||||
r[userstory.writer]
|
||||
Writers must export classes to LaTeX and embed graphs with minimal manual editing.
|
||||
|
||||
r[userstory.developer]
|
||||
Developers must implement custom metric calculators via the plugin interface.
|
||||
|
||||
r[userstory.analyst]
|
||||
Analysts must generate PNG graphs of damage curves directly from the terminal.
|
||||
|
||||
## Acceptance Criteria
|
||||
|
||||
r[acceptance.tex]
|
||||
Generated `.tex` must compile without errors; templates and header flags must function.
|
||||
|
||||
r[acceptance.dashboard]
|
||||
Dashboard must display at least five distinct metrics and render ASCII charts legibly.
|
||||
|
||||
r[acceptance.validation]
|
||||
Invalid JSON files must be rejected with pinpointed error messages.
|
||||
|
||||
r[acceptance.help]
|
||||
`--help` output must enumerate all sub-commands and examples; completion scripts install cleanly.
|
||||
|
||||
r[acceptance.graph]
|
||||
PNG/SVG graph files must be created for each graph command and viewable in standard image viewers.
|
||||
|
||||
r[acceptance.logging]
|
||||
Verbose/quiet modes and file logging must work as specified, with timestamps and levels.
|
||||
|
||||
r[acceptance.testing]
|
||||
Code coverage must be ≥90 %; at least one end-to-end CLI test exercising create, export, and dashboard.
|
||||
|
||||
r[acceptance.documentation]
|
||||
README, usage guide, and plugin development docs must be complete and up-to-date.
|
||||
|
||||
## Deliverables Checklist
|
||||
|
||||
r[deliverables.binary]
|
||||
The CLI binary `ravenous-tools` must be distributable on crates.io and as a GitHub release.
|
||||
|
||||
r[deliverables.repo-skeleton]
|
||||
The `data/` repository scaffold must be created empty with a README.
|
||||
|
||||
r[deliverables.config-sample]
|
||||
`config/ravenous_tools_data.toml` (sample) must be provided with default values.
|
||||
|
||||
r[deliverables.latex-template]
|
||||
`templates/default_template.toml` must be available and referenceable.
|
||||
|
||||
r[deliverables.tests]
|
||||
Unit tests covering ≥90 % and integration tests for each sub-command must be included.
|
||||
|
||||
r[deliverables.ci-workflow]
|
||||
A complete ci integration must be provided.
|
||||
|
||||
r[deliverables.documentation]
|
||||
README, usage guide, API docs, and plugin interface docs must be comprehensive.
|
||||
|
||||
r[deliverables.plugin-interface]
|
||||
`ravenous_tools_plugin` crate exposing the trait must be published.
|
||||
|
||||
r[deliverables.example-plugin]
|
||||
An example plugin (e.g., custom metric calculator) must be distributed with the repo.
|
||||
|
||||
## Future Requirements
|
||||
|
||||
r[bulk.classes.export]
|
||||
The `export` command must accept one or several class names and generate tex files containing all requested classes.
|
||||
|
||||
r[bulk.parts.export]
|
||||
The `export` command must accept one or several parts types and generate tex files containing all requested parts.
|
||||
|
||||
r[bulk.objects.export]
|
||||
The `export` command must accept one or several objects types and generate tex files containing all requested objects.
|
||||
|
||||
r[graph.supported-types]
|
||||
Supported graph types include bar chart, line chart, heat-map, radar chart.
|
||||
|
||||
r[completion.bash]
|
||||
Auto-completion scripts for Bash must be installable via `install-completion` sub-command.
|
||||
|
||||
r[completion.zsh]
|
||||
Auto-completion scripts for Zsh must be installable via `install-completion` sub-command.
|
||||
|
||||
r[completion.fish]
|
||||
Auto-completion scripts for Fish must be installable via `install-completion` sub-command.
|
||||
|
||||
r[completion.powershell]
|
||||
Auto-completion scripts for PowerShell must be installable via `install-completion` sub-command.
|
||||
|
||||
r[logging.file]
|
||||
The `--log <path>` option must write structured logs (JSON-lines) to the specified file.
|
||||
|
||||
r[userstory.designer]
|
||||
Game designers must be able to add a new class with a single command and see it reflected immediately in exports.
|
||||
|
||||
r[acceptance.crud]
|
||||
All CRUD commands must correctly manipulate JSON files, with clear errors when classes are missing.
|
||||
|
|
@ -1,2 +0,0 @@
|
|||
[toolchain]
|
||||
channel = "stable"
|
||||
|
|
@ -0,0 +1,12 @@
|
|||
[package]
|
||||
name = "stats"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
config = {path = "../config"}
|
||||
cli_parser = {path = "../cli_parser"}
|
||||
anyhow = "1.0.95"
|
||||
csv = "1.3.1"
|
||||
debug_print = "1.0.0"
|
||||
serde = { version = "1.0.217", features = ["derive"] }
|
||||
|
|
@ -0,0 +1,19 @@
|
|||
[package]
|
||||
name = "tablegen"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
cli_parser = {path = "../cli_parser"}
|
||||
config = {path = "../config"}
|
||||
anyhow = "1.0.95"
|
||||
csv = "1.3.1"
|
||||
dynfmt = { version = "0.1.5", features = ["curly"] }
|
||||
glob = "0.3.2"
|
||||
phf = { version = "0.11.3", features = ["macros"] }
|
||||
regex = "1.11.1"
|
||||
regex_static = "0.1.1"
|
||||
serde = { version = "1.0.217", features = ["derive", "alloc"] }
|
||||
|
||||
[dev-dependencies]
|
||||
insta = { version = "1.42.2", features = ["yaml"] }
|
||||
|
|
@ -18,7 +18,7 @@
|
|||
//! The following functions are re-exported from the module `tablegen`:
|
||||
//!
|
||||
//! - [`table_gen`]: Handling the whole conversion and auto dispatch.
|
||||
|
||||
#![feature(coverage_attribute)]
|
||||
#![warn(missing_docs, clippy::missing_docs_in_private_items)]
|
||||
mod table_structs;
|
||||
mod table_types;
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
---
|
||||
source: tablegen/src/tablegen.rs
|
||||
expression: "make_latex_string(\"🩸⚡☽◅⧆Ø⌭☆🗘½0.5& ++ (++) (--) -★★★ ★★★ +★★★\")"
|
||||
---
|
||||
"\\blood{}\\gauge{}\\slash{}\\pierce{}\\blunt{}\\o{}\\torque{}\\ddzero{}\\reload{}\\sfrac{1}{2}\\sfrac{1}{2}\\& ++ $(++)$ $(--)$ \\ddmod{-}{3} \\ddlvl{3} \\ddmod{+}{3}"
|
||||
|
|
@ -8,6 +8,7 @@ use regex_static::once_cell::sync::Lazy;
|
|||
/// All the type of tsv that can be processed by the program
|
||||
// #[enum_dispatch]
|
||||
#[derive(Clone)]
|
||||
#[cfg_attr(test, derive(Debug, PartialEq))]
|
||||
pub enum TableTargets {
|
||||
/// A class tsv
|
||||
Classes,
|
||||
|
|
@ -51,3 +52,37 @@ pub(super) static RE_STARS: Lazy<Regex> = regex_static::lazy_regex!(r"★+");
|
|||
pub(super) static RE_PLUS_STARS: Lazy<Regex> = regex_static::lazy_regex!(r"([\+-])(★+)");
|
||||
/// The regex for finding all (+/-) and replacing them with mathmode
|
||||
pub(super) static RE_MATHS: Lazy<Regex> = regex_static::lazy_regex!(r"\([\+-]+\)");
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use crate::table_structs::{RE_MATHS, RE_PLUS_STARS, RE_STARS};
|
||||
|
||||
#[test]
|
||||
fn test_regex() {
|
||||
assert_eq!(RE_STARS.find("Bob ★★★★ zz").unwrap().as_str(), "★★★★");
|
||||
assert!(RE_STARS.find("Bob zz").is_none());
|
||||
|
||||
assert_eq!(
|
||||
RE_PLUS_STARS
|
||||
.captures("Bob +★★★★ zz")
|
||||
.unwrap()
|
||||
.get(2)
|
||||
.unwrap()
|
||||
.as_str(),
|
||||
"★★★★"
|
||||
);
|
||||
assert_eq!(
|
||||
RE_PLUS_STARS
|
||||
.captures("Bob -★★★★ zz")
|
||||
.unwrap()
|
||||
.get(2)
|
||||
.unwrap()
|
||||
.as_str(),
|
||||
"★★★★"
|
||||
);
|
||||
assert!(RE_PLUS_STARS.captures("Bob ★★★★ zz").is_none());
|
||||
assert_eq!(RE_MATHS.find("Bob (+++)").unwrap().as_str(), "(+++)");
|
||||
assert_eq!(RE_MATHS.find("Bob (--)").unwrap().as_str(), "(--)");
|
||||
assert!(RE_MATHS.find("Bob -- ++ ").is_none());
|
||||
}
|
||||
}
|
||||
|
|
@ -137,7 +137,7 @@ impl WriteTable for ClassesArray {
|
|||
continue;
|
||||
}
|
||||
if lvl != 0 {
|
||||
writeln!(buffer, "{}", config.classes.sep)?;
|
||||
writeln!(buffer, "{}", &config.classes.sep)?;
|
||||
}
|
||||
writeln!(buffer, "{}", formatted_tier)?;
|
||||
for elem in tier {
|
||||
|
|
@ -26,7 +26,7 @@
|
|||
//! This module consists of several submodules:
|
||||
//! - `table_structs`: Defines the structure and behavior of tables.
|
||||
//! - `table_types`: Contains types related to TSV files and LaTeX code generation.
|
||||
use anyhow::{Context, Result};
|
||||
use anyhow::{Context, Result, anyhow};
|
||||
use config::tablegen::{TableArgs, TableGenerationTarget};
|
||||
use glob::glob;
|
||||
use regex::Captures;
|
||||
|
|
@ -46,6 +46,7 @@ use crate::{
|
|||
/// Generate the tables for the specified files
|
||||
///
|
||||
/// In charge of the dispatch and the whole conversion
|
||||
#[coverage(off)] // DISPATCH: Can't cover a dispatch
|
||||
pub fn table_gen(args: &TableArgs, config: &Config) -> Result<()> {
|
||||
let list_files = match args.kind {
|
||||
TableGenerationTarget::Classes => {
|
||||
|
|
@ -83,6 +84,7 @@ pub fn table_gen(args: &TableArgs, config: &Config) -> Result<()> {
|
|||
}
|
||||
|
||||
/// Process any type of file, one by one and call the right converter function
|
||||
#[coverage(off)] // IO: This function does I/O and can't be tested
|
||||
fn process_files(list_files: &mut Vec<PathBuf>, args: &TableArgs, config: &Config) -> Result<()> {
|
||||
for f in list_files {
|
||||
if let Err(e) = process_one_file(f, args, config) {
|
||||
|
|
@ -93,6 +95,7 @@ fn process_files(list_files: &mut Vec<PathBuf>, args: &TableArgs, config: &Confi
|
|||
}
|
||||
|
||||
/// Process one file
|
||||
#[coverage(off)] // IO: This function does I/O and can't be tested
|
||||
fn process_one_file(f: &mut PathBuf, args: &TableArgs, config: &Config) -> Result<()> {
|
||||
let tt = extract_type(f)?;
|
||||
let tsv: Box<dyn WriteTable> = match tt {
|
||||
|
|
@ -107,13 +110,18 @@ fn process_one_file(f: &mut PathBuf, args: &TableArgs, config: &Config) -> Resul
|
|||
}
|
||||
|
||||
#[inline]
|
||||
#[coverage(off)] // INLINE: The coverage is badly reported it is however covered in the testing scenario
|
||||
/// Extract the type of target of the given file
|
||||
fn extract_type(f: &Path) -> Result<&TableTargets> {
|
||||
let key = &f
|
||||
.file_name()
|
||||
.context("The filename of can't be extracted...skipping")?
|
||||
.to_str()
|
||||
.context("Can't convert filename to string")?[7..10];
|
||||
.context("Can't convert filename to string")?;
|
||||
if key.len() < 10 {
|
||||
return Err(anyhow!("Filename doens't have the correct formatting"));
|
||||
}
|
||||
let key = &key[7..10]; // TODO[!]: Horrible practice, clean this
|
||||
STR_TO_TARGET_FULL.get(key).with_context(|| {
|
||||
format!(
|
||||
"Could not find the type of file given based on the prefix of your file ({})\n\
|
||||
|
|
@ -128,6 +136,7 @@ fn extract_type(f: &Path) -> Result<&TableTargets> {
|
|||
|
||||
/// List all files matching a pattern in the given directory
|
||||
#[inline]
|
||||
#[coverage(off)] // IO: This function does I/O and can't be tested
|
||||
fn list_dir(pattern: &str) -> Vec<PathBuf> {
|
||||
// println!("{}", pattern);
|
||||
// println!("{:?}", glob(pattern));
|
||||
|
|
@ -143,6 +152,7 @@ fn list_dir(pattern: &str) -> Vec<PathBuf> {
|
|||
/// This function reads in a TSV file, processes its contents according to the provided configuration,
|
||||
/// and writes out the resulting LaTeX code as a string. If an error occurs during processing or writing,
|
||||
/// it will be returned as part of the result.
|
||||
#[coverage(off)] // BAD_IO: This function does I/O and can't be tested
|
||||
pub fn export_tsv(
|
||||
f: &Path,
|
||||
tsv: Box<dyn WriteTable>,
|
||||
|
|
@ -197,6 +207,7 @@ pub(super) fn make_latex_string(arg: &str) -> String {
|
|||
///
|
||||
/// This function reads in a tab-separated values (TSV) file and returns it as a Table object,
|
||||
/// which can be used to generate LaTeX code or perform other operations on the data.
|
||||
#[coverage(off)] // BAD_IO: This function does I/O and can't be tested
|
||||
fn read_tsv_classes<T>(filename: &T) -> Result<ClassesArray, Error>
|
||||
where
|
||||
T: AsRef<Path>,
|
||||
|
|
@ -231,6 +242,7 @@ where
|
|||
/// Reads a TSV file into a table.
|
||||
///
|
||||
/// Reads a tab-separated values (TSV) file and deserializes its contents into a table.
|
||||
#[coverage(off)] // BAD_IO: This function does I/O and can't be tested
|
||||
fn read_generic_tsv(filename: &Path, craft_type: &TableTargets) -> Result<Box<dyn WriteTable>> {
|
||||
let file = File::open(filename)?;
|
||||
let rdr = csv::ReaderBuilder::new()
|
||||
|
|
@ -259,6 +271,7 @@ fn read_generic_tsv(filename: &Path, craft_type: &TableTargets) -> Result<Box<dy
|
|||
///
|
||||
/// This function takes in a Table object and returns its contents as a formatted string,
|
||||
/// which can be used to generate LaTeX code or perform other operations on the data.
|
||||
#[coverage(off)] // BAD_IO: This function does I/O and can't be tested
|
||||
pub(super) fn tsv_to_string(tsv: Box<dyn WriteTable>, config: &Config) -> Result<String> {
|
||||
tsv.write_table(config)
|
||||
}
|
||||
|
|
@ -289,3 +302,66 @@ pub(super) fn tsv_to_string(tsv: Box<dyn WriteTable>, config: &Config) -> Result
|
|||
// let craft_array = CraftArray { row: levels };
|
||||
// Ok(Box::new(craft_array))
|
||||
// }
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use std::path::Path;
|
||||
|
||||
use crate::{table_structs::TableTargets, tablegen::extract_type};
|
||||
|
||||
use super::make_latex_string;
|
||||
|
||||
#[test]
|
||||
fn test_str_clean() {
|
||||
insta::assert_yaml_snapshot!(make_latex_string(
|
||||
"🩸⚡☽◅⧆Ø⌭☆🗘½0.5& ++ (++) (--) -★★★ ★★★ +★★★"
|
||||
));
|
||||
}
|
||||
#[test]
|
||||
fn test_extension() {
|
||||
Path::new("");
|
||||
|
||||
assert!(extract_type(Path::new("short")).is_err());
|
||||
assert_eq!(
|
||||
extract_type(Path::new("000000-cls")).unwrap(),
|
||||
&TableTargets::Classes
|
||||
);
|
||||
assert_eq!(
|
||||
extract_type(Path::new("000000-fud")).unwrap(),
|
||||
&TableTargets::Food
|
||||
);
|
||||
assert_eq!(
|
||||
extract_type(Path::new("000000-alc")).unwrap(),
|
||||
&TableTargets::Alchemy
|
||||
);
|
||||
assert_eq!(
|
||||
extract_type(Path::new("000000-frg")).unwrap(),
|
||||
&TableTargets::Forge
|
||||
);
|
||||
assert_eq!(
|
||||
extract_type(Path::new("000000-mpi")).unwrap(),
|
||||
&TableTargets::MPieges
|
||||
);
|
||||
assert_eq!(
|
||||
extract_type(Path::new("000000-wpn")).unwrap(),
|
||||
&TableTargets::Weapons
|
||||
);
|
||||
assert_eq!(
|
||||
extract_type(Path::new("000000-arm")).unwrap(),
|
||||
&TableTargets::Armors
|
||||
);
|
||||
assert_eq!(
|
||||
extract_type(Path::new("000000-gdg")).unwrap(),
|
||||
&TableTargets::Gadgets
|
||||
);
|
||||
assert_eq!(
|
||||
extract_type(Path::new("000000-pot")).unwrap(),
|
||||
&TableTargets::Potions
|
||||
);
|
||||
assert_eq!(
|
||||
extract_type(Path::new("000000-trp")).unwrap(),
|
||||
&TableTargets::Traps
|
||||
);
|
||||
assert!(extract_type(Path::new("000000-bad")).is_err());
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,32 @@
|
|||
[package]
|
||||
name = "weaponry"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
more_fields = {path ="../more_fields"}
|
||||
comfy-table = "7.1.4"
|
||||
csv = "1.3.1"
|
||||
probability = "0.20.3"
|
||||
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"] }
|
||||
strum = { version = "0.27.0", features = ["derive"] }
|
||||
thiserror = "2.0.11"
|
||||
regex = "1.11.1"
|
||||
charming = { version = "0.4.0", features = [] }
|
||||
|
||||
[dev-dependencies]
|
||||
fastrand = "2.3.0"
|
||||
criterion = { version = "0.5" }
|
||||
regex = "1.11.1"
|
||||
pretty_assertions = "^1.4"
|
||||
logos = "^0.15"
|
||||
clap = { version = "4.5.30", features = ["derive"] }
|
||||
insta = { version = "1.42.2", features = ["yaml"] }
|
||||
|
||||
[[bench]]
|
||||
name = "iter_creation"
|
||||
harness = false
|
||||
|
||||
Binary file not shown.
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue