Compare commits
296 Commits
| Author | SHA1 | Date |
|---|---|---|
|
|
342b2105c6 | |
|
|
8238a4bf2f | |
|
|
26b4b31684 | |
|
|
dd9999b347 | |
|
|
4dc5a5f03e | |
|
|
61206c7a88 | |
|
|
a9dc404da0 | |
|
|
2bfccc4175 | |
|
|
395c03621f | |
|
|
b5f4b8daf0 | |
|
|
ba8e6c09f3 | |
|
|
d7914c6eaa | |
|
|
f34d581522 | |
|
|
c008e16556 | |
|
|
daf65e8a27 | |
|
|
cec31c6689 | |
|
|
9408152f98 | |
|
|
29a1c93f3f | |
|
|
8ff115e593 | |
|
|
55960bffbd | |
|
|
d58ddc9349 | |
|
|
05092c354f | |
|
|
a449407ab4 | |
|
|
70cde5aa52 | |
|
|
c5481210d8 | |
|
|
44db2ca294 | |
|
|
7be200c749 | |
|
|
9ae9471ccd | |
|
|
7f5c09ae36 | |
|
|
a3b0f4a744 | |
|
|
9ca9e49a8e | |
|
|
c91ca2f26f | |
|
|
41fead32a4 | |
|
|
264fadfdc8 | |
|
|
886f139bbb | |
|
|
a0f05fb638 | |
|
|
3b9bd39a5a | |
|
|
854020118b | |
|
|
f5e63b9b89 | |
|
|
f659bebc9a | |
|
|
3d211b711a | |
|
|
54688cb74f | |
|
|
d50a22d3f8 | |
|
|
483dc1003f | |
|
|
2235357925 | |
|
|
c74de46f8b | |
|
|
59a78f4236 | |
|
|
4ff3d2c992 | |
|
|
4ac2146b13 | |
|
|
7ec926432e | |
|
|
1c216df46d | |
|
|
c06ca05151 | |
|
|
bcf01e2004 | |
|
|
161a7d2ab4 | |
|
|
536ef42d70 | |
|
|
6da458a236 | |
|
|
55f5fe10d2 | |
|
|
eb63fb0806 | |
|
|
885a1caaf6 | |
|
|
08a1697345 | |
|
|
27debbf153 | |
|
|
789b925400 | |
|
|
f1337b1678 | |
|
|
5600804ab4 | |
|
|
8a655d2a69 | |
|
|
c3c0309948 | |
|
|
1caff57923 | |
|
|
62e459e5bd | |
|
|
2e12f9708d | |
|
|
e0be27ae6f | |
|
|
abe9db7c0b | |
|
|
d01ce27d5b | |
|
|
7e021d644a | |
|
|
209c24aab2 | |
|
|
572ad159a2 | |
|
|
08a66bf2b8 | |
|
|
f86199d497 | |
|
|
006ebe9a0b | |
|
|
37a6531ae4 | |
|
|
46b8e35254 | |
|
|
1e0c6dfb53 | |
|
|
529f90b93e | |
|
|
707dc2e223 | |
|
|
2258fa4267 | |
|
|
020dca43bd | |
|
|
8ac1f053b7 | |
|
|
40e0885a78 | |
|
|
c11ce3d21c | |
|
|
3460841ed7 | |
|
|
222cd14d29 | |
|
|
6ca8033308 | |
|
|
a2cb6434b1 | |
|
|
094d4b78e0 | |
|
|
cf71d6b8cb | |
|
|
77d224418f | |
|
|
e5217b09d8 | |
|
|
321051a443 | |
|
|
0611883f85 | |
|
|
40077a9fe3 | |
|
|
dc918ccb8b | |
|
|
30bc8bb9a1 | |
|
|
12d0128d97 | |
|
|
2e81b6f1d2 | |
|
|
979254cb0b | |
|
|
493c5742e7 | |
|
|
16844dba07 | |
|
|
db22d38b98 | |
|
|
dbb44dffb4 | |
|
|
df688646de | |
|
|
11e5c6c5c5 | |
|
|
4cf73ff243 | |
|
|
d451b99a48 | |
|
|
697facab40 | |
|
|
30057dd7cf | |
|
|
3b94b71782 | |
|
|
fadd82ff3b | |
|
|
d7e7ffcb17 | |
|
|
b855455596 | |
|
|
5a84833922 | |
|
|
4f2bb22420 | |
|
|
b493381390 | |
|
|
6d080230ee | |
|
|
93d1bbbbe7 | |
|
|
4380ad5591 | |
|
|
eaed13f320 | |
|
|
01842fc64a | |
|
|
352940486e | |
|
|
6526d16451 | |
|
|
b5fb986b5f | |
|
|
32ff0ef115 | |
|
|
e99d723e5d | |
|
|
9cbdc25df4 | |
|
|
b6de1aa1cd | |
|
|
18c864efe5 | |
|
|
788f9fb112 | |
|
|
101b8c778a | |
|
|
56289649a4 | |
|
|
cb6c7ebc2a | |
|
|
21618a8782 | |
|
|
ab6515c742 | |
|
|
8a2114da74 | |
|
|
f726b7ce15 | |
|
|
8825587e53 | |
|
|
f3bb2c9d80 | |
|
|
5b3972a906 | |
|
|
04bc4d57ec | |
|
|
a231dfdd19 | |
|
|
fde34be744 | |
|
|
7f98215bc2 | |
|
|
bb3041ed8d | |
|
|
06b8fa7979 | |
|
|
22b46f6c07 | |
|
|
a2269ccb87 | |
|
|
5738f0fd74 | |
|
|
58061b8b9b | |
|
|
c97425cb6f | |
|
|
8bb6d09b15 | |
|
|
3af43de27e | |
|
|
dfa806acef | |
|
|
c9c6cbe40e | |
|
|
d9ab10c0a7 | |
|
|
72edbd4cf0 | |
|
|
36c7c8050b | |
|
|
65502297b7 | |
|
|
84564a9199 | |
|
|
433054dd7e | |
|
|
cef4741a0f | |
|
|
d4723e828e | |
|
|
02c76ca33a | |
|
|
d8d976dcdc | |
|
|
ece331b2b2 | |
|
|
27a9f1cb5c | |
|
|
45c31c23b4 | |
|
|
8389b21aec | |
|
|
bb39660f6c | |
|
|
a0b0012d76 | |
|
|
f044d26a10 | |
|
|
bfe9285b43 | |
|
|
862021e0b2 | |
|
|
a5d44b82e4 | |
|
|
813747d643 | |
|
|
22d60f5559 | |
|
|
f5534a77a2 | |
|
|
9d8beaf9b3 | |
|
|
1505a6c6f7 | |
|
|
26d22037ae | |
|
|
a5f796d2dd | |
|
|
6cc0f27d3d | |
|
|
a512e0518d | |
|
|
b69206212c | |
|
|
ddb70c1cb3 | |
|
|
06c74639ff | |
|
|
36e1b84ae8 | |
|
|
c945ebccf0 | |
|
|
91c5c4bb37 | |
|
|
495607efb4 | |
|
|
a7f4ceb007 | |
|
|
6f1b2d98fa | |
|
|
5d514d3d33 | |
|
|
9facac6b9f | |
|
|
603a1cd8b6 | |
|
|
4b4d39257a | |
|
|
9e1521e373 | |
|
|
2c44cdd817 | |
|
|
9786323e53 | |
|
|
53de64946f | |
|
|
69fcf1dffb | |
|
|
d27cc588b1 | |
|
|
5279365511 | |
|
|
95f7998e5c | |
|
|
d3ccc315c1 | |
|
|
1311c7c7c0 | |
|
|
f9736ffa1f | |
|
|
75a88508f2 | |
|
|
8f71a9c01d | |
|
|
6756a98a4c | |
|
|
edd3d17be4 | |
|
|
cbff7ea169 | |
|
|
c393f8e264 | |
|
|
9d302d4d45 | |
|
|
725cd9cfc4 | |
|
|
95fb8b6a06 | |
|
|
02d92e4a99 | |
|
|
bb0cdffaee | |
|
|
82b9515a8e | |
|
|
c98b8f52d4 | |
|
|
791108e58d | |
|
|
ddb8167676 | |
|
|
b1ce4c43bb | |
|
|
8e982eb734 | |
|
|
3132cd98f5 | |
|
|
c344e96517 | |
|
|
945ec489c5 | |
|
|
53d8ab77dd | |
|
|
0f0ec8c8f0 | |
|
|
2ece26aac0 | |
|
|
fb6aee97d9 | |
|
|
7796dcbadd | |
|
|
ed34e2bf60 | |
|
|
6b303294f1 | |
|
|
e31a7fd33b | |
|
|
b0b654b056 | |
|
|
3d44f04926 | |
|
|
5e4b24eb5c | |
|
|
a515238651 | |
|
|
3a79972371 | |
|
|
69439f56f4 | |
|
|
6a48178549 | |
|
|
fb8b8b0dbf | |
|
|
e6fd22db8d | |
|
|
bccae62b3a | |
|
|
8dab7c6760 | |
|
|
a7f087dd0a | |
|
|
62f3a356c1 | |
|
|
3a5583ea99 | |
|
|
cfa16aa1c8 | |
|
|
a05b8c309b | |
|
|
8f113ffdc3 | |
|
|
8b110c9d6d | |
|
|
9ee72e03b3 | |
|
|
2cc32f41ce | |
|
|
47c7735a67 | |
|
|
5394cc0c51 | |
|
|
afee1540cc | |
|
|
e724a81781 | |
|
|
40b884146b | |
|
|
79fc453246 | |
|
|
2d61155b20 | |
|
|
18374ec459 | |
|
|
0f81bb4d42 | |
|
|
5158360fb5 | |
|
|
fa4cf4be29 | |
|
|
51f5e6753e | |
|
|
d4d137b8cf | |
|
|
abf04e4fef | |
|
|
621e82e8b6 | |
|
|
589047baef | |
|
|
fa5d8c9057 | |
|
|
2dd8d54c3b | |
|
|
dc84016969 | |
|
|
6186d9ab18 | |
|
|
cc5af1907c | |
|
|
333d5e6981 | |
|
|
cd64e4423b | |
|
|
658c6e1e7b | |
|
|
b769294c06 | |
|
|
61c0a344d8 | |
|
|
d1a615a7ed | |
|
|
1e56dc9e5e | |
|
|
0f97616dfd | |
|
|
6c60a76b88 | |
|
|
c4a6c50951 | |
|
|
18cc6cd48e | |
|
|
a3eed1c989 | |
|
|
92c6f5ece0 | |
|
|
2b13830ffd |
|
|
@ -1,2 +0,0 @@
|
|||
[build]
|
||||
rustflags = ["-Clink-arg=-fuse-ld=lld", "-Ctarget-cpu=native"]
|
||||
|
|
@ -0,0 +1,12 @@
|
|||
specs:
|
||||
- name: base
|
||||
prefix: r
|
||||
source_url: "https://github.com/bearcove/tracey"
|
||||
include:
|
||||
- "requirements/**/*.md"
|
||||
impls:
|
||||
- name: main
|
||||
include:
|
||||
- "crates/**/*.rs"
|
||||
exclude:
|
||||
- "target/**"
|
||||
|
|
@ -16,8 +16,16 @@ 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
|
||||
*.bkp
|
||||
coverage/
|
||||
|
|
|
|||
|
|
@ -0,0 +1,4 @@
|
|||
[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
|
||||
|
|
@ -0,0 +1,8 @@
|
|||
[last_run_clean]
|
||||
run_status = "Success"
|
||||
lines_parsed = 151
|
||||
coverage = 20.88
|
||||
|
||||
[last_run_clean.run_duration]
|
||||
secs = 22
|
||||
nanos = 771992149
|
||||
82
Cargo.toml
82
Cargo.toml
|
|
@ -1,20 +1,18 @@
|
|||
cargo-features = ["codegen-backend"]
|
||||
[package]
|
||||
name = "ravenous-tools"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
[workspace]
|
||||
members = ["crates/*"]
|
||||
resolver = "3"
|
||||
|
||||
# [workspace.package]
|
||||
# edition = "2024"
|
||||
# license = "MIT OR Apache-2.0"
|
||||
[workspace.package]
|
||||
version = "0.3.34"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
clap = { version = "4.5.4", features = ["derive"] }
|
||||
csv = "1.3.0"
|
||||
regex = "1.10.4"
|
||||
serde = { version = "1.0.198", features = ["derive"] }
|
||||
|
||||
[profile.dev]
|
||||
debug = 0
|
||||
codegen-backend = "cranelift"
|
||||
# codegen-backend = "cranelift"
|
||||
|
||||
[profile.release]
|
||||
lto = true
|
||||
|
|
@ -22,12 +20,56 @@ codegen-units = 1
|
|||
panic = "abort"
|
||||
strip = "none"
|
||||
|
||||
[profile.windows]
|
||||
inherits = "release"
|
||||
opt-level = "z"
|
||||
debug = false
|
||||
strip = true
|
||||
lto = true
|
||||
codegen-units = 1
|
||||
incremental = false
|
||||
[profile.fast]
|
||||
inherits = "dev"
|
||||
opt-level = 0
|
||||
debug = 0
|
||||
strip = "none"
|
||||
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"
|
||||
|
|
|
|||
|
|
@ -0,0 +1,69 @@
|
|||
// 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'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -0,0 +1,62 @@
|
|||
# Future tools
|
||||
[ ] Lexer/Checker
|
||||
|
||||
## Lexer
|
||||
` Command: grammar --check `
|
||||
|
||||
Tries to do a quick grammar check and locate errors
|
||||
|
||||
* https://brunocalza.me/writing-a-simple-lexer-in-rust/
|
||||
* https://github.com/goffrie/plex
|
||||
|
||||
### Logos, fast lexer
|
||||
|
||||
* https://crates.io/crates/logos
|
||||
```rust
|
||||
use logos::Logos;
|
||||
|
||||
#[derive(Logos, Debug, PartialEq)]
|
||||
#[logos(skip r"[ \t\n\f]+")] // Ignore this regex pattern between tokens
|
||||
enum Token {
|
||||
// Tokens can be literal strings, of any length.
|
||||
#[token("fast")]
|
||||
Fast,
|
||||
|
||||
#[token(".")]
|
||||
Period,
|
||||
|
||||
// Or regular expressions.
|
||||
#[regex("[a-zA-Z]+")]
|
||||
Text,
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
|
||||
### Chumsky, full parser
|
||||
|
||||
```rust
|
||||
use chumsky::prelude::*;
|
||||
|
||||
#[derive(Clone)]
|
||||
enum Instr {
|
||||
Left, Right,
|
||||
Incr, Decr,
|
||||
Read, Write,
|
||||
Loop(Vec<Self>),
|
||||
}
|
||||
|
||||
fn parser() -> impl Parser<char, Vec<Instr>, Error = Simple<char>> {
|
||||
recursive(|bf| choice((
|
||||
just('<').to(Instr::Left),
|
||||
just('>').to(Instr::Right),
|
||||
just('+').to(Instr::Incr),
|
||||
just('-').to(Instr::Decr),
|
||||
just(',').to(Instr::Read),
|
||||
just('.').to(Instr::Write),
|
||||
bf.delimited_by(just('['), just(']')).map(Instr::Loop),
|
||||
))
|
||||
.repeated())
|
||||
}
|
||||
```
|
||||
|
||||
|
|
@ -1,3 +1,10 @@
|
|||
 
|
||||
|
||||
# ravenous-tools
|
||||
|
||||
Set of tools to handle ravenous rulebook creation
|
||||
Set of tools to handle ravenous rulebook creation
|
||||
|
||||
# Installation
|
||||
Now depends on libsqlite3-dev and sqlite3
|
||||
A bundled implementation should be added on all releases
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,5 @@
|
|||
# TODO
|
||||
* Remake graphs
|
||||
* Remake export
|
||||
* Remake dashboard
|
||||
|
||||
|
|
@ -0,0 +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>
|
||||
|
After Width: | Height: | Size: 1.3 KiB |
|
|
@ -0,0 +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>
|
||||
|
After Width: | Height: | Size: 1.3 KiB |
|
|
@ -0,0 +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>
|
||||
|
After Width: | Height: | Size: 1.3 KiB |
|
|
@ -0,0 +1,9 @@
|
|||
[package]
|
||||
name = "cli_parser"
|
||||
version.workspace = true
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
config = {workspace = true}
|
||||
clap = {workspace = true}
|
||||
serde = {workspace = true}
|
||||
|
|
@ -0,0 +1,151 @@
|
|||
//! The usual cli parser shenenigans
|
||||
//!
|
||||
#![warn(missing_docs, clippy::missing_docs_in_private_items)]
|
||||
|
||||
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},
|
||||
statsolver::StatConfig,
|
||||
tablegen::{Craft, TableArgs},
|
||||
};
|
||||
use serde::Deserialize;
|
||||
|
||||
// use graphs::{GraphConfig, make_graphs};
|
||||
// use makepdf::{MakeConfig, make_pdf};
|
||||
// use stats::{StatConfig, stat_solver};
|
||||
// use table_structs::Craft;
|
||||
|
||||
#[derive(Parser, Debug)]
|
||||
#[command(version, about)]
|
||||
#[command(propagate_version = true)]
|
||||
/// The list of commands to run
|
||||
pub struct ParserCLIArgs {
|
||||
/// The subcommand to run.
|
||||
#[command(subcommand)]
|
||||
pub command: Commands,
|
||||
}
|
||||
|
||||
#[derive(Subcommand, Debug)]
|
||||
/// Enum representing the available commands.
|
||||
pub enum Commands {
|
||||
/// Generate a table from input data using the provided arguments.
|
||||
Tablegen(TableArgs),
|
||||
/// Show/Export config
|
||||
Config(ConfigArgs),
|
||||
/// Handle stat repartition
|
||||
Stats(StatConfig),
|
||||
/// Make a pdf via pdflatex
|
||||
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),
|
||||
}
|
||||
|
||||
#[derive(Debug, Args)]
|
||||
/// Genrate the config file with the specified arguments
|
||||
pub struct ConfigArgs {
|
||||
/// Wether to write the config to file, or just show it
|
||||
#[arg(short, long, default_value_t = false)]
|
||||
pub write: bool,
|
||||
|
||||
/// Wether to overwrite the file if it exists
|
||||
#[arg(short, long, default_value_t = false)]
|
||||
pub force: bool,
|
||||
|
||||
/// The path to overwrite to
|
||||
pub path: Option<String>,
|
||||
}
|
||||
|
||||
#[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)]
|
||||
/// The classes config
|
||||
pub struct Classes {
|
||||
/// The header string formatter
|
||||
pub header: String,
|
||||
/// The row string formatter
|
||||
pub tier: String,
|
||||
/// The row string separator
|
||||
pub sep: String,
|
||||
/// The table end string formatter
|
||||
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)]
|
||||
/// The configuration struct for the PdfMaker
|
||||
pub struct MakeConfig {
|
||||
/// The filename to compile
|
||||
pub filename: String,
|
||||
|
||||
/// Special target
|
||||
#[arg(short, long)]
|
||||
pub target: Option<MakeTargets>,
|
||||
|
||||
/// The verbosity level
|
||||
#[arg(short, long, default_value = "warning")]
|
||||
pub verbosity: VerboseLevel,
|
||||
|
||||
/// The progress bar style
|
||||
#[arg(short, long, default_value = "class", help = format!("The progress bar style. [{}]",HELP_BLOCK_SELECTION.as_str()))]
|
||||
pub pbar: String,
|
||||
|
||||
/// switch to non interactive mode
|
||||
#[arg(short = 'N', long, default_value_t = false)]
|
||||
pub non_interactive: bool,
|
||||
|
||||
/// Select only these targets
|
||||
#[arg(short, long, value_name = "FILE", group = "select")]
|
||||
pub only: Vec<String>,
|
||||
|
||||
/// Deselect these targets
|
||||
#[arg(short, long, value_name = "FILE", group = "select")]
|
||||
pub no: Vec<String>,
|
||||
|
||||
/// Wether to add the initial and final context
|
||||
#[arg(short = 'C', long, action = clap::ArgAction::SetFalse)]
|
||||
pub no_context: bool,
|
||||
|
||||
/// 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,11 @@
|
|||
[package]
|
||||
name = "config"
|
||||
version.workspace = true
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
clap = {workspace = true}
|
||||
serde = {workspace = true}
|
||||
phf = {workspace = true}
|
||||
indexmap = {workspace = true}
|
||||
anyhow = {workspace = true}
|
||||
|
|
@ -0,0 +1,76 @@
|
|||
// 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,
|
||||
}
|
||||
|
|
@ -0,0 +1,57 @@
|
|||
//! # `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,
|
||||
}
|
||||
|
|
@ -0,0 +1,17 @@
|
|||
// 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,
|
||||
}
|
||||
|
|
@ -0,0 +1,237 @@
|
|||
// 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()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,17 @@
|
|||
// Workspace: config
|
||||
// File: config/src/lib.rs
|
||||
//! Holds config and traits
|
||||
//!
|
||||
//! Also write configs to disk
|
||||
|
||||
#![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,71 @@
|
|||
// 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,
|
||||
}
|
||||
|
|
@ -0,0 +1,178 @@
|
|||
// 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(),
|
||||
})
|
||||
}
|
||||
|
|
@ -0,0 +1,16 @@
|
|||
// Workspace: config
|
||||
// File: config/src/statsolver.rs
|
||||
//! Statsolver Structs
|
||||
|
||||
use clap::Args;
|
||||
|
||||
#[derive(Args, Debug, Clone)]
|
||||
/// The configuration struct for the StatSolver
|
||||
pub struct StatConfig {
|
||||
// #[arg(default_value_t: "data/Book1.csv")]
|
||||
/// The path where the data to analyse is
|
||||
pub config_path: String,
|
||||
/// The verbosity level
|
||||
#[arg(short, long, default_value_t = false)]
|
||||
pub verbosity: bool,
|
||||
}
|
||||
|
|
@ -0,0 +1,65 @@
|
|||
// 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,
|
||||
}
|
||||
|
|
@ -0,0 +1,10 @@
|
|||
[package]
|
||||
name = "fast_class"
|
||||
version.workspace = true
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
config = {workspace = true}
|
||||
cli_parser = {workspace = true}
|
||||
anyhow = {workspace = true}
|
||||
facet = "0.46.5"
|
||||
|
|
@ -0,0 +1,139 @@
|
|||
//! # 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
|
||||
//
|
||||
|
|
@ -0,0 +1,12 @@
|
|||
[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}
|
||||
|
|
@ -0,0 +1,99 @@
|
|||
//! 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(())
|
||||
}
|
||||
|
|
@ -0,0 +1,8 @@
|
|||
//! 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;
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
[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}
|
||||
|
|
@ -0,0 +1,388 @@
|
|||
//! The module `graphs` is responsible for exporting graphs based on CSV data
|
||||
//!
|
||||
//! # Usage
|
||||
//!
|
||||
//! - [`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 cli_parser::Config;
|
||||
use config::graph::{FinalClassRadar, GraphConfig, GraphTargetType, LoadedClassRadar, RawRow};
|
||||
use glob::glob;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{
|
||||
fs::File,
|
||||
io::{Read, Write},
|
||||
iter,
|
||||
path::{Path, PathBuf},
|
||||
process::Command,
|
||||
};
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
|
||||
/// Main action dispatch for the graph make
|
||||
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),
|
||||
}
|
||||
}
|
||||
|
||||
/// Initialize the config on the main directory
|
||||
fn init_graph_config(_args: &GraphConfig) -> Result<()> {
|
||||
let mut f = File::create("graph_config.ron")?;
|
||||
let theme = MiniTheme::new();
|
||||
f.write_all(
|
||||
ron::ser::to_string_pretty(&theme, ron::ser::PrettyConfig::default())
|
||||
.context("Converting to toml")?
|
||||
.as_bytes(),
|
||||
)
|
||||
.context("Writing to file")?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 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);
|
||||
let mut f = File::open(c).context("Opening config")?;
|
||||
let mut buf = String::new();
|
||||
f.read_to_string(&mut buf).context("Reading the config")?;
|
||||
Ok(ron::from_str(buf.as_str()).context("Deserializing config")?)
|
||||
} else {
|
||||
println!("[INFO] Loading default config");
|
||||
Ok(MiniTheme::new())
|
||||
}
|
||||
}
|
||||
/// Delete the existing graphs
|
||||
fn del_graphs(args: &GraphConfig) -> Result<()> {
|
||||
let mut cmd = Command::new("rm");
|
||||
cmd.args(
|
||||
glob("Images/Radar/*.svg")?
|
||||
.map(|v| v.unwrap().to_str().unwrap().to_string())
|
||||
.collect::<Vec<String>>(),
|
||||
);
|
||||
|
||||
if args.all {
|
||||
cmd.args(
|
||||
glob("Images/Radar/*.png")?
|
||||
.map(|v| v.unwrap().to_str().unwrap().to_string())
|
||||
.collect::<Vec<String>>(),
|
||||
);
|
||||
}
|
||||
|
||||
if let Err(e) = cmd.output() {
|
||||
println!(
|
||||
"[ERRR] An error has occured when executing the remove target \n {:#?}",
|
||||
e
|
||||
)
|
||||
}
|
||||
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
|
||||
fn gen_graph(args: &GraphConfig) -> Result<()> {
|
||||
// Import CSV
|
||||
let data = include_bytes!("../../../data/lmroman8-regular.ttf") as &[u8];
|
||||
get_or_try_init_fonts(Some(vec![data])).unwrap();
|
||||
|
||||
let csv = import_csv(args)?;
|
||||
|
||||
let maxv = &csv.max;
|
||||
|
||||
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!("[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())?;
|
||||
|
||||
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")?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Import the default csv
|
||||
fn import_csv(args: &GraphConfig) -> Result<GraphValues> {
|
||||
let file = File::open(&args.origin)
|
||||
.context("Opening the radar file")
|
||||
.unwrap();
|
||||
let rdr = csv::ReaderBuilder::new().from_reader(file);
|
||||
|
||||
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
|
||||
// max: Vec<(String, f32)>,
|
||||
max: Vec<RadarIndicator>,
|
||||
|
||||
/// The list of all character and associated values
|
||||
// values: Vec<(String, Vec<f32>)>,
|
||||
values: Vec<Series>,
|
||||
}
|
||||
|
||||
/// Cleanup the given csv to output usable data
|
||||
fn cleanup_csv(mut rdr: csv::Reader<File>) -> Result<GraphValues> {
|
||||
let headers = rdr.headers().context("Opening headers")?;
|
||||
// Making the max/base vec
|
||||
|
||||
// Gathering all the different category names
|
||||
let headers = headers
|
||||
.iter()
|
||||
.filter(|v| !v.is_empty())
|
||||
.skip(1)
|
||||
.map(|v| v.to_string())
|
||||
.collect::<Vec<String>>();
|
||||
|
||||
// Gather all the different categories
|
||||
let mut rdr = rdr.records();
|
||||
|
||||
// Calculate the max values
|
||||
let maxvals: Vec<f32> = rdr
|
||||
.next()
|
||||
.context("Gathering max values")??
|
||||
.iter()
|
||||
.map(|v| v.parse::<f32>().unwrap_or(0.0))
|
||||
.skip(1)
|
||||
.collect();
|
||||
|
||||
// Calculate all the values of all graphs
|
||||
let mut res = Vec::new();
|
||||
for line in rdr {
|
||||
let line = line.context("Parsing table lines")?;
|
||||
let name = line
|
||||
.get(0)
|
||||
.context("Fetching name for character")?
|
||||
.to_string()
|
||||
.replace(" ", "_")
|
||||
.replace("î", "i")
|
||||
.to_lowercase()
|
||||
.replace("é", "e");
|
||||
let vals: Vec<f32> = line
|
||||
.iter()
|
||||
.skip(1)
|
||||
.enumerate()
|
||||
.map(|(i, v)| {
|
||||
v.parse::<f32>().unwrap_or(0.0) * 5.0
|
||||
/ maxvals.get(i).context("Fetching max value").unwrap()
|
||||
})
|
||||
.collect();
|
||||
res.push(Series::new(name, vals));
|
||||
}
|
||||
|
||||
Ok(GraphValues {
|
||||
max: headers
|
||||
.iter()
|
||||
.map(|v| v.to_owned())
|
||||
.zip(iter::repeat(5.0f32))
|
||||
.map(|(name, max)| RadarIndicator { name, max })
|
||||
.collect::<Vec<RadarIndicator>>(),
|
||||
values: res,
|
||||
})
|
||||
}
|
||||
|
||||
impl MiniTheme {
|
||||
/// The default theme for out tool
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
font_family: "Latin Modern Roman".to_string(),
|
||||
margin: Box {
|
||||
left: 10.0,
|
||||
top: 20.0,
|
||||
right: 90.0,
|
||||
bottom: 60.0,
|
||||
},
|
||||
width: 860.0,
|
||||
height: 560.0,
|
||||
grid_stroke_color: Color {
|
||||
r: 77,
|
||||
g: 69,
|
||||
b: 57,
|
||||
a: 255,
|
||||
},
|
||||
grid_stroke_width: 2.5,
|
||||
series_stroke_width: 5.0,
|
||||
series_label_font_size: 60.0,
|
||||
series_label_font_color: Color {
|
||||
r: 75,
|
||||
g: 61,
|
||||
b: 68,
|
||||
a: 255,
|
||||
},
|
||||
series_colors: [Color {
|
||||
r: 179,
|
||||
g: 165,
|
||||
b: 85,
|
||||
a: 255,
|
||||
}]
|
||||
.to_vec(),
|
||||
legend_show: Some(false),
|
||||
}
|
||||
}
|
||||
|
||||
/// Apply our super custom theme to the graph
|
||||
pub(super) fn apply_to(&self, r: &mut RadarChart) {
|
||||
r.font_family = self.font_family.clone();
|
||||
r.margin = self.margin.clone();
|
||||
r.width = self.width;
|
||||
r.height = self.height;
|
||||
r.grid_stroke_color = self.grid_stroke_color;
|
||||
r.grid_stroke_width = self.grid_stroke_width;
|
||||
r.series_stroke_width = self.series_stroke_width;
|
||||
r.series_label_font_size = self.series_label_font_size;
|
||||
r.series_label_font_color = self.series_label_font_color;
|
||||
r.series_colors = self.series_colors.clone();
|
||||
r.legend_show = self.legend_show;
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(missing_docs, clippy::missing_docs_in_private_items)]
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub struct MiniTheme {
|
||||
pub font_family: String,
|
||||
pub margin: Box,
|
||||
pub width: f32,
|
||||
pub height: f32,
|
||||
pub legend_show: Option<bool>,
|
||||
// pub background_color: Color,
|
||||
pub grid_stroke_color: Color,
|
||||
pub grid_stroke_width: f32,
|
||||
pub series_stroke_width: f32,
|
||||
pub series_label_font_size: f32,
|
||||
pub series_label_font_color: Color,
|
||||
pub series_colors: Vec<Color>,
|
||||
// pub title_font_size: f32,
|
||||
// pub title_font_color: Color,
|
||||
// pub title_font_weight: Option<String>,
|
||||
// pub title_margin: Option<Box>,
|
||||
// pub title_align: Align,
|
||||
// pub title_height: f32,
|
||||
// pub sub_title_font_size: f32,
|
||||
// pub sub_title_font_color: Color,
|
||||
// pub sub_title_margin: Option<Box>,
|
||||
// pub sub_title_align: Align,
|
||||
// pub sub_title_height: f32,
|
||||
// pub legend_font_size: f32,
|
||||
// pub legend_font_color: Color,
|
||||
// pub legend_align: Align,
|
||||
// pub legend_margin: Option<Box>,
|
||||
// pub x_axis_font_size: f32,
|
||||
// pub x_axis_stroke_color: Color,
|
||||
// pub x_axis_font_color: Color,
|
||||
// pub x_axis_name_gap: f32,
|
||||
// pub x_axis_height: f32,
|
||||
// pub y_axis_font_size: f32,
|
||||
// pub y_axis_font_color: Color,
|
||||
// pub y_axis_stroke_color: Color,
|
||||
// pub y_axis_split_number: usize,
|
||||
// pub y_axis_name_gap: f32,
|
||||
// pub table_header_color: Color,
|
||||
// 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()
|
||||
}
|
||||
|
|
@ -0,0 +1,10 @@
|
|||
//! This workspace_crate is a Rust library designed to create and manage graphs based on CSV (Comma-Separated Values) data.
|
||||
//!
|
||||
//!
|
||||
|
||||
#![warn(missing_docs, clippy::missing_docs_in_private_items)]
|
||||
// Internal modules
|
||||
mod graphs;
|
||||
//
|
||||
// Re Export
|
||||
pub use graphs::make_graphs;
|
||||
|
|
@ -0,0 +1,19 @@
|
|||
[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"
|
||||
|
|
@ -0,0 +1,30 @@
|
|||
// Workspace: make
|
||||
// File: make/src/lib.rs
|
||||
//! The module `makepdf` is responsible for making a pdf using pdflatex.
|
||||
//!
|
||||
//! The main function, [`make_pdf`], orchestrates the entire process of preparing,
|
||||
//! building, and cleaning up LaTeX files to produce a final PDF. It relies on several other modules
|
||||
//! within the `makepdf` workspace to perform specific tasks.
|
||||
//!
|
||||
//! This module contains various helper functions used in the main build process.
|
||||
//!
|
||||
//! It provides utilities for checking and adding input lines based on specified conditions,
|
||||
//! generating glossaries, and managing temporary files. These functions are essential for ensuring
|
||||
//! that the LaTeX files are correctly prepared before invoking pdflatex to generate the final PDF.
|
||||
//!
|
||||
//! Contains utility data types used by other modules in the `makepdf` workspace.
|
||||
//!
|
||||
//! This module is responsible for defining the necessary data structures and traits that are shared
|
||||
//! across different parts of the build process. It includes items such as enums, structs, and traits
|
||||
//! that help in organizing and managing the various components involved in creating a PDF from LaTeX files.
|
||||
//!
|
||||
|
||||
#![warn(missing_docs, clippy::missing_docs_in_private_items)]
|
||||
// Internal modules
|
||||
mod makepdf;
|
||||
mod makepdf_functions;
|
||||
mod makepdf_misc;
|
||||
mod makepdf_structs;
|
||||
|
||||
// Re Export
|
||||
pub use makepdf::make_pdf;
|
||||
|
|
@ -0,0 +1,344 @@
|
|||
// Workspace: make
|
||||
// File: make/src/makepdf.rs
|
||||
//! The module `makepdf_functions` is responsible for making a pdf using pdflatex.
|
||||
//!
|
||||
//!
|
||||
//! # Usage
|
||||
//!
|
||||
//! - [make_pdf]: Make a pdf spawning a subprocess
|
||||
//!
|
||||
//! # Functions
|
||||
//!
|
||||
//! - `launch_subprocess`: Launches the subprocess to make the pdf
|
||||
//! - `checkline`: Checks each line of the subprocess output and updates the status accordingly
|
||||
//!
|
||||
|
||||
use config::make::{BLOCK_PROGRESSION, HELP_BLOCK_SELECTION, MakeTargets, VerboseLevel};
|
||||
use std::{
|
||||
fmt::Write,
|
||||
process::Stdio,
|
||||
str,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
use cli_parser::{Config, MakeConfig};
|
||||
use dynfmt::FormatArgs;
|
||||
use indicatif::{ProgressBar, ProgressState, ProgressStyle};
|
||||
use logos::Logos;
|
||||
use tokio::{
|
||||
io::{AsyncBufReadExt, BufReader},
|
||||
process::Command,
|
||||
};
|
||||
|
||||
use anyhow::{Context, Result, anyhow};
|
||||
|
||||
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<()> {
|
||||
let Ok(Some(_)) = BLOCK_PROGRESSION.get_key(&args.pbar) else {
|
||||
panic!(
|
||||
"Progressbar {} doesn't exists. Use one of the following [{:?}]",
|
||||
args.pbar, HELP_BLOCK_SELECTION
|
||||
);
|
||||
};
|
||||
|
||||
// Identify special targets: Clean, Glossaries, All, List etc.
|
||||
match args.target {
|
||||
Some(MakeTargets::All) => {
|
||||
// Make the target to build
|
||||
let file_r = make_file(args);
|
||||
make_all(args, file_r);
|
||||
}
|
||||
Some(MakeTargets::List) => make_list(args),
|
||||
Some(MakeTargets::Glossaries) => make_glossaries(args),
|
||||
Some(MakeTargets::Clean) => make_clean(args),
|
||||
None => {
|
||||
let file = make_file(args);
|
||||
launch_subprocess(args, file).context("Launching PdfLatex")?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Make all targets
|
||||
fn make_all(args: &MakeConfig, rebuild_target: BuilderParseResult) {
|
||||
launch_subprocess(args, rebuild_target).unwrap();
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
/// Pdfreading and curating
|
||||
async fn launch_subprocess(
|
||||
args: &MakeConfig,
|
||||
rebuild_target: BuilderParseResult,
|
||||
) -> Result<Status> {
|
||||
let mut cmd = Command::new(&args.latex_command);
|
||||
let mut status = Status::zero();
|
||||
|
||||
let started = Instant::now();
|
||||
let mut last_total_duration = Duration::from_secs(0);
|
||||
let mut current_run = BuildInfo::new(args);
|
||||
let last_run = BuildInfo::load(args);
|
||||
|
||||
let mut built = 0;
|
||||
let mut to_build = last_run.lines_parsed;
|
||||
let last_duration = last_run.time_ellapsed.as_secs_f64();
|
||||
|
||||
if args.non_interactive {
|
||||
cmd.arg("--interaction=nonstopmode");
|
||||
}
|
||||
if args.shell_escape {
|
||||
cmd.arg("--shell-escape");
|
||||
}
|
||||
|
||||
cmd.arg(&rebuild_target.new_name);
|
||||
cmd.env("max_print_line", "3000");
|
||||
// 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 stdout = child
|
||||
.stdout
|
||||
.take()
|
||||
.expect("Child did not have a handle to stdout");
|
||||
|
||||
let mut reader = BufReader::new(stdout).split(0xA);
|
||||
|
||||
// Ensure the child process is spawned in the runtime so it can
|
||||
// make progress on its own while we await for any output.
|
||||
tokio::spawn(async move {
|
||||
let _status = child
|
||||
.wait()
|
||||
.await
|
||||
.expect("Child process encountered an error");
|
||||
// sleep(Duration::from_millis(100)).await;
|
||||
// println!("Child status was: {}", status);
|
||||
});
|
||||
|
||||
let pb = ProgressBar::new(to_build);
|
||||
pb.set_style(
|
||||
ProgressStyle::with_template(
|
||||
"{spinner:.green} [{elapsed_precise}] [{wide_bar:.cyan/blue}] (lines: {pos}/{len}) (speed: {per_sec}) (eta: {eta})",
|
||||
)
|
||||
.unwrap()
|
||||
.with_key("eta", move |state: &ProgressState, w: &mut dyn Write| {
|
||||
write!(w, "{:.1}s", (last_duration - state.elapsed().as_secs_f64()).max(0.)).unwrap()
|
||||
})
|
||||
.with_key("per_sec",|state:&ProgressState,w:&mut dyn Write|{
|
||||
write!(w,"{:.1}/lps",state.per_sec()).unwrap()
|
||||
})
|
||||
.progress_chars(&BLOCK_PROGRESSION[&args.pbar]),
|
||||
);
|
||||
pb.enable_steady_tick(Duration::from_millis(100));
|
||||
|
||||
loop {
|
||||
let res = reader.next_segment().await;
|
||||
// let new = min(built + 1, to_build);
|
||||
let new = if built < to_build {
|
||||
built + 1
|
||||
} else {
|
||||
to_build += 1;
|
||||
pb.set_length(to_build);
|
||||
built + 1
|
||||
};
|
||||
built = new;
|
||||
pb.set_position(new);
|
||||
|
||||
current_run.lines_parsed += 1;
|
||||
if let Err(e) = res {
|
||||
return Err(anyhow!("[CORE] Runtime error : {}", e));
|
||||
} else if let Ok(line) = res {
|
||||
if let Some(line) = line {
|
||||
let s = match str::from_utf8(&line) {
|
||||
Ok(v) => v,
|
||||
Err(e) => {
|
||||
// status.errors += 1;
|
||||
if args.verbosity <= VerboseLevel::Info {
|
||||
let valid = str::from_utf8(&line[..e.valid_up_to()]).unwrap_or("");
|
||||
pb.println(format!(
|
||||
"{} An invalid UTF-8 sequence was parsed {:?}",
|
||||
COL_INFO.apply_to("[CORE]"),
|
||||
e
|
||||
));
|
||||
pb.println(format!(
|
||||
"{} The valid part is: {}",
|
||||
COL_INFO.apply_to("[CORE]"),
|
||||
valid
|
||||
))
|
||||
}
|
||||
continue;
|
||||
}
|
||||
};
|
||||
checkline(
|
||||
args,
|
||||
s,
|
||||
&mut status,
|
||||
&mut current_run,
|
||||
&started,
|
||||
&pb,
|
||||
&mut last_total_duration,
|
||||
)
|
||||
.expect("Error while checking line");
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
current_run.time_ellapsed = started.elapsed();
|
||||
pb.finish_and_clear();
|
||||
status.print(args, ¤t_run, rebuild_target);
|
||||
current_run.save();
|
||||
Ok(status)
|
||||
}
|
||||
|
||||
/// Check each line and changes the status and/or display according warnings
|
||||
fn checkline(
|
||||
args: &MakeConfig,
|
||||
orginal_line: &str,
|
||||
status: &mut Status,
|
||||
run: &mut BuildInfo,
|
||||
started: &Instant,
|
||||
pb: &ProgressBar,
|
||||
last_total_duration: &mut Duration,
|
||||
) -> Result<()> {
|
||||
// Match the line to guess what is happening
|
||||
let mut lex = LineType::lexer(orginal_line);
|
||||
let parsed_line = match lex.next() {
|
||||
Some(Ok(m)) => m,
|
||||
None => LineType::Empty,
|
||||
_ => LineType::Unknown(orginal_line.to_string()),
|
||||
};
|
||||
|
||||
// Post processing for some lines that can't be properly handlend by the lexer
|
||||
let final_line = match parsed_line {
|
||||
// LineType::Mode => todo!(),
|
||||
// LineType::Info(_) => todo!(),
|
||||
// LineType::StartingSequence => todo!(),
|
||||
// LineType::EndSequence => todo!(),
|
||||
// LineType::MPSConverter => todo!(),
|
||||
ref a @ LineType::Chapter(_) => {
|
||||
run.add_lap(started, last_total_duration);
|
||||
a
|
||||
}
|
||||
LineType::MissingReferencePrs => &LineType::MissingReference(orginal_line.to_string()),
|
||||
LineType::WarningPrs => &LineType::Warning(orginal_line.to_string()),
|
||||
LineType::PdfTexVersion(_) => &LineType::PdfTexVersion(orginal_line.to_string()),
|
||||
// LineType::Context(_) => todo!(),
|
||||
LineType::BoxFullnessPrs => &LineType::BoxFullness(orginal_line.to_string()),
|
||||
// LineType::LaTexVersion => todo!(),
|
||||
// LineType::WriteMode => todo!(),
|
||||
// LineType::DocumentClass => todo!(),
|
||||
// LineType::EnteringDocument(_) => todo!(),
|
||||
// LineType::Library(_) => todo!(),
|
||||
LineType::PackageWarningPrs((ref pkg, ref wrn)) => match pkg.as_str() {
|
||||
"Package tabularray Warning" => {
|
||||
&LineType::LowPackageWarning(("tabulararray".to_string(), wrn.clone()))
|
||||
}
|
||||
_ => {
|
||||
let mut name = pkg.split(" ");
|
||||
&LineType::PackageWarning((
|
||||
name.nth(1).unwrap_or("unknown").to_string(),
|
||||
wrn.clone(),
|
||||
))
|
||||
}
|
||||
},
|
||||
// LineType::PackageContextWarning(_) => todo!(),
|
||||
// LineType::Loading(_) => todo!(),
|
||||
// LineType::Unknown(_) => todo!(),
|
||||
// LineType::PageGen => todo!(),
|
||||
// LineType::Output => todo!(),
|
||||
// LineType::Log => todo!(),
|
||||
// LineType::Empty => todo!(),
|
||||
// LineType::GeometryResolution => todo!(),
|
||||
// LineType::GeometryFound => todo!(),
|
||||
// LineType::Transcript => todo!(),
|
||||
_ => &parsed_line,
|
||||
};
|
||||
|
||||
// Early exit if the verbosity level doenst match
|
||||
if final_line.vlvl() < args.verbosity {
|
||||
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!(
|
||||
"{} {:?}",
|
||||
*TXT_MISC,
|
||||
COL_NORMAL.apply_to(final_line)
|
||||
)),
|
||||
VerboseLevel::Box => pb.println(format!(
|
||||
"{} {:?}",
|
||||
*TXT_BOXX,
|
||||
COL_NORMAL.apply_to(final_line)
|
||||
)),
|
||||
VerboseLevel::Context => pb.println(format!(
|
||||
"{} {:?}",
|
||||
*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!(
|
||||
"{} {:?}",
|
||||
*TXT_INFO,
|
||||
COL_NORMAL.apply_to(final_line)
|
||||
))
|
||||
}
|
||||
VerboseLevel::Warning => {
|
||||
status.warnings += 1;
|
||||
pb.println(format!(
|
||||
"{} {:?}",
|
||||
*TXT_WARN,
|
||||
COL_NORMAL.apply_to(final_line)
|
||||
))
|
||||
}
|
||||
VerboseLevel::Error => {
|
||||
status.errors += 1;
|
||||
pb.println(format!(
|
||||
"{} {:?}",
|
||||
*TXT_ERRR,
|
||||
COL_NORMAL.apply_to(final_line)
|
||||
))
|
||||
}
|
||||
VerboseLevel::Critical => {
|
||||
status.errors += 1;
|
||||
pb.println(format!(
|
||||
"{} {:?}",
|
||||
*TXT_CRIT,
|
||||
COL_NORMAL.apply_to(final_line)
|
||||
))
|
||||
}
|
||||
VerboseLevel::Uncatchable => {
|
||||
status.errors += 1;
|
||||
pb.println(format!(
|
||||
"{} {}",
|
||||
*TXT_UKNW,
|
||||
COL_NORMAL.apply_to(orginal_line)
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
|
@ -0,0 +1,314 @@
|
|||
// Workspace: make
|
||||
// File: make/src/makepdf_functions.rs
|
||||
//! The module `makepdf_functions` is a collection of helper functions used in the main build process.
|
||||
//!
|
||||
//! It provides various utilities for preparing, building, and cleaning up LaTeX files.
|
||||
//! These functions are primarily responsible for checking and adding input lines based
|
||||
//! on specified conditions, generating glossaries, and managing temporary files.
|
||||
//!
|
||||
use std::{
|
||||
fs::File,
|
||||
io::{Read, Write},
|
||||
path::{Path, PathBuf},
|
||||
process::Command,
|
||||
str::from_utf8,
|
||||
sync::LazyLock,
|
||||
};
|
||||
|
||||
use anyhow::Result;
|
||||
use cli_parser::MakeConfig;
|
||||
use indexmap::IndexMap;
|
||||
use regex::Regex;
|
||||
|
||||
use crate::makepdf_structs::{COL_ERROR, COL_INFO, COL_MISC, COL_WARNING};
|
||||
|
||||
/// Regex detecting wether an input line is present
|
||||
static INPUT_REGEX: LazyLock<Regex> =
|
||||
LazyLock::new(|| Regex::new(r#"^\\input\{"?([^\}]+)\}"?"#).unwrap());
|
||||
/// The chapter name list
|
||||
static CHAPT_REGEX: LazyLock<Regex> =
|
||||
LazyLock::new(|| Regex::new(r#" *\\chapter\*?\{"?([^\}]+)\}"?"#).unwrap());
|
||||
|
||||
/// The info returned by a make_file
|
||||
pub(super) struct BuilderParseResult {
|
||||
/// The new name
|
||||
pub(super) new_name: String,
|
||||
|
||||
/// The list of chapter encountered
|
||||
pub(super) chapt_list: Vec<String>,
|
||||
}
|
||||
|
||||
/// Make the (new/purged) target file and return (name,chapter_list)
|
||||
pub(super) fn make_file(args: &MakeConfig) -> BuilderParseResult {
|
||||
let path = target_name(&args.filename);
|
||||
let m = make_ignore_targets(args);
|
||||
let mut f = File::open(&args.filename).expect("The file doesn't exist");
|
||||
let mut of = File::create(&path).unwrap();
|
||||
let mut contents = String::new();
|
||||
let mut chapters = Vec::new();
|
||||
let mut first = true;
|
||||
// Warn about wrong keys
|
||||
clear_keys(args, &m);
|
||||
f.read_to_string(&mut contents)
|
||||
.expect("Couldn't read the file");
|
||||
for line in contents.lines() {
|
||||
if let Some(c) = INPUT_REGEX.captures(line) {
|
||||
// Check if it's the first inport, then adds the version number
|
||||
if first {
|
||||
first = false;
|
||||
writeln!(of, "\\def\\buildversion{{ {} }}", get_build_version())
|
||||
.expect("Couldn't write version number");
|
||||
}
|
||||
// Check wether it should be added
|
||||
if add_checker(&c[1], &m, args) {
|
||||
if args.no_context {
|
||||
println!(
|
||||
"{} {} {}",
|
||||
COL_INFO.apply_to("[PREP]"),
|
||||
COL_MISC.apply_to("Including"),
|
||||
&c[1]
|
||||
);
|
||||
}
|
||||
of.write_all(line.as_bytes()).unwrap();
|
||||
of.write_all("\n".as_bytes()).unwrap();
|
||||
} else if args.no_context {
|
||||
println!(
|
||||
"{} {} {}",
|
||||
COL_INFO.apply_to("[PREP]"),
|
||||
COL_WARNING.apply_to("Excluding"),
|
||||
&c[1]
|
||||
);
|
||||
}
|
||||
} else {
|
||||
of.write_all(line.as_bytes()).unwrap();
|
||||
of.write_all("\n".as_bytes()).unwrap();
|
||||
}
|
||||
if let Some(c) = CHAPT_REGEX.captures(line) {
|
||||
chapters.push(c[1].to_string());
|
||||
}
|
||||
}
|
||||
|
||||
BuilderParseResult {
|
||||
new_name: format!("{:?}", path),
|
||||
chapt_list: chapters,
|
||||
}
|
||||
}
|
||||
|
||||
/// Execute an external git command
|
||||
macro_rules! exec_cmd {
|
||||
($cmd:expr, $args:expr) => {
|
||||
{
|
||||
let mut cmd = Command::new($cmd);
|
||||
cmd.args($args);
|
||||
|
||||
match cmd.output() {
|
||||
Ok(v) => from_utf8(&v.stdout)
|
||||
.expect("Couldn't parse the git tag result")
|
||||
.to_owned(),
|
||||
Err(e) => {
|
||||
println!(
|
||||
"[ERRR] An error has occured while trying to retrieve the Ravenous Version\n {:#?}",
|
||||
e
|
||||
);
|
||||
"Unknown".to_string()
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/// Ask git for the current version
|
||||
fn get_build_version() -> String {
|
||||
let tag = exec_cmd!("git", ["describe", "--tags", "--abbrev=0"]).replace("\n", "");
|
||||
|
||||
let hsh = exec_cmd!("git", ["rev-parse", "--short", "HEAD"]).replace("\n", "");
|
||||
|
||||
// let thsh = exec_cmd!("git", ["show-ref", tag.as_str(), "-s"]);
|
||||
let vnmbr = exec_cmd!(
|
||||
"git",
|
||||
["rev-list", format!("{}..HEAD", tag).as_str(), "--count"]
|
||||
)
|
||||
.replace("\n", "");
|
||||
format!("Version: {}r{} ({})", tag, vnmbr, hsh)
|
||||
}
|
||||
|
||||
/// Clear the list of keys (for now only warn)
|
||||
fn clear_keys(args: &MakeConfig, dict_entries: &IndexMap<String, String>) {
|
||||
for k in args.only.iter() {
|
||||
if !dict_entries.contains_key(k) {
|
||||
panic!(
|
||||
"{} The key {} wasn't in the list of togglable imports :\n{:?} rerun with option -t list for the full list",
|
||||
COL_ERROR.apply_to("[ERRR]"),
|
||||
k,
|
||||
dict_entries.keys()
|
||||
)
|
||||
}
|
||||
}
|
||||
for k in args.no.iter() {
|
||||
if !dict_entries.contains_key(k) {
|
||||
panic!(
|
||||
"{} The key {} wasn't in the list of togglable imports:\n {:?} rerun with option -t list for the full list",
|
||||
COL_ERROR.apply_to("[ERRR]"),
|
||||
k,
|
||||
dict_entries.keys()
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Algorithm to check wether to add or not the entry
|
||||
fn add_checker(check: &str, dict_entries: &IndexMap<String, String>, args: &MakeConfig) -> bool {
|
||||
if args.only.is_empty() && args.no.is_empty() {
|
||||
return true;
|
||||
}
|
||||
for k in args.only.iter() {
|
||||
if dict_entries.contains_key(k) && dict_entries[k] == check {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
if !args.no.is_empty() {
|
||||
for k in args.no.iter() {
|
||||
if dict_entries.contains_key(k) && dict_entries[k] == check {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
false
|
||||
}
|
||||
/// List all chapters targetable by ignore and only
|
||||
pub(super) fn make_list(args: &MakeConfig) {
|
||||
let m = make_ignore_targets(args);
|
||||
println!("The ignore targets are the following:");
|
||||
println!("{:#?}", m);
|
||||
}
|
||||
|
||||
/// Make the dict of targets
|
||||
fn make_ignore_targets(args: &MakeConfig) -> IndexMap<String, String> {
|
||||
let mut map: IndexMap<String, String> = IndexMap::new();
|
||||
let mut f = File::open(&args.filename).unwrap();
|
||||
let mut contents = String::new();
|
||||
f.read_to_string(&mut contents).unwrap();
|
||||
for line in contents.lines() {
|
||||
if let Some(c) = INPUT_REGEX.captures(line) {
|
||||
// println!("[TRGT] {:?}", &c[1]);
|
||||
simplify_add(c[1].to_string(), &mut map).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
map
|
||||
}
|
||||
|
||||
/// Create a target name, by appending _build to it
|
||||
pub(super) fn target_name(target: &str) -> PathBuf {
|
||||
let target = Path::new(target);
|
||||
let mut target_oss = target.file_stem().unwrap().to_owned();
|
||||
target_oss.push("_build.tex");
|
||||
target_oss.into()
|
||||
}
|
||||
|
||||
/// Create a target suffix and by append _build
|
||||
pub(super) fn target_pref(target: &str) -> String {
|
||||
let target = Path::new(target);
|
||||
let target_oss = target.file_stem().unwrap().to_owned();
|
||||
let v = format!("{:?}", target_oss);
|
||||
v[1..v.len() - 1].to_string()
|
||||
}
|
||||
|
||||
/// Try to add a simplified entry to a list
|
||||
pub(super) fn simplify_add(
|
||||
entry: String,
|
||||
dict_entries: &mut IndexMap<String, String>,
|
||||
) -> Result<()> {
|
||||
// If the value was already inside, no need to add it
|
||||
if dict_entries.values().any(|e| e == &entry) {
|
||||
return Ok(());
|
||||
}
|
||||
// Strategy one: use the last part after /
|
||||
if let Some(e) = entry.split("/").nth(1) {
|
||||
let e = e.to_lowercase();
|
||||
if e.len() >= 3 {
|
||||
for i in 3..e.len() {
|
||||
if !dict_entries.contains_key(&e[..i]) {
|
||||
dict_entries.insert(e[..i].to_owned(), entry);
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
}
|
||||
{
|
||||
if !dict_entries.contains_key(&e) {
|
||||
dict_entries.insert(e.to_owned(), entry);
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Strategy two use first part before / and add _ to last
|
||||
let mut spl = entry.split("/");
|
||||
if let (Some(p), Some(s)) = (spl.next(), spl.next()) {
|
||||
let (p, s) = (p.to_lowercase(), s.to_lowercase());
|
||||
let key = format!("{:1}_{}", p, s);
|
||||
if !dict_entries.contains_key(&key) {
|
||||
dict_entries.insert(key.to_owned(), entry);
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
|
||||
// Last ditch strategy
|
||||
let e = entry.replace("/", "_").to_lowercase();
|
||||
dict_entries.insert(e, entry);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Make the glossaries
|
||||
pub(super) fn make_glossaries(args: &MakeConfig) {
|
||||
use std::str;
|
||||
// let name = format!("{:?}", target_name(&args.filename));
|
||||
// let name = &name[1..name.len() - 1];
|
||||
// println!("{}", name);
|
||||
let name = target_pref(&args.filename);
|
||||
match Command::new("makeglossaries")
|
||||
.arg(format!("{}_build", name))
|
||||
.output()
|
||||
{
|
||||
Err(e) => {
|
||||
println!(
|
||||
"An error has occured while trying to build the glossaries\n{:#?}",
|
||||
e
|
||||
)
|
||||
}
|
||||
Ok(o) => {
|
||||
println!("Program exited with status {}", o.status);
|
||||
if !o.stdout.is_empty() {
|
||||
println!("{}", str::from_utf8(&o.stdout).unwrap_or(""));
|
||||
}
|
||||
if !o.stderr.is_empty() {
|
||||
println!("{}", str::from_utf8(&o.stderr).unwrap_or(""));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Make the working directory clean, by eliminating all temporary files
|
||||
pub(super) fn make_clean(args: &MakeConfig) {
|
||||
let _ = args;
|
||||
// let target = format!("{:?}", Path::new(&args.filename).file_stem().unwrap());
|
||||
let target = target_pref(&args.filename);
|
||||
let list_suff = [
|
||||
".aux", ".glg", ".glo", ".gls", ".ist", ".log", ".out", ".toc", ".pdf", ".dvi", ".fls",
|
||||
];
|
||||
let mut cmd = Command::new("rm");
|
||||
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, ".tex"));
|
||||
// println!("{:?}", cmd);
|
||||
if let Err(e) = cmd.output() {
|
||||
println!(
|
||||
"[ERRR] An error has occured when executing the clean target \n {:#?}",
|
||||
e
|
||||
)
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1 @@
|
|||
//! Printing and misc utilities
|
||||
|
|
@ -0,0 +1,487 @@
|
|||
// Workspace: make
|
||||
// File: make/src/makepdf_structs.rs
|
||||
//! Contains utility data types used by other modules in the `makepdf` workspace.
|
||||
//!
|
||||
use cli_parser::MakeConfig;
|
||||
use config::make::VerboseLevel;
|
||||
use logos::Logos;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{
|
||||
cell::OnceCell,
|
||||
io::{Read, Write},
|
||||
sync::LazyLock,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
use console::Style;
|
||||
|
||||
use crate::makepdf_functions::BuilderParseResult;
|
||||
|
||||
/// Color Scheme for the NORMAL level
|
||||
pub(super) static COL_NORMAL: LazyLock<Style> = LazyLock::new(Style::new);
|
||||
/// Color Scheme for the MISC level
|
||||
pub(super) static COL_MISC: LazyLock<Style> = LazyLock::new(|| Style::new().color256(44));
|
||||
/// Color Scheme for the BOX level
|
||||
pub(super) static COL_BOX: LazyLock<Style> = LazyLock::new(|| Style::new().color256(37));
|
||||
/// Color Scheme for the CONTEXT level
|
||||
pub(super) static COL_CONTEXT: LazyLock<Style> = LazyLock::new(|| Style::new().color256(30));
|
||||
/// Color Scheme for the INFO level
|
||||
pub(super) static COL_INFO: LazyLock<Style> = LazyLock::new(|| Style::new().color256(2));
|
||||
/// Color Scheme for the WARNING level
|
||||
pub(super) static COL_WARNING: LazyLock<Style> = LazyLock::new(|| Style::new().color256(166));
|
||||
/// Color Scheme for the ERROR level
|
||||
#[allow(dead_code)]
|
||||
pub(super) static COL_ERROR: LazyLock<Style> = LazyLock::new(|| Style::new().color256(52));
|
||||
/// Color Scheme for the CRITICAL level
|
||||
pub(super) static COL_CRITICAL: LazyLock<Style> = LazyLock::new(|| Style::new().color256(1));
|
||||
/// Color Scheme for the UNCATCHABLE level
|
||||
pub(super) static COL_UNCATCHABLE: LazyLock<Style> =
|
||||
LazyLock::new(|| Style::new().color256(124).bold());
|
||||
|
||||
/// Filler box for the [MISC] text box
|
||||
pub(super) static TXT_MISC: LazyLock<String> =
|
||||
LazyLock::new(|| format!("{}", COL_MISC.apply_to(&"[MISC]")));
|
||||
/// Filler box for the [BOXX] text box
|
||||
pub(super) static TXT_BOXX: LazyLock<String> =
|
||||
LazyLock::new(|| format!("{}", COL_BOX.apply_to(&"[BOXX]")));
|
||||
/// 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]")));
|
||||
/// Filler box for the [WARN] text box
|
||||
pub(super) static TXT_WARN: LazyLock<String> =
|
||||
LazyLock::new(|| format!("{}", COL_WARNING.apply_to(&"[WARN]")));
|
||||
/// Filler box for the [CRIT] text box
|
||||
pub(super) static TXT_CRIT: LazyLock<String> =
|
||||
LazyLock::new(|| format!("{}", COL_CRITICAL.apply_to(&"[CRIT]")));
|
||||
/// Filler box for the [ERRR] text box
|
||||
pub(super) static TXT_ERRR: LazyLock<String> =
|
||||
LazyLock::new(|| format!("{}", COL_CRITICAL.apply_to(&"[ERRR]")));
|
||||
/// Filler box for the [UKNW] text box
|
||||
pub(super) static TXT_UKNW: LazyLock<String> =
|
||||
LazyLock::new(|| format!("{}", COL_UNCATCHABLE.apply_to(&"[UKNW]")));
|
||||
|
||||
/// Keeps tracks of the stats of the last(s) run to offer accurate estimation
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub(super) struct BuildInfo {
|
||||
/// File parsed
|
||||
pub filename: String,
|
||||
/// Options Selected
|
||||
pub options: Vec<String>,
|
||||
/// Number of lines parsed
|
||||
pub lines_parsed: u64,
|
||||
/// Time ellapsed
|
||||
pub time_ellapsed: Duration,
|
||||
/// Time per section ellapsed
|
||||
pub time_spent: Vec<Duration>,
|
||||
/// Final file size
|
||||
pub file_size: u64,
|
||||
}
|
||||
|
||||
impl BuildInfo {
|
||||
/// Create a new empty run
|
||||
pub fn new(args: &MakeConfig) -> Self {
|
||||
Self {
|
||||
filename: args.filename.clone(),
|
||||
// options: args.update_from_arg_matches,
|
||||
options: Vec::new(),
|
||||
lines_parsed: 0,
|
||||
time_ellapsed: Duration::from_secs(0),
|
||||
time_spent: Vec::new(),
|
||||
file_size: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Load a run from file
|
||||
pub(super) fn load(args: &MakeConfig) -> Self {
|
||||
let mut file = match std::fs::File::open(".last_run.toml") {
|
||||
Ok(f) => f,
|
||||
Err(_) => return Self::empty_guess(args),
|
||||
};
|
||||
let mut cfg = String::new();
|
||||
file.read_to_string(&mut cfg).unwrap();
|
||||
let cfg = toml::from_str(&cfg);
|
||||
match cfg {
|
||||
Ok(c) => c,
|
||||
Err(_) => Self::empty_guess(args),
|
||||
}
|
||||
}
|
||||
|
||||
/// An enmpty (and very small) initial guess
|
||||
fn empty_guess(args: &MakeConfig) -> BuildInfo {
|
||||
let mut s = Self::new(args);
|
||||
s.lines_parsed = 100;
|
||||
s.file_size = 100;
|
||||
s
|
||||
}
|
||||
|
||||
/// Save the last run info
|
||||
pub(super) fn save(&self) {
|
||||
let mut file = std::fs::File::create(".last_run.toml").unwrap();
|
||||
file.write_all(toml::to_string(&self).unwrap().as_bytes())
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
/// Add a level to a chapter, and return the new total duration
|
||||
pub(super) fn add_lap(&mut self, started: &Instant, last_total: &mut Duration) {
|
||||
let total = started.elapsed();
|
||||
self.time_spent
|
||||
.push(total.checked_sub(*last_total).unwrap());
|
||||
*last_total = total;
|
||||
}
|
||||
}
|
||||
// [7] [8]
|
||||
// [UKNW] LaTeX Warning: There were undefined references.
|
||||
// [UKNW] (./Ravenous_build.gls [29] [30] (/usr/share/texmf/tex/latex/lm/ot1lmr.fd) (/usr/share/texmf/tex/latex/lm/omllmm.fd) (/usr/share/texmf/tex/latex/lm/omslmsy.fd) (/usr/share/texmf/tex/latex/lm/omxlmex.fd) (/usr/share/texlive/texmf-dist/tex/latex/amsfonts/umsa.fd) (/usr/share/texlive/texmf-dist/tex/latex/microtype/mt-msa.cfg) (/usr/share/texlive/texmf-dist/tex/latex/amsfonts/umsb.fd) (/usr/share/texlive/texmf-dist/tex/latex/microtype/mt-msb.cfg) [31] [32]
|
||||
// [UKNW] LaTeX Warning: There were undefined references.
|
||||
|
||||
/// The line encountered
|
||||
// #[allow(unused)]
|
||||
#[derive(Debug, Logos, PartialEq, Clone)]
|
||||
#[logos(skip r"[) ]+")]
|
||||
pub(super) enum LineType {
|
||||
/// The tex building mode : entering extended mode
|
||||
#[regex("entering[_ ]extended[_ ]mode")]
|
||||
Mode,
|
||||
/// Info level
|
||||
#[token("L3 programming layer", |lex| lex.slice().to_string())]
|
||||
#[token("For additional information", |lex| lex.slice().to_string())]
|
||||
#[token("Pictures in Paragraphs", |lex| lex.slice().to_string())]
|
||||
#[token("2021/01/20 v 2.00 tkz-graph.sty", |lex| lex.slice().to_string())]
|
||||
Info(String),
|
||||
|
||||
/// Strange starting sequence
|
||||
#[token("? ) [")]
|
||||
#[token("? [1{")]
|
||||
StartingSequence,
|
||||
|
||||
/// Strange end sequence
|
||||
#[token("{/usr/share")]
|
||||
#[token(" ){/")]
|
||||
EndSequence,
|
||||
|
||||
/// Converter [Loading MPS to PDF converter (version 2006.09.02).]
|
||||
#[token("[Loading MPS to PDF converter")]
|
||||
MPSConverter,
|
||||
|
||||
/// A chapter was processed
|
||||
#[regex(r"Chapitre [0-9]+", |lex| lex.slice()[9..].to_string())]
|
||||
Chapter(String),
|
||||
|
||||
/// Missing reference
|
||||
#[token(r"LaTeX Warning: Reference")]
|
||||
MissingReferencePrs,
|
||||
|
||||
/// Missed reference, completed with all info
|
||||
MissingReference(String),
|
||||
|
||||
/// Generic Latex Warning
|
||||
#[regex("pdf([Ll]a)?[tT]e[Xx] [wW]arning")]
|
||||
#[regex("[Ll]a[tT]e[Xx] [wW]arning")]
|
||||
WarningPrs,
|
||||
|
||||
/// Reparsed Warning
|
||||
Warning(String),
|
||||
|
||||
// /// Runaway argument
|
||||
// #[token("Runaway argument?")]
|
||||
// RunAway,
|
||||
/// PdfTex VersionThis is pdfTeX, Version 3.141592653-2.6-1.40.22
|
||||
#[token("This is pdfTeX", |_| "".to_string())]
|
||||
PdfTexVersion(String),
|
||||
|
||||
/// Context, mosty for boxes
|
||||
// TODO: False positives / Reparsing Context("10") )) [107] (./Ecoles/Protecteur.tex
|
||||
// TODO: uncaught: [UKNW] [3] [4] (./Chapters/Intro.tex (/usr/share/texmf/tex/latex/lm/ot1lmr.fd) (/usr/share/texmf/tex/latex/lm/omllmm.fd) (/usr/share/texmf/tex/latex/lm/omslmsy.fd) (/usr/share/texmf/tex/latex/lm/omxlmex.fd) (/usr/share/texlive/texmf-dist/tex/latex/amsfonts/umsa.fd) (/usr/share/texlive/texmf-dist/tex/latex/microtype/mt-msa.cfg) (/usr/share/texlive/texmf-dist/tex/latex/amsfonts/umsb.fd) (/usr/share/texlive/texmf-dist/tex/latex/microtype/mt-msb.cfg) (/usr/share/texmf/tex/latex/lm/ts1lmr.fd)) [5 <./Images//Ico/LogoNoush.jpg>] [6]
|
||||
#[regex(r"\[\d+\]", |lex| lex.slice()[1..lex.slice().len()-1].to_string())]
|
||||
#[regex(r"\[\d[^\]]+", |lex| lex.slice()[1..lex.slice().len()-1].to_string())]
|
||||
Context(String),
|
||||
|
||||
/// Overfull and underfull boxes
|
||||
#[regex("(Over|Under)full")]
|
||||
BoxFullnessPrs,
|
||||
|
||||
/// A box, reparsed
|
||||
BoxFullness(String),
|
||||
|
||||
/// The Latex Version
|
||||
#[regex("LaTeX2e")]
|
||||
LaTexVersion,
|
||||
/// The write18 mode, whatever that is
|
||||
#[token(" restricted \\write18 enabled.")]
|
||||
#[token(" \\write18 enabled.")]
|
||||
WriteMode,
|
||||
|
||||
/// The class of document (book, article, etc)
|
||||
// s if s.starts_with("Document Class") => LineType::DocumentClass(s.to_string()),
|
||||
#[token("Document Class:")]
|
||||
DocumentClass,
|
||||
|
||||
/// Signals that the parser entered a document
|
||||
//TODO: Fix name collection
|
||||
// #[regex(r"(\)+ )?\(\./[A-z/]+\.tex", |lex| lex.slice().split("(").next().unwrap_or("").to_string())]
|
||||
// #[regex(r"(\)+ )?(\[\w+\])?\(\./[A-z/]+\.tex", |lex| lex.slice().split("(").next().unwrap_or("").to_string())]
|
||||
// #[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())]
|
||||
EnteringDocument(String),
|
||||
|
||||
/// Info on the loading of a library
|
||||
#[regex(r"Library \(\w+\)[^\n]+", |lex| split_by(":",&lex.slice()[8..]), allow_greedy=true)]
|
||||
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)]
|
||||
PackageWarningPrs((String, String)),
|
||||
|
||||
/// A package warning, with normal warning level
|
||||
PackageWarning((String, String)),
|
||||
|
||||
/// A package warning, with low warning level
|
||||
LowPackageWarning((String, String)),
|
||||
|
||||
/// The warning context generated by a package
|
||||
#[regex(r"\([A-z_-]+\) [^\n]+", |lex| split_by(")",&lex.slice()[1..]), allow_greedy=true)]
|
||||
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),
|
||||
|
||||
/// Unknown type
|
||||
Unknown(String),
|
||||
|
||||
/// Building blocks, signals pages being rendered ?
|
||||
#[token(" []")]
|
||||
#[token("[]")]
|
||||
PageGen,
|
||||
|
||||
/// Output
|
||||
// #[regex(r"Output written on", |lex| lex.slice()[18..].to_string())]
|
||||
#[token(r"Output written on")]
|
||||
Output,
|
||||
|
||||
/// Log
|
||||
// #[regex("Transcript written on [^\n]+", |lex| lex.slice()[18..].to_string())]
|
||||
#[token("Transcript written on")]
|
||||
Log,
|
||||
|
||||
/// Useless help line
|
||||
#[regex(r"\.\.\.")]
|
||||
Garbage,
|
||||
|
||||
/// Empty line, to discard
|
||||
Empty,
|
||||
|
||||
/// Geometry package
|
||||
#[token("*geometry* driver: auto-detecting")]
|
||||
GeometryResolution,
|
||||
|
||||
/// Geometry found
|
||||
#[token("*geometry* detected driver: pdftex")]
|
||||
GeometryFound,
|
||||
|
||||
/// 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::PdfTexVersion(_) => VerboseLevel::Misc,
|
||||
LineType::Context(_) => VerboseLevel::Misc,
|
||||
LineType::LaTexVersion => VerboseLevel::Misc,
|
||||
LineType::WriteMode => VerboseLevel::Misc,
|
||||
LineType::DocumentClass => VerboseLevel::Misc,
|
||||
LineType::Output => VerboseLevel::Misc,
|
||||
LineType::Log => VerboseLevel::Misc,
|
||||
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::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,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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()));
|
||||
}
|
||||
None
|
||||
}
|
||||
#[derive(Debug)]
|
||||
/// The current status of a run, holding all final info
|
||||
pub(super) struct Status {
|
||||
/// Number of encountered info (mainly o/ufull)
|
||||
pub(super) info: usize,
|
||||
/// Number of warnings, mainly label/reference rerun
|
||||
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>,
|
||||
}
|
||||
|
||||
impl Status {
|
||||
/// Initialize a new status
|
||||
pub(super) fn zero() -> Self {
|
||||
Self {
|
||||
info: 0,
|
||||
warnings: 0,
|
||||
errors: 0,
|
||||
first_error: OnceCell::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Print a pretty message
|
||||
pub(super) fn print(
|
||||
&self,
|
||||
args: &MakeConfig,
|
||||
run_info: &BuildInfo,
|
||||
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!(
|
||||
"{} {}",
|
||||
col_bld.apply_to("[RCAP]"),
|
||||
COL_NORMAL.apply_to(format!(
|
||||
"Processed file {} in {:?}.",
|
||||
run_info.filename, run_info.time_ellapsed
|
||||
))
|
||||
);
|
||||
println!(
|
||||
"{} {}",
|
||||
col_bld.apply_to("[RCAP]"),
|
||||
COL_NORMAL.apply_to(format!(
|
||||
"The compilation generated {} Warnings and {} Errors.",
|
||||
self.warnings, self.errors
|
||||
))
|
||||
);
|
||||
if args.no_context {
|
||||
println!(
|
||||
"{} {}",
|
||||
col_bld.apply_to("[RCAP]"),
|
||||
COL_NORMAL.apply_to("Time spent per chapter")
|
||||
);
|
||||
if !run_info.time_spent.is_empty() {
|
||||
println!(
|
||||
"{}",
|
||||
run_info
|
||||
.time_spent
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, d)| format!(
|
||||
"{} Chapter {} {} - {:.2?}s",
|
||||
COL_CONTEXT.apply_to("[===>]"),
|
||||
i + 1,
|
||||
file_info.chapt_list.get(i).unwrap_or(&"???".to_string()),
|
||||
d.as_secs_f64()
|
||||
))
|
||||
.collect::<Vec<String>>()
|
||||
.join("\n")
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,26 @@
|
|||
[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}
|
||||
|
|
@ -0,0 +1,51 @@
|
|||
//! # 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(())
|
||||
}
|
||||
|
|
@ -0,0 +1,65 @@
|
|||
//! 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(())
|
||||
}
|
||||
|
|
@ -0,0 +1,142 @@
|
|||
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,
|
||||
}
|
||||
|
|
@ -0,0 +1,424 @@
|
|||
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());
|
||||
}
|
||||
|
|
@ -0,0 +1,73 @@
|
|||
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)
|
||||
}
|
||||
|
|
@ -0,0 +1,243 @@
|
|||
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,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,165 @@
|
|||
#![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)
|
||||
)
|
||||
}
|
||||
|
|
@ -0,0 +1,169 @@
|
|||
//! 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
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,363 @@
|
|||
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,
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,546 @@
|
|||
//! # 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,
|
||||
}
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
[package]
|
||||
name = "more_fields"
|
||||
edition = "2024"
|
||||
version.workspace = true
|
||||
|
||||
[dependencies]
|
||||
more_fields_macro = {path ="../more_fields_macro"}
|
||||
|
||||
[dev-dependencies]
|
||||
pretty_assertions = {workspace = true}
|
||||
|
||||
[features]
|
||||
expand_macro = []
|
||||
|
|
@ -0,0 +1,125 @@
|
|||
// 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());
|
||||
// }
|
||||
}
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
[package]
|
||||
name = "more_fields_macro"
|
||||
edition = "2024"
|
||||
version.workspace = true
|
||||
|
||||
[lib]
|
||||
proc-macro = true
|
||||
|
||||
[dependencies]
|
||||
quote = "1.0.46"
|
||||
syn = {version= "2.0.118", features=["full"]}
|
||||
|
|
@ -0,0 +1,184 @@
|
|||
// 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)
|
||||
}
|
||||
|
|
@ -0,0 +1,23 @@
|
|||
# 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"]
|
||||
|
|
@ -0,0 +1,70 @@
|
|||
//! The `ravenous-tool` command-line tool.
|
||||
//!
|
||||
//! This program is meant as a helper for the ravenous project.
|
||||
//!
|
||||
#![warn(missing_docs)]
|
||||
#![warn(clippy::missing_docs_in_private_items)]
|
||||
|
||||
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};
|
||||
use clap::Parser;
|
||||
use cli_parser::{Commands, Config, ConfigArgs, ParserCLIArgs};
|
||||
use std::{
|
||||
fs::{self, OpenOptions},
|
||||
io::Write,
|
||||
};
|
||||
|
||||
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());
|
||||
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),
|
||||
Commands::Config(args) => write_config(&args, &config, config_str),
|
||||
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),
|
||||
}
|
||||
}
|
||||
|
||||
/// Write the config either to stdout, or to a file
|
||||
fn write_config(args: &ConfigArgs, _configg: &Config, config_str: &str) -> Result<()> {
|
||||
// if
|
||||
// fs::write("./helper_config.toml", config_str).context("Writing config")
|
||||
if args.write {
|
||||
let p = match &args.path {
|
||||
Some(p) => p,
|
||||
None => "./helper_config.toml",
|
||||
};
|
||||
let mut file = match &args.force {
|
||||
true => OpenOptions::new()
|
||||
.write(true)
|
||||
.create(true)
|
||||
.truncate(true)
|
||||
.open(p),
|
||||
false => OpenOptions::new().write(true).create_new(true).open(p),
|
||||
}
|
||||
.with_context(|| format!("Trying to write to file {}", p))?;
|
||||
file.write_all(config_str.as_bytes())?;
|
||||
println!("Config sucessfuly written to {}", p);
|
||||
} else {
|
||||
println!("{}", config_str);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
|
@ -0,0 +1,12 @@
|
|||
[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}
|
||||
|
|
@ -0,0 +1,21 @@
|
|||
// Workspace: stats
|
||||
// File: stats/src/lib.rs
|
||||
//! The `stats` crate provides tools for managing and solving statistical affinity problems in creatures.
|
||||
//!
|
||||
//! This module serves as the entry point to all functionality provided by the `stats` crate.
|
||||
//!
|
||||
//! # Submodules
|
||||
//!
|
||||
//! - `stat_algo`: Contains algorithms for finding solutions to the statistics problem.
|
||||
//! - `stat_structs`: Defines data structures used for managing statistical weights and matrix operations.
|
||||
//! - `stat_io`: Handles input/output operations, such as loading stat records from configuration files.
|
||||
|
||||
#![warn(missing_docs, clippy::missing_docs_in_private_items)]
|
||||
// Internal modules
|
||||
mod stat_algo;
|
||||
mod stat_io;
|
||||
mod stat_structs;
|
||||
mod stats;
|
||||
|
||||
// Re Export
|
||||
pub use stats::stat_solver;
|
||||
|
|
@ -0,0 +1,172 @@
|
|||
// Workspace: stats
|
||||
// File: stats/src/stat_algo.rs
|
||||
//! The module `stat_algo` contains algorithms for solving statistical affinity problems.
|
||||
|
||||
//! # Usage
|
||||
//!
|
||||
//! - [find_all_fits]: Searches for all fits of a given mode in the character matrix and adds them to the solution.
|
||||
|
||||
use crate::{
|
||||
stat_io::{AffName, CharacCharMatrix},
|
||||
stat_structs::Fit,
|
||||
};
|
||||
use anyhow::{Result, anyhow};
|
||||
use debug_print::debug_println;
|
||||
use std::{iter::Cycle, vec::IntoIter};
|
||||
|
||||
/// Fitness mode
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub(super) enum Mode {
|
||||
/// A positive fitness, looking for stats the creature has affinity with
|
||||
Positive,
|
||||
/// A negative fitness, looking for stats the creature has no affinity with
|
||||
Negative,
|
||||
}
|
||||
|
||||
/// Find all the fits for the solution (algo1)
|
||||
pub(super) fn find_all_fits(
|
||||
statmatrix: &mut CharacCharMatrix,
|
||||
mut sw: Cycle<IntoIter<AffName>>,
|
||||
mode: Mode,
|
||||
) -> Result<()> {
|
||||
let (mut fits, mut desired_fit_level) = match mode {
|
||||
Mode::Positive => {
|
||||
statmatrix.sort();
|
||||
(statmatrix.size_loop(), Some(Fit::Strong))
|
||||
}
|
||||
Mode::Negative => {
|
||||
statmatrix.reverse_sort();
|
||||
(statmatrix.size_unfited_loop(), Some(Fit::VeryWeak))
|
||||
}
|
||||
};
|
||||
while fits > 0 {
|
||||
if let Some(fit_level) = desired_fit_level {
|
||||
(fits, desired_fit_level) = match mode {
|
||||
Mode::Positive => (
|
||||
find_stat_fit(statmatrix, &mut sw, &fit_level, fits, mode),
|
||||
fit_level.lower(None),
|
||||
),
|
||||
Mode::Negative => (
|
||||
find_stat_fit(statmatrix, &mut sw, &fit_level, fits, mode),
|
||||
fit_level.upper(None),
|
||||
),
|
||||
}
|
||||
} else {
|
||||
return Err(anyhow!(
|
||||
"Can't find any ({:?}) fit at any level, please examine the remaining unfitted characters",
|
||||
mode
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// /// Find all the fits for the solution (algo1)
|
||||
// pub(super) fn find_all_negative_fits(
|
||||
// statmatrix: &mut CharacCharMatrix,
|
||||
// mut sw: Cycle<IntoIter<AffName>>,
|
||||
// ) -> Result<()> {
|
||||
// let mut fits = statmatrix.size_unfited_loop();
|
||||
// let mut desired_fit_level = Some(Fit::VeryWeak);
|
||||
// while fits > 0 {
|
||||
// if let Some(fit_level) = desired_fit_level {
|
||||
// fits = find_stat_unfit(statmatrix, &mut sw, &fit_level, fits);
|
||||
// desired_fit_level = fit_level.upper();
|
||||
// } else {
|
||||
// return Err(anyhow!(
|
||||
// "Can't find any fit at any level, please examine the remaining unfitted characters"
|
||||
// ));
|
||||
// }
|
||||
// }
|
||||
// Ok(())
|
||||
// }
|
||||
|
||||
/// Number of value that couldn't have a fit
|
||||
type NbUnfit = usize;
|
||||
|
||||
/// Find a stat that fits the given affinity
|
||||
fn find_stat_fit(
|
||||
statmatrix: &mut CharacCharMatrix,
|
||||
stat: &mut Cycle<IntoIter<AffName>>,
|
||||
fit_level: &Fit,
|
||||
iterations: usize,
|
||||
mode: Mode,
|
||||
) -> NbUnfit {
|
||||
let mut unfit = 0;
|
||||
// All iteration to do
|
||||
for _ in 0..iterations {
|
||||
let stat = stat.next().unwrap();
|
||||
// Iterate every creature this part of the algorithm is unneeded for our fitness function
|
||||
// as the fitness doesn't depend on the creature
|
||||
if test_fit_for_all_creatures(statmatrix, stat, fit_level, mode).is_err() {
|
||||
unfit += 1;
|
||||
}
|
||||
}
|
||||
if statmatrix.verbose() {
|
||||
if unfit > 0 {
|
||||
println!(
|
||||
"[{}] stats couldn't be [{:?}] fitted at level {:?}",
|
||||
unfit, mode, fit_level
|
||||
);
|
||||
} else {
|
||||
println!("All stats [{:?}] fitted at level [{:?}]", mode, fit_level);
|
||||
}
|
||||
}
|
||||
unfit
|
||||
}
|
||||
|
||||
/// Iterate the fitness on every creature
|
||||
/// Useless for our fitness algorithm
|
||||
fn test_fit_for_all_creatures(
|
||||
statmatrix: &mut CharacCharMatrix,
|
||||
stat: AffName,
|
||||
fit_level: &Fit,
|
||||
mode: Mode,
|
||||
) -> Result<()> {
|
||||
for _ in 0..statmatrix.get_len_affinity(stat) {
|
||||
debug_println!(
|
||||
"[{:?}] Testing fit for stat {:?} at level {:?}",
|
||||
mode,
|
||||
stat,
|
||||
fit_level
|
||||
);
|
||||
let found = match mode {
|
||||
Mode::Negative => statmatrix.find_creature_for_stat_with_negative_fit(stat, fit_level),
|
||||
Mode::Positive => statmatrix.find_creature_for_stat_with_fit(stat, fit_level),
|
||||
};
|
||||
|
||||
if let Ok(creature_id) = found {
|
||||
debug_println!(
|
||||
" ==> Creature {} has affinity for stat {:?}",
|
||||
statmatrix.inner_creature(creature_id, stat).get_name(),
|
||||
stat
|
||||
);
|
||||
statmatrix
|
||||
.add_affinity_to_creature(statmatrix.to_vec_id(creature_id, stat), stat, mode)
|
||||
.unwrap();
|
||||
|
||||
if statmatrix.verbose() {
|
||||
let creature = statmatrix.inner_creature(creature_id, stat);
|
||||
println!(
|
||||
"[{:?}] [{:?}] is a fit for stat {:?} [{:?}]",
|
||||
mode,
|
||||
creature.get_name(),
|
||||
stat,
|
||||
fit_level
|
||||
);
|
||||
println!(
|
||||
" --> [{:?}] {:?}",
|
||||
creature.get_name(),
|
||||
creature.get_all_selected()
|
||||
)
|
||||
}
|
||||
statmatrix.remove_creature_from_stat(creature_id, stat);
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
Err(anyhow!(
|
||||
"No creature can fit the charac {:?} at fitness {:?}",
|
||||
stat,
|
||||
fit_level
|
||||
))
|
||||
}
|
||||
|
|
@ -0,0 +1,535 @@
|
|||
// Workspace: stats
|
||||
// File: stats/src/stat_io.rs
|
||||
//! The module `CharacStatMatrix` allows for manipulation of creatures and their associated affinities.
|
||||
//! It provides a structured way to add, manage, and retrieve information about creatures based on
|
||||
//! different affinity statistics.
|
||||
//!
|
||||
use crate::{stat_algo::Mode, stat_structs::Fit};
|
||||
use anyhow::anyhow;
|
||||
use anyhow::{Context, Result};
|
||||
use config::statsolver::StatConfig;
|
||||
use csv::StringRecord;
|
||||
use debug_print::debug_println;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{fmt::Display, fs::File, iter::zip, path::Path};
|
||||
|
||||
/// How to represent mathematically the affinity for a stat
|
||||
type Affinity = f64;
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
/// A row representing the creature affinity for a stat
|
||||
pub(super) struct CreatureCharacteristicsAffinity {
|
||||
/// A list of witch stats are desired and at witch level
|
||||
affinity: Vec<Affinity>,
|
||||
}
|
||||
|
||||
impl Display for CreatureCharacteristicsAffinity {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(
|
||||
f,
|
||||
"{}",
|
||||
zip(&self.affinity, AffName::as_iter())
|
||||
.map(|(val, aname)| format!("[{:?}]: {}", aname, val))
|
||||
.collect::<Vec<String>>()
|
||||
.join(","),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl CreatureCharacteristicsAffinity {
|
||||
/// Get the affinity level on the given stat
|
||||
fn get_affinity(&self, affinity: AffName) -> Affinity {
|
||||
self.affinity[affinity as usize]
|
||||
}
|
||||
|
||||
// fn fit(&self, stat: AffName) -> _ {
|
||||
// fit(stat, self.affinity)
|
||||
// }
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
/// A single creature with the needed fields to handle affinity selection
|
||||
pub(super) struct Creature {
|
||||
/// The name of the creature
|
||||
name: String,
|
||||
/// The list of affinity desired
|
||||
affinities: CreatureCharacteristicsAffinity,
|
||||
// /// The actives affinities ?
|
||||
// actives_affinities: Vec<Affinity>,
|
||||
/// The currently selected affinities
|
||||
selected_affinities: Vec<AffName>,
|
||||
/// The currently selected negative affinities
|
||||
selected_negative_affinities: Vec<AffName>,
|
||||
}
|
||||
|
||||
impl Creature {
|
||||
/// Get the underlying name
|
||||
pub(super) fn get_name(&self) -> &str {
|
||||
&self.name
|
||||
}
|
||||
|
||||
/// The list of affinities
|
||||
#[allow(dead_code)]
|
||||
pub(super) fn get_affinities(&self) -> &CreatureCharacteristicsAffinity {
|
||||
&self.affinities
|
||||
}
|
||||
|
||||
/// The list of selected characs
|
||||
#[allow(dead_code)]
|
||||
pub(super) fn get_selected(&self) -> &Vec<AffName> {
|
||||
&self.selected_affinities
|
||||
}
|
||||
|
||||
/// The list of selected negative characs
|
||||
#[allow(dead_code)]
|
||||
pub(super) fn get_negative_selected(&self) -> &Vec<AffName> {
|
||||
&self.selected_negative_affinities
|
||||
}
|
||||
|
||||
/// The list of all selected characs
|
||||
#[allow(dead_code)]
|
||||
pub(super) fn get_all_selected(&self) -> Vec<AffName> {
|
||||
let mut v = self.selected_affinities.clone();
|
||||
v.extend(&self.selected_negative_affinities);
|
||||
v
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<StringRecord> for Creature {
|
||||
type Error = anyhow::Error;
|
||||
|
||||
fn try_from(value: StringRecord) -> std::prelude::v1::Result<Self, Self::Error> {
|
||||
let mut iterable = value.into_iter();
|
||||
let creature = iterable.next().context("Getting name")?;
|
||||
let aff = iterable
|
||||
.map(|m| m.parse::<f64>().context("Parsing string").unwrap())
|
||||
.collect();
|
||||
Ok(Self {
|
||||
name: creature.to_owned(),
|
||||
affinities: CreatureCharacteristicsAffinity { affinity: aff },
|
||||
// actives_affinities: Vec::new(),
|
||||
selected_affinities: Vec::new(),
|
||||
selected_negative_affinities: Vec::new(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// How much a stat fit into a vec of affinities
|
||||
fn fit(value: Affinity, _vaff: &[Affinity]) -> Fit {
|
||||
// For now ignore the other affinities
|
||||
if value >= 5. {
|
||||
Fit::VeryStrong
|
||||
} else if value >= 4. {
|
||||
Fit::Strong
|
||||
} else if value >= 3. {
|
||||
Fit::Medium
|
||||
} else if value >= 1. {
|
||||
Fit::Weak
|
||||
} else {
|
||||
Fit::VeryWeak
|
||||
}
|
||||
}
|
||||
// fn negative_fit(value: Affinity, _vaff: &[Affinity]) -> Fit {
|
||||
// // For now ignore the other affinities
|
||||
// if value >= 5. {
|
||||
// Fit::VeryStrong
|
||||
// } else if value >= 4. {
|
||||
// Fit::Strong
|
||||
// } else if value >= 3. {
|
||||
// Fit::Medium
|
||||
// } else if value >= 1. {
|
||||
// Fit::Weak
|
||||
// } else {
|
||||
// Fit::VeryWeak
|
||||
// }
|
||||
// }
|
||||
|
||||
impl Creature {
|
||||
/// Return the fit of a stat
|
||||
pub(super) fn fit(&self, stat: AffName) -> Fit {
|
||||
fit(self.get_stat(stat), &self.affinities.affinity)
|
||||
}
|
||||
|
||||
/// Return the negative fitness of a stat
|
||||
pub(super) fn negative_fit(&self, stat: AffName) -> Fit {
|
||||
fit(self.get_stat(stat), &self.affinities.affinity)
|
||||
}
|
||||
/// Get the stat associated to the given affinity
|
||||
fn get_stat(&self, stat: AffName) -> Affinity {
|
||||
self.affinities.get_affinity(stat)
|
||||
}
|
||||
|
||||
/// Add the given affinity to the list of affinities (Unckecked)
|
||||
fn add_affinity(&mut self, stat: AffName) {
|
||||
self.selected_affinities.push(stat);
|
||||
}
|
||||
/// Add the given affinity to the list of affinities (Unckecked)
|
||||
fn add_negative_affinity(&mut self, stat: AffName) {
|
||||
self.selected_negative_affinities.push(stat);
|
||||
}
|
||||
|
||||
/// Can the stat be picked positively (aka, test the length and wether the stat was already selected)
|
||||
/// This test only works if the algo is done in the correct order
|
||||
// TODO: #[deprecated]
|
||||
fn can_pick(&self, stat: AffName) -> bool {
|
||||
debug_println!(" ==> Testing if {} can fit {:?}", self.name, stat);
|
||||
self.selected_affinities.len() < 2 && !self.selected_affinities.contains(&stat)
|
||||
}
|
||||
|
||||
/// Can the stat be picked negatively (aka, is the length ok and does the vector already contains the value)
|
||||
/// This test only works if the algo is done in the correct order
|
||||
// TODO: #[deprecated]
|
||||
fn can_pick_negatively(&self, stat: AffName) -> bool {
|
||||
debug_println!(" ==> Testing if {} can fit {:?}", self.name, stat);
|
||||
self.selected_negative_affinities.is_empty() && !self.selected_affinities.contains(&stat)
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<StringRecord> for CreatureCharacteristicsAffinity {
|
||||
type Error = anyhow::Error;
|
||||
|
||||
fn try_from(value: StringRecord) -> Result<Self> {
|
||||
let aff = value
|
||||
.into_iter()
|
||||
.skip(1)
|
||||
.map(|m| m.parse::<f64>().context("Parsing string").unwrap())
|
||||
.collect();
|
||||
Ok(Self { affinity: aff })
|
||||
}
|
||||
}
|
||||
|
||||
/// The names of all affinities (essentialy a list of characteristics)
|
||||
#[allow(clippy::missing_docs_in_private_items)]
|
||||
#[derive(Deserialize, Serialize, Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(super) enum AffName {
|
||||
F,
|
||||
Ag,
|
||||
Per,
|
||||
Psy,
|
||||
Int,
|
||||
Vol,
|
||||
Chn,
|
||||
Chr,
|
||||
}
|
||||
|
||||
impl AffName {
|
||||
/// Return the list of stats as iterable
|
||||
pub(super) fn as_iter() -> impl Iterator<Item = AffName> {
|
||||
[
|
||||
AffName::F,
|
||||
AffName::Ag,
|
||||
AffName::Per,
|
||||
AffName::Psy,
|
||||
AffName::Int,
|
||||
AffName::Vol,
|
||||
AffName::Chn,
|
||||
AffName::Chr,
|
||||
]
|
||||
.iter()
|
||||
.copied()
|
||||
}
|
||||
}
|
||||
|
||||
/// A creature id in the vector of creatures
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub(super) struct CreatureVecId(usize);
|
||||
|
||||
/// A creature id in the inner vector
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(super) struct CreatureInnerId(usize);
|
||||
|
||||
impl CreatureInnerId {
|
||||
/// Get the underlying Inner Id
|
||||
fn id(self) -> usize {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl CreatureVecId {
|
||||
/// Gets the underlying creature Id
|
||||
fn id(self) -> usize {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a creature inner id from an id
|
||||
impl From<usize> for CreatureInnerId {
|
||||
fn from(val: usize) -> Self {
|
||||
CreatureInnerId(val)
|
||||
}
|
||||
}
|
||||
/// Create a creature vector id from an id
|
||||
impl From<usize> for CreatureVecId {
|
||||
fn from(val: usize) -> Self {
|
||||
CreatureVecId(val)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
/// A matrix representing: List of characteristics and associated list of creatures
|
||||
/// All math is done at this level to avoid cost
|
||||
/// Right now the index of every creature is used in the matrix, but a references could be used instead
|
||||
pub(super) struct CharacCharMatrix {
|
||||
/// The inner vector structure, used to access rapidly the underlying affinities
|
||||
inner: Vec<Vec<(CreatureVecId, Affinity)>>,
|
||||
/// The list of creatures refered to by the inner structure
|
||||
creatures: Vec<Creature>,
|
||||
/// The module config, handy to have
|
||||
config: StatConfig,
|
||||
}
|
||||
impl CharacCharMatrix {
|
||||
/// Initialize the charac matrix by sorting it
|
||||
fn init(&mut self) {
|
||||
// self.sort()
|
||||
}
|
||||
|
||||
/// Find a creature having an affinity for the given stat
|
||||
/// Returns the id in the inner struct
|
||||
pub(super) fn find_creature_for_stat_with_fit(
|
||||
&self,
|
||||
stat: AffName,
|
||||
fit_level: &Fit,
|
||||
) -> Result<CreatureInnerId> {
|
||||
for (i, (creature, _affinity)) in self.inner[stat as usize].iter().enumerate() {
|
||||
if self.available(*creature, stat, *fit_level).is_ok() {
|
||||
return Ok(i.into());
|
||||
}
|
||||
}
|
||||
Err(anyhow!("Couldn't reach the specified Fit"))
|
||||
}
|
||||
|
||||
/// Find a create with a negative fit for a stat
|
||||
/// Returns the id in the inner struct
|
||||
pub(super) fn find_creature_for_stat_with_negative_fit(
|
||||
&self,
|
||||
stat: AffName,
|
||||
fit_level: &Fit,
|
||||
) -> Result<CreatureInnerId> {
|
||||
for (i, (creature, _)) in self.inner[stat as usize].iter().enumerate() {
|
||||
if self.available_negative(*creature, stat, *fit_level).is_ok() {
|
||||
return Ok(i.into());
|
||||
}
|
||||
}
|
||||
Err(anyhow!("Coudln't find a match at the given negative fit"))
|
||||
}
|
||||
/// Get a creature by Id
|
||||
pub(super) fn get_creature(&self, id: CreatureVecId) -> &Creature {
|
||||
&self.creatures[id.id()]
|
||||
}
|
||||
/// Get a mutable reference to the creature by Id
|
||||
pub(super) fn get_mut_creature(&mut self, id: CreatureVecId) -> &mut Creature {
|
||||
&mut self.creatures[id.id()]
|
||||
}
|
||||
|
||||
/// Get the creature name
|
||||
#[allow(dead_code)]
|
||||
pub(super) fn creature_name(&self, id: CreatureVecId) -> &String {
|
||||
&self.get_creature(id).name
|
||||
}
|
||||
|
||||
/// Get the creature name from it's inner value
|
||||
#[allow(dead_code)]
|
||||
pub(super) fn inner_creature(&self, id: CreatureInnerId, stat: AffName) -> &Creature {
|
||||
&self.creatures[self.to_vec_id(id, stat).id()]
|
||||
}
|
||||
|
||||
/// Adds the affinity given to a creature
|
||||
pub(super) fn add_affinity_to_creature(
|
||||
&mut self,
|
||||
id: CreatureVecId,
|
||||
stat: AffName,
|
||||
mode: Mode,
|
||||
) -> Result<()> {
|
||||
match mode {
|
||||
Mode::Positive => self.get_mut_creature(id).add_affinity(stat),
|
||||
Mode::Negative => self.get_mut_creature(id).add_negative_affinity(stat),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Returns Ok() if the creature can fit the stat at the fit level Err otherwise
|
||||
fn available(&self, id: CreatureVecId, stat: AffName, fit: Fit) -> Result<()> {
|
||||
let creature = self.get_creature(id);
|
||||
if creature.fit(stat) >= fit && creature.can_pick(stat) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(anyhow!(
|
||||
"Creature {:?} can't find a fit for {:?} with affinity {:?}",
|
||||
creature,
|
||||
stat,
|
||||
fit
|
||||
))
|
||||
}
|
||||
}
|
||||
/// Returns Ok() if the creature can fit the negative stat at the fit level Err otherwise
|
||||
fn available_negative(&self, id: CreatureVecId, stat: AffName, fit: Fit) -> Result<()> {
|
||||
let creature = self.get_creature(id);
|
||||
if creature.negative_fit(stat) <= fit && creature.can_pick_negatively(stat) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(anyhow!(
|
||||
"Creature {:?} can't find a negative fit for {:?} with affinity {:?}",
|
||||
creature,
|
||||
stat,
|
||||
fit
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
/// Show the list of solutions chosen for each creature
|
||||
pub(super) fn print_solutions(&self) {
|
||||
for creature in self.creatures.iter() {
|
||||
println!(
|
||||
"[{}] Les Caractéristiques maximum à la création : {:?} (7), {:?} (7), {:?} (5)",
|
||||
creature.name,
|
||||
creature.selected_affinities[0],
|
||||
creature.selected_affinities[1],
|
||||
creature.selected_negative_affinities[0]
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Print all stat weights
|
||||
pub(super) fn print_weights(&self) {
|
||||
for creature in self.creatures.iter() {
|
||||
println!("[{}] {}", creature.name, creature.affinities);
|
||||
}
|
||||
}
|
||||
|
||||
/// Gives the size of the loop needed to fill all negative characteristics
|
||||
pub(super) fn size_unfited_loop(&self) -> usize {
|
||||
self.creatures.len()
|
||||
}
|
||||
|
||||
/// Gives the size of the loop needed to fill all characteristics
|
||||
pub(super) fn size_loop(&self) -> usize {
|
||||
self.creatures.len() * 2
|
||||
}
|
||||
|
||||
/// Get the length of the affinity vector related to the given stat
|
||||
pub(super) fn get_len_affinity(&self, stat: AffName) -> usize {
|
||||
self.get_affinity(stat).len()
|
||||
}
|
||||
|
||||
/// Get a reference to an affinity vector
|
||||
fn get_affinity(&self, stat: AffName) -> &Vec<(CreatureVecId, f64)> {
|
||||
&self.inner[stat as usize]
|
||||
}
|
||||
|
||||
/// Find the id in the vector associated to the inner id
|
||||
pub(super) fn to_vec_id(&self, creature_id: CreatureInnerId, stat: AffName) -> CreatureVecId {
|
||||
self.inner[stat as usize][creature_id.id()].0
|
||||
}
|
||||
|
||||
#[deprecated]
|
||||
#[allow(dead_code)]
|
||||
/// Find the inner id associated to the creature_id give
|
||||
pub(super) fn to_inner_id(&self, creature_id: CreatureVecId, stat: AffName) -> CreatureInnerId {
|
||||
// let a = &self.[creature_id.id()];
|
||||
self.inner[stat as usize]
|
||||
.iter()
|
||||
.enumerate()
|
||||
.find(|(_index, (id, _))| &creature_id == id)
|
||||
.map(|(id, _)| id.into())
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
// /// Consume the config object to add it to the CharacStatMatrix
|
||||
// #[deprecated]
|
||||
// pub(super) fn add_config(&mut self, config: StatConfig) {
|
||||
// self.config = config;
|
||||
// }
|
||||
|
||||
/// Get the level of verbosity
|
||||
pub(super) fn verbose(&self) -> bool {
|
||||
self.config.verbosity
|
||||
}
|
||||
|
||||
/// Get a reference to the active config
|
||||
#[allow(dead_code)]
|
||||
pub(super) fn get_config(&self) -> &StatConfig {
|
||||
&self.config
|
||||
}
|
||||
|
||||
/// Sort the underlying data
|
||||
pub(super) fn sort(&mut self) {
|
||||
for v in self.inner.iter_mut() {
|
||||
v.sort_unstable_by(|(_, v1), (_, v2)| v1.total_cmp(v2))
|
||||
}
|
||||
}
|
||||
/// Sort the underlying data in the reverse order
|
||||
pub(super) fn reverse_sort(&mut self) {
|
||||
for v in self.inner.iter_mut() {
|
||||
v.sort_unstable_by(|(_, v1), (_, v2)| v2.total_cmp(v1))
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove the creature to avoid doing incessant lookups
|
||||
pub(super) fn remove_creature_from_stat(
|
||||
&mut self,
|
||||
creature_id: CreatureInnerId,
|
||||
stat: AffName,
|
||||
) {
|
||||
let _rem = self.inner[stat as usize].remove(creature_id.id());
|
||||
// println!(
|
||||
// " ==> Removing stat {:?} on creature {} (was: {:?})",
|
||||
// stat,
|
||||
// self.creature_name(_rem.0),
|
||||
// _rem.1
|
||||
// );
|
||||
}
|
||||
}
|
||||
|
||||
// impl From<Vec<Creature>> for CharacCharMatrix {
|
||||
impl CharacCharMatrix {
|
||||
/// Create a CharacCharMatrix from a vec of creature and a config
|
||||
fn from_vec(creatures: Vec<Creature>, config: StatConfig) -> Self {
|
||||
let size = creatures.len() + 1;
|
||||
let mut inner = vec![
|
||||
Vec::<(CreatureVecId, Affinity)>::with_capacity(size),
|
||||
Vec::<(CreatureVecId, Affinity)>::with_capacity(size),
|
||||
Vec::<(CreatureVecId, Affinity)>::with_capacity(size),
|
||||
Vec::<(CreatureVecId, Affinity)>::with_capacity(size),
|
||||
Vec::<(CreatureVecId, Affinity)>::with_capacity(size),
|
||||
Vec::<(CreatureVecId, Affinity)>::with_capacity(size),
|
||||
Vec::<(CreatureVecId, Affinity)>::with_capacity(size),
|
||||
Vec::<(CreatureVecId, Affinity)>::with_capacity(size),
|
||||
];
|
||||
|
||||
for (creature_id, creature) in creatures.iter().enumerate() {
|
||||
for (index, value) in creature.affinities.affinity.iter().enumerate() {
|
||||
inner[index].push((creature_id.into(), *value));
|
||||
}
|
||||
}
|
||||
let mut r = Self {
|
||||
inner,
|
||||
creatures,
|
||||
config,
|
||||
};
|
||||
r.init();
|
||||
r
|
||||
}
|
||||
}
|
||||
|
||||
/// Load all the records in the csv
|
||||
pub(super) fn load_stat_records<T>(filename: T, config: StatConfig) -> Result<CharacCharMatrix>
|
||||
where
|
||||
T: AsRef<Path>,
|
||||
{
|
||||
let file = File::open(filename)?;
|
||||
let rdr = csv::ReaderBuilder::new()
|
||||
.has_headers(true)
|
||||
.delimiter(b',')
|
||||
.double_quote(false)
|
||||
.escape(Some(b'\\'))
|
||||
.flexible(true)
|
||||
.comment(Some(b'#'))
|
||||
.from_reader(file);
|
||||
|
||||
let creatures: Vec<Creature> = rdr
|
||||
.into_records()
|
||||
.flat_map(|c| Creature::try_from(c.unwrap()))
|
||||
.collect();
|
||||
let creature_matrix = CharacCharMatrix::from_vec(creatures, config);
|
||||
Ok(creature_matrix)
|
||||
}
|
||||
|
|
@ -0,0 +1,87 @@
|
|||
// Workspace: stats
|
||||
// File: stats/src/stats_structs.rs
|
||||
//! The module `stats_repartition` handles the repartition of stats on creatures.
|
||||
//! It includes structs and methods for managing the fitness of a solution and the
|
||||
//! weights of different affinities
|
||||
|
||||
use std::{iter::Cycle, vec::IntoIter};
|
||||
|
||||
use crate::stat_io::AffName;
|
||||
/// How much a solution fits the algorithm, or how much a solution fits a creature
|
||||
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Copy, Clone)]
|
||||
pub(super) enum Fit {
|
||||
/// Weakest fit, can't be used
|
||||
VeryWeak,
|
||||
/// Weak fit, shouldn't be used
|
||||
Weak,
|
||||
/// Average fit, can be used
|
||||
Medium,
|
||||
/// Strong fit, will always be used
|
||||
Strong,
|
||||
/// Best fit, must use
|
||||
VeryStrong,
|
||||
}
|
||||
impl Fit {
|
||||
/// Lower the fitness by one, with an optionnal maximum
|
||||
pub(super) fn lower(&self, min: Option<Fit>) -> Option<Fit> {
|
||||
let f = match self {
|
||||
Fit::VeryWeak => None,
|
||||
Fit::Weak => Some(Fit::VeryWeak),
|
||||
Fit::Medium => Some(Fit::Weak),
|
||||
Fit::Strong => Some(Fit::Medium),
|
||||
Fit::VeryStrong => Some(Fit::Strong),
|
||||
};
|
||||
if f <= min {
|
||||
return None;
|
||||
}
|
||||
f
|
||||
}
|
||||
|
||||
/// Raise the fitness level by one, with an optionnal maximum
|
||||
pub(super) fn upper(&self, min: Option<Fit>) -> Option<Fit> {
|
||||
let f = match self {
|
||||
Fit::VeryWeak => Some(Fit::Weak),
|
||||
Fit::Weak => Some(Fit::Medium),
|
||||
Fit::Medium => Some(Fit::Strong),
|
||||
Fit::Strong => Some(Fit::VeryStrong),
|
||||
Fit::VeryStrong => None,
|
||||
};
|
||||
if f <= min {
|
||||
return None;
|
||||
}
|
||||
f
|
||||
}
|
||||
}
|
||||
/// A stat weight level (Affinity name and weight)
|
||||
type StatWeightsTuple = Vec<(AffName, usize)>;
|
||||
|
||||
/// The statweights, holding looping methods
|
||||
#[derive(Debug)]
|
||||
pub(super) struct StatWeightList {
|
||||
/// The list of all affinities
|
||||
weights: Vec<AffName>,
|
||||
}
|
||||
impl StatWeightList {
|
||||
/// Iterate over all affinites to fill, endlessly
|
||||
pub(super) fn iter_cycle(self) -> Cycle<IntoIter<AffName>> {
|
||||
self.weights.into_iter().cycle()
|
||||
}
|
||||
}
|
||||
|
||||
impl From<StatWeightsTuple> for StatWeightList {
|
||||
fn from(mut value: StatWeightsTuple) -> Self {
|
||||
let ln = value.iter().rfold(0, |acc, (_, w)| acc + w);
|
||||
let mut weights = Vec::with_capacity(ln);
|
||||
let mut i = 0;
|
||||
while i < ln {
|
||||
for (w, nb) in value.iter_mut() {
|
||||
if nb != &0 {
|
||||
*nb -= 1;
|
||||
weights.push(*w);
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
Self { weights }
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,65 @@
|
|||
// Workspace: stats
|
||||
// File: stats/src/stats.rs
|
||||
//! The module `stats` handles stats disparity between all origins
|
||||
//!
|
||||
//! # Usage
|
||||
//!
|
||||
//! - [stat_solver]: Main solver function, in charge of selecting algorithms and handling all program flow
|
||||
//!
|
||||
//! It consists of several submodules:
|
||||
//!
|
||||
//! - `stat_algo`: Contains the algorithm implementations for finding solutions to the statistics problem.
|
||||
//! - `stat_structs`: Defines data structures used for managing statistical weights and matrix operations.
|
||||
//! - `stat_io`: Handles input/output operations, such as loading stat records from configuration files.
|
||||
use crate::{
|
||||
stat_algo::{Mode, find_all_fits},
|
||||
stat_structs::StatWeightList,
|
||||
};
|
||||
|
||||
use crate::stat_io::{AffName, CharacCharMatrix, load_stat_records};
|
||||
use anyhow::Result;
|
||||
use cli_parser::Config;
|
||||
use config::statsolver::StatConfig;
|
||||
|
||||
/// Main solver function, in charge of selecting algorithms and handling all program flow
|
||||
pub fn stat_solver(args: &StatConfig, config: &Config) -> Result<()> {
|
||||
let _ = config;
|
||||
let mut statmatrix = load_stat_records(&args.config_path, args.clone()).unwrap();
|
||||
solution_from_empty(&mut statmatrix).unwrap();
|
||||
if args.verbosity {
|
||||
println!("{:?}", statmatrix.print_weights());
|
||||
}
|
||||
statmatrix.print_solutions();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Find a solution from an empty solution (algo1)
|
||||
fn solution_from_empty(statmatrix: &mut CharacCharMatrix) -> Result<()> {
|
||||
// while statmatrix.not_filled() {}
|
||||
let stats_desired = vec![
|
||||
(AffName::F, 4),
|
||||
(AffName::Ag, 3),
|
||||
(AffName::Per, 3),
|
||||
(AffName::Psy, 3),
|
||||
(AffName::Int, 1),
|
||||
(AffName::Vol, 1),
|
||||
];
|
||||
let stats_undesirable = vec![
|
||||
(AffName::Int, 3),
|
||||
(AffName::Vol, 3),
|
||||
(AffName::Chr, 2),
|
||||
(AffName::Chn, 2),
|
||||
(AffName::F, 1),
|
||||
(AffName::Ag, 1),
|
||||
(AffName::Per, 1),
|
||||
(AffName::Psy, 1),
|
||||
];
|
||||
|
||||
let sw = StatWeightList::from(stats_desired).iter_cycle();
|
||||
let nsw = StatWeightList::from(stats_undesirable).iter_cycle();
|
||||
find_all_fits(statmatrix, sw, Mode::Positive).unwrap();
|
||||
find_all_fits(statmatrix, nsw, Mode::Negative).unwrap();
|
||||
// find_all_negative_fits(statmatrix, nsw).unwrap();
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
|
@ -0,0 +1,18 @@
|
|||
[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"] }
|
||||
|
||||
|
|
@ -0,0 +1,29 @@
|
|||
// Workspace: tablegen
|
||||
// File: tablegen/src/lib.rs
|
||||
//! This is a library for generating LaTeX tables from TSV files.
|
||||
//!
|
||||
//! The main entry point of this library is the `table_gen` function, which takes in configuration arguments and a config object,
|
||||
//! then processes the specified files according to their type (classes, craft, etc.).
|
||||
//! If an error occurs during processing, it will be reported via a Result.
|
||||
//!
|
||||
//! This library consists of several modules:
|
||||
//!
|
||||
//! - `table_structs`: Defines the structure and behavior of tables. It includes types like `RecordClass` representing
|
||||
//! a class record in a TSV file and `ClassesArray` holding all the data for classes.
|
||||
//! - `table_types`: Contains types related to TSV files and LaTeX code generation.
|
||||
//! It provides structures like `GenericArray` for creating tables based on generic records,
|
||||
//! and utility types like `CleanString` for handling string formatting specific to LaTeX tables.
|
||||
//! - `tablegen`: Contatining the whole logic behind the table generation
|
||||
//!
|
||||
//! The following functions are re-exported from the module `tablegen`:
|
||||
//!
|
||||
//! - [`table_gen`]: Handling the whole conversion and auto dispatch.
|
||||
|
||||
#![warn(missing_docs, clippy::missing_docs_in_private_items)]
|
||||
mod table_structs;
|
||||
mod table_types;
|
||||
mod tablegen;
|
||||
use cli_parser::Config;
|
||||
|
||||
// Reexport
|
||||
pub use tablegen::table_gen;
|
||||
|
|
@ -0,0 +1,53 @@
|
|||
// Workspace: tablegen
|
||||
// File: tablegen/src/table_structs.rs
|
||||
//! The module `table_structs` contains the base structs needed for the tablegen to function.
|
||||
use phf::phf_map;
|
||||
use regex::Regex;
|
||||
use regex_static::once_cell::sync::Lazy;
|
||||
|
||||
/// All the type of tsv that can be processed by the program
|
||||
// #[enum_dispatch]
|
||||
#[derive(Clone)]
|
||||
pub enum TableTargets {
|
||||
/// A class tsv
|
||||
Classes,
|
||||
/// Foods tsv
|
||||
Food,
|
||||
/// Alchemy tsv
|
||||
Alchemy,
|
||||
/// Forge tsv
|
||||
Forge,
|
||||
/// MPieges tsv
|
||||
MPieges,
|
||||
/// Weapons tsv
|
||||
Weapons,
|
||||
/// Armors tsv
|
||||
Armors,
|
||||
/// Gadgets tsv
|
||||
Gadgets,
|
||||
/// Potions tsv
|
||||
Potions,
|
||||
/// Traps tsv
|
||||
Traps,
|
||||
}
|
||||
|
||||
/// A mapping of string names to target types.
|
||||
pub(super) static STR_TO_TARGET_FULL: phf::Map<&'static str, TableTargets> = phf_map! {
|
||||
"cls" => TableTargets::Classes,
|
||||
"fud" => TableTargets::Food,
|
||||
"alc" => TableTargets::Alchemy,
|
||||
"frg" => TableTargets::Forge,
|
||||
"mpi" => TableTargets::MPieges,
|
||||
"wpn" => TableTargets::Weapons,
|
||||
"arm" => TableTargets::Armors,
|
||||
"gdg" => TableTargets::Gadgets,
|
||||
"pot" => TableTargets::Potions,
|
||||
"trp" => TableTargets::Traps,
|
||||
};
|
||||
|
||||
/// The regex for finding and replacing all stars with a custom DD
|
||||
pub(super) static RE_STARS: Lazy<Regex> = regex_static::lazy_regex!(r"★+");
|
||||
/// The regex for finding and replacing all +/- stars with a custom DD
|
||||
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"\([\+-]+\)");
|
||||
|
|
@ -0,0 +1,285 @@
|
|||
// Workspace: tablegen
|
||||
// File: tablegen/src/table_types.rs
|
||||
//! This module provides functionality for creating LaTeX tables based on data extracted from TSV files.
|
||||
//!
|
||||
//! It consists of several main components:
|
||||
//!
|
||||
//! - `RecordClass`: Represents a single row in a martial class TSV file and implements the `WriteRow` trait for writing table rows.
|
||||
//! - `ClassesArray`: Holds all the data for classes and provides methods to write the entire table as a string.
|
||||
//! - `GenericArray<RecordType>`: A generic structure for holding any type of records that implement the `WriteRow` trait and can be written as a LaTeX table.
|
||||
//! - `StringRecord`: Represents a row in a TSV file as a vector of strings.
|
||||
//!
|
||||
//! The module also includes utility types like `CleanString` for handling string formatting specific to LaTeX tables.
|
||||
|
||||
use crate::{Config, table_structs::TableTargets, tablegen::make_latex_string};
|
||||
use anyhow::{Context, Result};
|
||||
use csv::StringRecord;
|
||||
// use csv::StringRecord;
|
||||
use dynfmt::{Format, SimpleCurlyFormat};
|
||||
use serde::Deserialize;
|
||||
use std::{
|
||||
fmt::{self, Debug},
|
||||
io::{BufWriter, Write},
|
||||
};
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(rename_all = "PascalCase")]
|
||||
/// A single row in a martial class tsv file
|
||||
pub(super) struct RecordClass {
|
||||
/// 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: CleanString,
|
||||
/// The gauge cost for this technique.
|
||||
pub cout_jauge: CleanString,
|
||||
/// A brief description of the effect or outcome of using this technique.
|
||||
pub effet: CleanString,
|
||||
}
|
||||
|
||||
impl WriteRow for RecordClass {
|
||||
fn write_header(
|
||||
&self,
|
||||
_buffer: &mut BufWriter<Vec<u8>>,
|
||||
_config: &Config,
|
||||
_format: &str,
|
||||
) -> Result<()> {
|
||||
unimplemented!()
|
||||
}
|
||||
|
||||
fn write_row(
|
||||
&self,
|
||||
buffer: &mut BufWriter<Vec<u8>>,
|
||||
_config: &Config,
|
||||
_format: &str,
|
||||
) -> Result<()> {
|
||||
Ok(writeln!(
|
||||
buffer,
|
||||
" {}&{}&{}&{}{}&{} \\\\",
|
||||
self.technique,
|
||||
self.niveau,
|
||||
self.technique_type,
|
||||
self.cout_blood,
|
||||
self.cout_jauge,
|
||||
self.effet
|
||||
)?)
|
||||
}
|
||||
|
||||
fn write_footer(
|
||||
&self,
|
||||
_buffer: &mut BufWriter<Vec<u8>>,
|
||||
_config: &Config,
|
||||
_format: &str,
|
||||
) -> Result<()> {
|
||||
unimplemented!()
|
||||
}
|
||||
}
|
||||
/// Represents the whole Classes Array, with a vec for every tier
|
||||
pub(super) struct ClassesArray {
|
||||
/// Every tier held as a vec of vec of rows
|
||||
pub tiers: Vec<Vec<RecordClass>>,
|
||||
}
|
||||
|
||||
/// Trait needed to be writable as a LaTex table
|
||||
pub(super) trait WriteTable {
|
||||
/// Takes a config and writes to a string the representation of the Array
|
||||
fn write_table(&self, config: &Config) -> Result<String>;
|
||||
}
|
||||
/// Trait needed to be writable as a LaTex table
|
||||
pub(super) trait WriteRow {
|
||||
/// Write the header of the LaTex table
|
||||
fn write_header(
|
||||
&self,
|
||||
buffer: &mut BufWriter<Vec<u8>>,
|
||||
config: &Config,
|
||||
format: &str,
|
||||
) -> Result<()>;
|
||||
/// Write the row of the LaTex table
|
||||
fn write_row(
|
||||
&self,
|
||||
buffer: &mut BufWriter<Vec<u8>>,
|
||||
config: &Config,
|
||||
format: &str,
|
||||
) -> Result<()>;
|
||||
/// Write the row of the LaTex table
|
||||
fn write_footer(
|
||||
&self,
|
||||
buffer: &mut BufWriter<Vec<u8>>,
|
||||
config: &Config,
|
||||
format: &str,
|
||||
) -> Result<()>;
|
||||
}
|
||||
|
||||
/// This table stores it's row types
|
||||
pub(super) trait TypedRow {
|
||||
/// Get the row type of the table
|
||||
fn get_type(&self) -> &TableTargets;
|
||||
}
|
||||
|
||||
impl WriteTable for ClassesArray {
|
||||
fn write_table(&self, config: &Config) -> Result<String> {
|
||||
let mut buffer = BufWriter::new(Vec::new());
|
||||
let mut header_string = String::new();
|
||||
let mut o_row;
|
||||
let mut c_row = -1;
|
||||
for (lvl, tier) in self.tiers.iter().skip(1).enumerate() {
|
||||
c_row += 3;
|
||||
o_row = c_row;
|
||||
// rt_write!(buffer, config.classes.header, lvl + 1)?;
|
||||
let formatted_tier = SimpleCurlyFormat
|
||||
.format(&config.classes.tier, [lvl + 1])
|
||||
.expect("Formatting of header failed");
|
||||
// TODO: FIX THIS ABOMINATION
|
||||
if lvl > 3 {
|
||||
continue;
|
||||
}
|
||||
if lvl != 0 {
|
||||
writeln!(buffer, "{}", config.classes.sep)?;
|
||||
}
|
||||
writeln!(buffer, "{}", formatted_tier)?;
|
||||
for elem in tier {
|
||||
c_row += 1;
|
||||
elem.write_row(&mut buffer, config, NO_STRING)?
|
||||
}
|
||||
writeln!(buffer, "\\hline")?;
|
||||
header_string.push_str(&format!(
|
||||
" vline{{1,6}} = {{{}-{}}}{{solid}},\n",
|
||||
o_row, c_row
|
||||
));
|
||||
// .expect("Writing header format");
|
||||
}
|
||||
writeln!(buffer, "{}", config.classes.end)?;
|
||||
let formatted_header = SimpleCurlyFormat
|
||||
.format(&config.classes.header, ["{longtblr}", &header_string])
|
||||
.expect("Couldn't format the table header");
|
||||
buffer.flush()?;
|
||||
let mut h = formatted_header.as_bytes().to_vec();
|
||||
h.extend_from_slice(&buffer.into_inner()?);
|
||||
// writeln!(buffer, "{}", &config.classes.header)?;
|
||||
Ok(String::from_utf8(h)?)
|
||||
}
|
||||
}
|
||||
|
||||
/// Represents the whole Craft Array, with a vec for every tier
|
||||
pub(super) struct GenericArray<RecordType>
|
||||
where
|
||||
RecordType: WriteRow,
|
||||
{
|
||||
/// Every tier held as a vec of vec of rows
|
||||
pub row: Vec<RecordType>,
|
||||
/// Inner craft type, since the array is genric
|
||||
pub craft_type: TableTargets,
|
||||
}
|
||||
|
||||
impl<RecordType> WriteTable for GenericArray<RecordType>
|
||||
where
|
||||
RecordType: WriteRow,
|
||||
{
|
||||
fn write_table(&self, config: &Config) -> Result<String> {
|
||||
let mut buffer = BufWriter::new(Vec::new());
|
||||
let header = match self.craft_type {
|
||||
TableTargets::Classes => unimplemented!(),
|
||||
TableTargets::Food => &config.craft.header_food,
|
||||
TableTargets::Alchemy => &config.craft.header_alchemy,
|
||||
TableTargets::Forge => &config.craft.header_forge,
|
||||
TableTargets::MPieges => &config.craft.header_mtrap,
|
||||
TableTargets::Weapons => &config.craft.header_weapons,
|
||||
TableTargets::Armors => &config.craft.header_armors,
|
||||
TableTargets::Gadgets => &config.craft.header_gadgets,
|
||||
TableTargets::Potions => &config.craft.header_potions,
|
||||
TableTargets::Traps => &config.craft.header_traps,
|
||||
};
|
||||
// let ln = self.row.len();
|
||||
// if ln < 2 {
|
||||
// return Err(anyhow!("No entries were found in the tsv"));
|
||||
// }
|
||||
self.row[0].write_header(&mut buffer, config, header)?;
|
||||
// for row in 2..=ln - 2 {
|
||||
// self.row[row].write_row(&mut buffer, config, NO_STRING)?;
|
||||
// writeln!(buffer, "\\\\")?;
|
||||
// }
|
||||
// self.row[ln - 1].write_row(&mut buffer, config, NO_STRING)?;
|
||||
for row in self.row.iter().skip(2) {
|
||||
row.write_row(&mut buffer, config, NO_STRING)?;
|
||||
}
|
||||
let footer = match self.get_type() {
|
||||
TableTargets::Classes => unimplemented!("Classes can't be handled by generics"),
|
||||
TableTargets::Gadgets | TableTargets::Potions => &config.craft.end_long,
|
||||
_ => &config.craft.end_long_side,
|
||||
};
|
||||
self.row[0].write_footer(&mut buffer, config, footer)?;
|
||||
Ok(String::from_utf8(buffer.into_inner()?)?)
|
||||
}
|
||||
}
|
||||
|
||||
impl<RecordType> TypedRow for GenericArray<RecordType>
|
||||
where
|
||||
RecordType: WriteRow,
|
||||
{
|
||||
fn get_type(&self) -> &TableTargets {
|
||||
&self.craft_type
|
||||
}
|
||||
}
|
||||
|
||||
impl WriteRow for StringRecord {
|
||||
fn write_header(
|
||||
&self,
|
||||
buffer: &mut std::io::BufWriter<Vec<u8>>,
|
||||
_config: &Config,
|
||||
format: &str,
|
||||
) -> Result<()> {
|
||||
writeln!(buffer, "{}", format).context("Writing header")
|
||||
}
|
||||
|
||||
fn write_row(
|
||||
&self,
|
||||
buffer: &mut std::io::BufWriter<Vec<u8>>,
|
||||
_config: &Config,
|
||||
_format: &str,
|
||||
) -> Result<()> {
|
||||
let mut itr = self.into_iter();
|
||||
write!(
|
||||
buffer,
|
||||
" {}",
|
||||
itr.next().context("Writing element of row")?
|
||||
)?;
|
||||
for e in itr {
|
||||
write!(buffer, " & {}", make_latex_string(e)).context("Writing row")?
|
||||
}
|
||||
// Must switch to manual row writing to avoid empty line if tex
|
||||
writeln!(buffer, "\\\\").context("Writing row")
|
||||
}
|
||||
|
||||
fn write_footer(
|
||||
&self,
|
||||
buffer: &mut std::io::BufWriter<Vec<u8>>,
|
||||
_config: &Config,
|
||||
format: &str,
|
||||
) -> Result<()> {
|
||||
writeln!(buffer, "{}", format).context("Writing footer")
|
||||
}
|
||||
}
|
||||
|
||||
/// Empty string
|
||||
const NO_STRING: &String = &String::new();
|
||||
|
||||
/// This type is used to represent strings in LaTeX tables, where certain characters need to be escaped or replaced with special commands.
|
||||
#[derive(Deserialize)]
|
||||
pub(super) struct CleanString(String);
|
||||
|
||||
impl fmt::Debug for CleanString {
|
||||
#[inline]
|
||||
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
|
||||
<String as fmt::Debug>::fmt(&self.0, f)
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for CleanString {
|
||||
#[inline]
|
||||
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
|
||||
f.write_str(&make_latex_string(&self.0))
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,291 @@
|
|||
// Workspace: tablegen
|
||||
// File: tablegen/src/tablegen.rs
|
||||
//! The tsv table generation module contains functionalities to read, convert and export TSV files.
|
||||
//!
|
||||
//! This module provides functionality for reading a tab-separated values (TSV) file into a table structure,
|
||||
//! converting the table data into LaTeX code, and exporting the resulting code as a string or writing it to a file.
|
||||
//!
|
||||
//! # Usage
|
||||
//!
|
||||
//! The `table_gen` function is the main entry point of this module. It takes in configuration arguments and a
|
||||
//! config object, then processes the specified files according to their type (classes, craft, etc.). If an error occurs during processing,
|
||||
//! it will be reported via a Result. For more information on each function's usage, see the respective sections below.
|
||||
//!
|
||||
//! # Functions
|
||||
//!
|
||||
//! - [`table_gen`]: Generates the tables for the specified files.
|
||||
//! - [`process_files`]: Processes any type of file, one by one and calls the right converter function.
|
||||
//! - [`export_tsv`]: Converts a TSV file to LaTeX code.
|
||||
//! - [`make_latex_string`]: Replaces all instances of unrepresentable utf8 or non escaped characters with latex ones.
|
||||
//! - [`read_tsv_classes`]: Reads a TSV file into a table for classes.
|
||||
//! - [`read_generic_tsv`]: Reads a TSV file into a table for generic types.
|
||||
//! - [`tsv_to_string`]: Converts a table of data into a string representation.
|
||||
//!
|
||||
//! # Submodules
|
||||
//!
|
||||
//! 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 config::tablegen::{TableArgs, TableGenerationTarget};
|
||||
use glob::glob;
|
||||
use regex::Captures;
|
||||
use std::{
|
||||
cell::RefCell,
|
||||
fs::File,
|
||||
io::{Error, Write},
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
|
||||
use crate::{
|
||||
Config,
|
||||
table_structs::{RE_MATHS, RE_PLUS_STARS, RE_STARS, STR_TO_TARGET_FULL, TableTargets},
|
||||
table_types::{ClassesArray, GenericArray, RecordClass, WriteTable},
|
||||
};
|
||||
|
||||
/// Generate the tables for the specified files
|
||||
///
|
||||
/// In charge of the dispatch and the whole conversion
|
||||
pub fn table_gen(args: &TableArgs, config: &Config) -> Result<()> {
|
||||
let list_files = match args.kind {
|
||||
TableGenerationTarget::Classes => {
|
||||
println!("Processing files in the Tables/ subdirectory");
|
||||
&mut list_dir("Tables/??? - *.tsv")
|
||||
}
|
||||
TableGenerationTarget::Craft => {
|
||||
println!("Processing files in the Craft/ subdirectory");
|
||||
&mut list_dir("Craft/??? - *.tsv")
|
||||
}
|
||||
// Add the use of glob to save the poor windows users
|
||||
TableGenerationTarget::Files => {
|
||||
println!("Processing the files given as argument");
|
||||
&mut args.filenames.iter().map(PathBuf::from).collect()
|
||||
}
|
||||
TableGenerationTarget::All => &mut {
|
||||
println!("Processing files in the Tables and Craft subdirectory");
|
||||
let mut targets = list_dir("Tables/??? - *.tsv");
|
||||
targets.append(&mut list_dir("Craft/??? - *.tsv"));
|
||||
targets
|
||||
},
|
||||
};
|
||||
|
||||
if list_files.is_empty() {
|
||||
println!("No files to process ... skipping");
|
||||
}
|
||||
// match args.kind {
|
||||
// TableGenerationTarget::Classes => process_files(list_files, args, config),
|
||||
// TableGenerationTarget::Craft => process_files(list_files, args, config),
|
||||
// // For now every file is considered as a class file
|
||||
// TableGenerationTarget::Files => process_files(list_files, args, config),
|
||||
// TableGenerationTarget::All =>process_files(list_files, args, config),
|
||||
// }
|
||||
process_files(list_files, args, config)
|
||||
}
|
||||
|
||||
/// Process any type of file, one by one and call the right converter function
|
||||
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) {
|
||||
println!("An error occured while processing the file {:?}\n{}", f, e)
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Process one file
|
||||
fn process_one_file(f: &mut PathBuf, args: &TableArgs, config: &Config) -> Result<()> {
|
||||
let tt = extract_type(f)?;
|
||||
let tsv: Box<dyn WriteTable> = match tt {
|
||||
TableTargets::Classes => Box::new(read_tsv_classes(f)?),
|
||||
// TableTargets::Food => read_tsv::<RecordFood>(f)?,
|
||||
// TableTargets::Alchemy => read_tsv::<RecordAlchemy>(f)?,
|
||||
// TableTargets::Forge => read_tsv::<RecordForge>(f)?,
|
||||
_ => read_generic_tsv(f, tt)?,
|
||||
};
|
||||
|
||||
export_tsv(f, tsv, args, config)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
/// 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];
|
||||
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\
|
||||
Are you sure {:?} contains a viable identifying prefix ?\n\
|
||||
The list of available prefixes is: [{:?}]",
|
||||
key,
|
||||
f,
|
||||
STR_TO_TARGET_FULL.keys()
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
/// 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()
|
||||
}
|
||||
|
||||
/// Converts a TSV file to LaTeX code.
|
||||
///
|
||||
/// 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.
|
||||
pub fn export_tsv(
|
||||
f: &Path,
|
||||
tsv: Box<dyn WriteTable>,
|
||||
args: &TableArgs,
|
||||
config: &Config,
|
||||
) -> Result<()> {
|
||||
let converted = tsv_to_string(tsv, config)?;
|
||||
if args.export {
|
||||
let name = &f
|
||||
.file_name()
|
||||
.context("Extracting old name")?
|
||||
.to_str()
|
||||
.context("Generating new name")?[12..];
|
||||
let name = format!("gen-{}", name);
|
||||
let path = f.with_file_name(name).with_extension("tex");
|
||||
println!("[Info] Writing to {:?}", path);
|
||||
let mut file = File::create(path)?;
|
||||
file.write_all(converted.as_bytes())?;
|
||||
} else {
|
||||
println!("###### [FILE:{:?}] ######", f);
|
||||
println!("{}", converted);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Replace all instances of unrepresentable utf8 or non escaped characters with latex ones
|
||||
pub(super) fn make_latex_string(arg: &str) -> String {
|
||||
let res = arg
|
||||
.replace('🩸', "\\blood{}")
|
||||
.replace('⚡', "\\gauge{}")
|
||||
.replace('☽', "\\slash{}")
|
||||
.replace('◅', "\\pierce{}")
|
||||
.replace('⧆', "\\blunt{}")
|
||||
.replace('Ø', "\\o{}")
|
||||
.replace('⌭', "\\torque{}")
|
||||
.replace('☆', "\\ddzero{}")
|
||||
.replace('🗘', "\\reload{}")
|
||||
.replace('½', "\\sfrac{1}{2}")
|
||||
.replace("0.5", "\\sfrac{1}{2}")
|
||||
.replace('&', "\\&");
|
||||
let res = RE_PLUS_STARS.replace_all(&res, |caps: &Captures| {
|
||||
format!("\\ddmod{{{}}}{{{}}}", &caps[1], caps[2].chars().count())
|
||||
});
|
||||
let res = RE_STARS.replace_all(&res, |caps: &Captures| {
|
||||
format!("\\ddlvl{{{}}}", caps[0].chars().count())
|
||||
});
|
||||
let res = RE_MATHS.replace_all(&res, |caps: &Captures| format!("${}$", &caps[0]));
|
||||
res.to_string()
|
||||
}
|
||||
|
||||
/// Reads a TSV file into a table.
|
||||
///
|
||||
/// 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.
|
||||
fn read_tsv_classes<T>(filename: &T) -> Result<ClassesArray, Error>
|
||||
where
|
||||
T: AsRef<Path>,
|
||||
{
|
||||
let file = File::open(filename)?;
|
||||
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 levels = Vec::with_capacity(8);
|
||||
let current_tier = RefCell::new(Vec::with_capacity(6));
|
||||
for result in rdr.deserialize() {
|
||||
let result: RecordClass = result?;
|
||||
if result.technique.starts_with("Tier ") {
|
||||
// Getto way of knowing we have a new tier
|
||||
let old_tier = current_tier.replace(Vec::with_capacity(8));
|
||||
levels.push(old_tier);
|
||||
} else if (result.technique == "Technique") | result.technique.is_empty() {
|
||||
// Skip this entry
|
||||
} else {
|
||||
current_tier.borrow_mut().push(result);
|
||||
}
|
||||
}
|
||||
Ok(ClassesArray { tiers: levels })
|
||||
}
|
||||
|
||||
/// Reads a TSV file into a table.
|
||||
///
|
||||
/// Reads a tab-separated values (TSV) file and deserializes its contents into a table.
|
||||
fn read_generic_tsv(filename: &Path, craft_type: &TableTargets) -> Result<Box<dyn WriteTable>> {
|
||||
let file = File::open(filename)?;
|
||||
let 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 res = rdr
|
||||
.into_records()
|
||||
.map(|r| r.context("reading row").unwrap())
|
||||
.collect();
|
||||
|
||||
let craft_array = GenericArray {
|
||||
row: res,
|
||||
craft_type: craft_type.clone(),
|
||||
};
|
||||
let generic_array = Box::new(craft_array);
|
||||
Ok(generic_array)
|
||||
}
|
||||
|
||||
/// Converts a table of data into a string representation.
|
||||
///
|
||||
/// 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.
|
||||
pub(super) fn tsv_to_string(tsv: Box<dyn WriteTable>, config: &Config) -> Result<String> {
|
||||
tsv.write_table(config)
|
||||
}
|
||||
// /// Reads a TSV file into a table.
|
||||
// ///
|
||||
// /// Reads a tab-separated values (TSV) file and deserializes its contents into a table.
|
||||
// fn read_tsv<RecordType>(filename: &Path) -> Result<Box<dyn WriteTable>>
|
||||
// where
|
||||
// // TODO: Remove the static and do not return a Box
|
||||
// RecordType: for<'a> serde::Deserialize<'a> + WriteRow + 'static,
|
||||
// {
|
||||
// let file = File::open(filename)?;
|
||||
// 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 levels = Vec::with_capacity(30);
|
||||
// for result in rdr.deserialize().skip(2) {
|
||||
// let result: RecordType = result?;
|
||||
// levels.push(result);
|
||||
// }
|
||||
|
||||
// let craft_array = CraftArray { row: levels };
|
||||
// Ok(Box::new(craft_array))
|
||||
// }
|
||||
|
|
@ -0,0 +1,8 @@
|
|||
[last_run_clean]
|
||||
run_status = "Success"
|
||||
lines_parsed = 57
|
||||
coverage = 60.03
|
||||
|
||||
[last_run_clean.run_duration]
|
||||
secs = 19
|
||||
nanos = 961545465
|
||||
|
|
@ -0,0 +1,41 @@
|
|||
[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)'] }
|
||||
|
|
@ -0,0 +1,52 @@
|
|||
use criterion::{Criterion, criterion_group, criterion_main};
|
||||
use std::{hint::black_box, time::Duration};
|
||||
use weaponry::{
|
||||
interfaces::RecipeCollection,
|
||||
weaponry_structs::{Equipement, InitialEquipementList},
|
||||
};
|
||||
|
||||
fn criterion_benchmark(c: &mut Criterion) {
|
||||
let blk_steps = [
|
||||
InitialEquipementList::from_vectored(vec![Equipement::default(); 100]),
|
||||
InitialEquipementList::from_vectored(vec![Equipement::default(); 100]),
|
||||
InitialEquipementList::from_vectored(vec![Equipement::default(); 100]),
|
||||
];
|
||||
c.bench_function("creating 100 Elements", |b| {
|
||||
b.iter(|| {
|
||||
InitialEquipementList::from_vectored(black_box(vec![
|
||||
black_box(Equipement::default());
|
||||
100
|
||||
]))
|
||||
})
|
||||
});
|
||||
c.bench_function("IterGenBlanket: 100x100x100", |b| {
|
||||
b.iter(|| {
|
||||
let mut s = blk_steps[0].clone();
|
||||
s.combine_all(black_box(&blk_steps[1]));
|
||||
s.combine_all(black_box(&blk_steps[2]));
|
||||
})
|
||||
});
|
||||
// c.bench_function("IterGen: 100x100x100x100", |b| {
|
||||
// b.iter(|| {
|
||||
// let mut s = steps[0].clone();
|
||||
// s.combine_all(steps[1].clone());
|
||||
// s.combine_all(steps[2].clone());
|
||||
// s.combine_all(steps[2].clone());
|
||||
// })
|
||||
// });
|
||||
// c.bench_function("IterGenPar: 100x100x100x100", |b| {
|
||||
// b.iter(|| {
|
||||
// let mut s = par_steps[0].clone();
|
||||
// s.combine_all(par_steps[1].clone());
|
||||
// s.combine_all(par_steps[2].clone());
|
||||
// s.combine_all(par_steps[2].clone());
|
||||
// })
|
||||
// });
|
||||
}
|
||||
|
||||
criterion_group! {
|
||||
name = benches;
|
||||
config = Criterion::default().measurement_time(Duration::from_secs(10));
|
||||
targets= criterion_benchmark
|
||||
}
|
||||
criterion_main!(benches);
|
||||
|
|
@ -0,0 +1 @@
|
|||
# max_width = 278
|
||||
|
|
@ -0,0 +1,21 @@
|
|||
// Workspace: weaponry
|
||||
// File: examples/test_serialisation_wl.rs
|
||||
//! Test of an initial serialisation and scenario wl
|
||||
//! Doing this work on an example will help writing it as an integration test afterwards
|
||||
|
||||
use weaponry::interfaces::RecipeDatabase;
|
||||
use weaponry::weaponry_structs::equipement_impl_database::EquipementDatabase;
|
||||
use weaponry::weaponry_structs::equipement_structs::{DatabaseEquipementStats, InnerEquipementStats};
|
||||
|
||||
fn main() {
|
||||
let db = EquipementDatabase::new("./databases/weapons.db").unwrap();
|
||||
let initial_deserialisation = db.serialize_vec_from_table::<DatabaseEquipementStats>("Equipements", None);
|
||||
// println!("Initial deserialisation in DatabaseEquipementStats: {:?}", initial_deserialisation);
|
||||
// println!("First entry: {:?}", initial_deserialisation.as_ref().unwrap()[0]);
|
||||
|
||||
let intermediate_deserialisation = initial_deserialisation.unwrap().into_iter().map(InnerEquipementStats::try_from).collect::<Vec<_>>();
|
||||
let f = intermediate_deserialisation.iter().fold((0, 0), |val, res| (val.0 + res.is_ok() as usize, val.1 + 1_usize));
|
||||
// println!("Final data {:#?}", intermediate_deserialisation);
|
||||
println!("Failed to parse: {:#?}", intermediate_deserialisation.into_iter().filter_map(|v| v.err()).collect::<Vec<_>>());
|
||||
println!("Succeded in parsing {}/{}", f.0, f.1);
|
||||
}
|
||||
|
|
@ -0,0 +1,40 @@
|
|||
// Workspace: weaponry
|
||||
// File: examples/typical_wl_recipe.rs
|
||||
//! Example of a typical workload
|
||||
|
||||
use std::time::Instant;
|
||||
|
||||
use weaponry::{
|
||||
interfaces::RecipeCollection,
|
||||
weaponry_structs::{Equipement, InitialEquipementList},
|
||||
};
|
||||
|
||||
fn main() {
|
||||
let blk_steps = [
|
||||
InitialEquipementList::from_vectored(
|
||||
[1; 100].iter().map(|_| Equipement::default()).collect(),
|
||||
),
|
||||
InitialEquipementList::from_vectored(
|
||||
[1; 100].iter().map(|_| Equipement::default()).collect(),
|
||||
),
|
||||
InitialEquipementList::from_vectored(
|
||||
[1; 100].iter().map(|_| Equipement::default()).collect(),
|
||||
),
|
||||
];
|
||||
|
||||
// #[cfg(test)]
|
||||
// println!("{:#?}", blk_steps);
|
||||
let now = Instant::now();
|
||||
let mut s = blk_steps[0].clone();
|
||||
println!("First size {}", s.ref_inner().len());
|
||||
s.combine_all(&blk_steps[0]);
|
||||
println!("Second size {}", s.ref_inner().len());
|
||||
s.combine_all(&blk_steps[0]);
|
||||
println!("Third size {}", s.ref_inner().len());
|
||||
s.combine_all(&blk_steps[0]);
|
||||
|
||||
// println!("{:#?}", blk_steps);
|
||||
// println!("{:#?}", s);
|
||||
println!("Final size {}", s.ref_inner().len());
|
||||
println!("Ellapsed: {:?}", Instant::now().duration_since(now));
|
||||
}
|
||||
|
|
@ -0,0 +1,137 @@
|
|||
// Workspace: weaponry
|
||||
// File: examples/usage_scenario.rs
|
||||
//! Test use case of a scenario
|
||||
//!
|
||||
//!
|
||||
use clap::Parser;
|
||||
use std::cmp::Ordering;
|
||||
use std::path::Path;
|
||||
use weaponry::error::FatalEquipementError;
|
||||
use weaponry::interfaces::ToAnalysis;
|
||||
use weaponry::sort_by;
|
||||
use weaponry::sort_by_cat_then;
|
||||
use weaponry::weaponry_structs::RefinedEquipement;
|
||||
|
||||
// TODO[!] : All of these should likely be in the prelude if used like this
|
||||
use weaponry::weaponry_structs::CrossRecipeScenario;
|
||||
use weaponry::weaponry_structs::equipement_scenario::ConfigEquipementScenario;
|
||||
use weaponry::{
|
||||
interfaces::{Reportable, Scenario, ToCSV},
|
||||
weaponry_structs::RefinedEquipementList,
|
||||
};
|
||||
|
||||
fn main() {
|
||||
let args = CLIArgs::parse();
|
||||
let save_path = args.path.unwrap_or("data/first_data".into());
|
||||
let scenarios = CrossRecipeScenario::new_with_config(ConfigEquipementScenario {
|
||||
table_name: "Equipements".into(),
|
||||
db_path: "./databases/weapons.db".into(),
|
||||
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(|e| {
|
||||
e.inner.category_base.as_ref().is_some_and(|v| {
|
||||
!matches!(v, weaponry::weaponry_structs::WeaponBaseShape::Shields)
|
||||
&& !matches!(v, weaponry::weaponry_structs::WeaponBaseShape::Armors)
|
||||
})
|
||||
});
|
||||
|
||||
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}"),
|
||||
}
|
||||
// if args.html_export{}
|
||||
refined_list.write_html(&save_path).unwrap();
|
||||
|
||||
// if args.csv_export{}
|
||||
// export_as_csv(&refined_list, save_path);
|
||||
}
|
||||
#[derive(Parser, Debug)]
|
||||
/// Basic cli
|
||||
pub struct CLIArgs {
|
||||
/// 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"))]
|
||||
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
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
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")))
|
||||
);
|
||||
}
|
||||
|
||||
type DynamicFilterType = Box<dyn FnMut(&RefinedEquipement, &RefinedEquipement) -> Ordering>;
|
||||
|
||||
pub fn cmd_to_filter(og_entry: &str) -> Result<DynamicFilterType, FatalEquipementError> {
|
||||
let (category, entry) = if og_entry.starts_with("cat+") {
|
||||
(true, og_entry.split_at(4).1)
|
||||
} else {
|
||||
(false, og_entry)
|
||||
};
|
||||
|
||||
macro_rules! return_if_starts_with {
|
||||
($iden:ident) => {
|
||||
if stringify!($iden).starts_with(entry) {
|
||||
return match category {
|
||||
true => Ok(Box::new(sort_by_cat_then!($iden))),
|
||||
false => Ok(Box::new(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()))
|
||||
}
|
||||
|
|
@ -0,0 +1,40 @@
|
|||
# Introduction
|
||||
The generic nature of the recipe generator makes it rather complicated to navigate and comprehend;
|
||||
however while suffering from many developpement mistakes and shortcommings, a good deal of code reuse was averted
|
||||
|
||||
# Structure
|
||||
The inner structures follow the following.
|
||||
|
||||
| Underlaying data | Encapsulating Element | Encapsulating list of elements |
|
||||
|-----------------------|----------------------------|--------------------------------|
|
||||
| DatabaseInner (DeSer) | None | None |
|
||||
| BaseInner (Converted) | InitialElement | InitialElementList |
|
||||
| AdvancedInner (Calc) | RefinedElement (+BaseInner)| RefinedElementList |
|
||||
|
||||
|
||||
# Explainations
|
||||
| Category | Explainations | Traits | Impls |
|
||||
|---------------------|------------------------------|----------------------------------------|------------------------|
|
||||
| DatabaseInner | Deserialization InnerData | FieldsAsSclice | DatabaseEquipementStats|
|
||||
| BaseInner | BuildingBlock InnerData | FieldAsSlice, Add, From<DatabaseInner> | InnerEquipementStats |
|
||||
| AdvancedInner | Calculated data for analysis | Serialize, From<DatabaseInner> | AdvancedStats |
|
||||
| IntermediateElement | Setup InitialElement | | EqFinishing, etc.. |
|
||||
| InitialElement | Real Elements by Combination | From<InitalElement>, Combinable | Equipement |
|
||||
| RefinedElement | Export & Analysis | Serialize | RefinedEquipement |
|
||||
| InitialElementList | Create list by cross combin. | RecipeCollection | InitialEquipementList |
|
||||
| RefinedElementList | Analysis & Export | From<InitialElementList, (TBD) | RefinedEquipemenList |
|
||||
|
||||
# Workflow
|
||||
* Deserialize data in a deserializing struct
|
||||
* Convert it to a valid inner element data
|
||||
* Wrap in in an intermediate element to allow custom filters and advanced checks
|
||||
* Create an initial element from it
|
||||
* Wrap these element in a serie of list (by part, shape, finishing, etc).
|
||||
* Combine these list to create all final elements (by inner combination)
|
||||
* Process this combination of list into a RefinedElementList
|
||||
* Analysis or export
|
||||
* ????
|
||||
* Profit
|
||||
|
||||
|
||||
# Implementation
|
||||
|
|
@ -0,0 +1,322 @@
|
|||
<mxfile host="Electron" agent="Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) draw.io/26.0.9 Chrome/128.0.6613.186 Electron/32.2.5 Safari/537.36" version="26.0.9">
|
||||
<diagram id="C5RBs43oDa-KdzZeNtuy" name="Page-1">
|
||||
<mxGraphModel dx="410" dy="1179" grid="1" gridSize="10" guides="1" tooltips="1" connect="1" arrows="1" fold="1" page="1" pageScale="1" pageWidth="827" pageHeight="1169" math="0" shadow="0">
|
||||
<root>
|
||||
<mxCell id="WIyWlLk6GJQsqaUBKTNV-0" />
|
||||
<mxCell id="WIyWlLk6GJQsqaUBKTNV-1" parent="WIyWlLk6GJQsqaUBKTNV-0" />
|
||||
<mxCell id="dEHQTlttWntmzIJzVtkA-0" value="Database" style="swimlane;whiteSpace=wrap;html=1;" parent="WIyWlLk6GJQsqaUBKTNV-1" vertex="1">
|
||||
<mxGeometry x="310" y="30" width="200" height="90" as="geometry">
|
||||
<mxRectangle x="10" y="10" width="140" height="30" as="alternateBounds" />
|
||||
</mxGeometry>
|
||||
</mxCell>
|
||||
<mxCell id="dEHQTlttWntmzIJzVtkA-1" value="Data Tables" style="whiteSpace=wrap;html=1;" parent="dEHQTlttWntmzIJzVtkA-0" vertex="1">
|
||||
<mxGeometry x="10" y="30" width="180" height="20" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="dEHQTlttWntmzIJzVtkA-2" value="Recipe Tables" style="whiteSpace=wrap;html=1;" parent="dEHQTlttWntmzIJzVtkA-0" vertex="1">
|
||||
<mxGeometry x="10" y="60" width="180" height="20" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="dEHQTlttWntmzIJzVtkA-25" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;exitX=1;exitY=0.5;exitDx=0;exitDy=0;entryX=0.5;entryY=0;entryDx=0;entryDy=0;" parent="WIyWlLk6GJQsqaUBKTNV-1" source="dEHQTlttWntmzIJzVtkA-3" target="dEHQTlttWntmzIJzVtkA-8" edge="1">
|
||||
<mxGeometry relative="1" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="dEHQTlttWntmzIJzVtkA-26" value="FromVectored" style="edgeLabel;html=1;align=center;verticalAlign=middle;resizable=0;points=[];fontColor=#FFB366;fontStyle=1" parent="dEHQTlttWntmzIJzVtkA-25" vertex="1" connectable="0">
|
||||
<mxGeometry x="0.1668" y="-1" relative="1" as="geometry">
|
||||
<mxPoint as="offset" />
|
||||
</mxGeometry>
|
||||
</mxCell>
|
||||
<mxCell id="dEHQTlttWntmzIJzVtkA-3" value="Initial Object Representation" style="swimlane;whiteSpace=wrap;html=1;" parent="WIyWlLk6GJQsqaUBKTNV-1" vertex="1">
|
||||
<mxGeometry x="320" y="250" width="200" height="60" as="geometry">
|
||||
<mxRectangle x="10" y="160" width="190" height="30" as="alternateBounds" />
|
||||
</mxGeometry>
|
||||
</mxCell>
|
||||
<mxCell id="dEHQTlttWntmzIJzVtkA-10" value="Data" style="whiteSpace=wrap;html=1;" parent="dEHQTlttWntmzIJzVtkA-3" vertex="1">
|
||||
<mxGeometry x="10" y="30" width="180" height="20" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="dEHQTlttWntmzIJzVtkA-5" value="Interface.rs" style="swimlane;whiteSpace=wrap;html=1;" parent="WIyWlLk6GJQsqaUBKTNV-1" vertex="1">
|
||||
<mxGeometry x="40" y="20" width="200" height="710" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="54zimUUJfCheyulekPPo-12" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;exitX=0;exitY=0.5;exitDx=0;exitDy=0;entryX=-0.004;entryY=0.95;entryDx=0;entryDy=0;strokeColor=#FF6666;flowAnimation=1;entryPerimeter=0;" edge="1" parent="dEHQTlttWntmzIJzVtkA-5" source="dEHQTlttWntmzIJzVtkA-6" target="dEHQTlttWntmzIJzVtkA-18">
|
||||
<mxGeometry relative="1" as="geometry">
|
||||
<Array as="points">
|
||||
<mxPoint x="-20" y="80" />
|
||||
<mxPoint x="-20" y="59" />
|
||||
</Array>
|
||||
</mxGeometry>
|
||||
</mxCell>
|
||||
<mxCell id="dEHQTlttWntmzIJzVtkA-6" value="FixedRecipe" style="rounded=0;whiteSpace=wrap;html=1;" parent="dEHQTlttWntmzIJzVtkA-5" vertex="1">
|
||||
<mxGeometry x="10" y="70" width="180" height="20" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="54zimUUJfCheyulekPPo-7" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;exitX=0;exitY=0.5;exitDx=0;exitDy=0;entryX=0;entryY=0.5;entryDx=0;entryDy=0;strokeColor=#3333FF;flowAnimation=1;" edge="1" parent="dEHQTlttWntmzIJzVtkA-5" source="dEHQTlttWntmzIJzVtkA-17" target="dEHQTlttWntmzIJzVtkA-79">
|
||||
<mxGeometry relative="1" as="geometry">
|
||||
<Array as="points">
|
||||
<mxPoint x="-30" y="560" />
|
||||
<mxPoint x="-30" y="490" />
|
||||
</Array>
|
||||
</mxGeometry>
|
||||
</mxCell>
|
||||
<mxCell id="dEHQTlttWntmzIJzVtkA-17" value="Refined List" style="whiteSpace=wrap;html=1;" parent="dEHQTlttWntmzIJzVtkA-5" vertex="1">
|
||||
<mxGeometry x="10" y="550" width="180" height="20" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="dEHQTlttWntmzIJzVtkA-18" value="RecipeElement" style="rounded=0;whiteSpace=wrap;html=1;" parent="dEHQTlttWntmzIJzVtkA-5" vertex="1">
|
||||
<mxGeometry x="10" y="40" width="180" height="20" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="54zimUUJfCheyulekPPo-9" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;exitX=0;exitY=0.5;exitDx=0;exitDy=0;entryX=-0.004;entryY=0.95;entryDx=0;entryDy=0;strokeColor=#FF6666;flowAnimation=1;entryPerimeter=0;" edge="1" parent="dEHQTlttWntmzIJzVtkA-5" source="dEHQTlttWntmzIJzVtkA-31" target="dEHQTlttWntmzIJzVtkA-56">
|
||||
<mxGeometry relative="1" as="geometry">
|
||||
<Array as="points">
|
||||
<mxPoint x="-30" y="270" />
|
||||
<mxPoint x="-30" y="249" />
|
||||
</Array>
|
||||
</mxGeometry>
|
||||
</mxCell>
|
||||
<mxCell id="dEHQTlttWntmzIJzVtkA-31" value="Combinable" style="whiteSpace=wrap;html=1;" parent="dEHQTlttWntmzIJzVtkA-5" vertex="1">
|
||||
<mxGeometry x="10" y="260" width="180" height="20" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="54zimUUJfCheyulekPPo-6" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;exitX=0;exitY=0.5;exitDx=0;exitDy=0;entryX=0;entryY=1;entryDx=0;entryDy=0;strokeColor=#3333FF;flowAnimation=1;" edge="1" parent="dEHQTlttWntmzIJzVtkA-5" source="dEHQTlttWntmzIJzVtkA-41" target="dEHQTlttWntmzIJzVtkA-31">
|
||||
<mxGeometry relative="1" as="geometry">
|
||||
<Array as="points">
|
||||
<mxPoint x="-30" y="340" />
|
||||
<mxPoint x="-30" y="280" />
|
||||
</Array>
|
||||
</mxGeometry>
|
||||
</mxCell>
|
||||
<mxCell id="dEHQTlttWntmzIJzVtkA-41" value="RecipeCollection" style="whiteSpace=wrap;html=1;" parent="dEHQTlttWntmzIJzVtkA-5" vertex="1">
|
||||
<mxGeometry x="10" y="330" width="180" height="20" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="dEHQTlttWntmzIJzVtkA-53" value="ToTex &amp; ToCsv &amp; Reportable" style="whiteSpace=wrap;html=1;" parent="dEHQTlttWntmzIJzVtkA-5" vertex="1">
|
||||
<mxGeometry x="10" y="580" width="180" height="20" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="54zimUUJfCheyulekPPo-14" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;exitX=0;exitY=0;exitDx=0;exitDy=0;entryX=0;entryY=0.5;entryDx=0;entryDy=0;strokeColor=#FF6666;flowAnimation=1;" edge="1" parent="dEHQTlttWntmzIJzVtkA-5" source="dEHQTlttWntmzIJzVtkA-56" target="dEHQTlttWntmzIJzVtkA-18">
|
||||
<mxGeometry relative="1" as="geometry">
|
||||
<Array as="points">
|
||||
<mxPoint x="-30" y="230" />
|
||||
<mxPoint x="-30" y="50" />
|
||||
</Array>
|
||||
</mxGeometry>
|
||||
</mxCell>
|
||||
<mxCell id="dEHQTlttWntmzIJzVtkA-56" value="DbSerialisable" style="whiteSpace=wrap;html=1;" parent="dEHQTlttWntmzIJzVtkA-5" vertex="1">
|
||||
<mxGeometry x="10" y="230" width="180" height="20" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="dEHQTlttWntmzIJzVtkA-79" value="ToTex &amp; ToCsv &amp; Reportable" style="whiteSpace=wrap;html=1;" parent="dEHQTlttWntmzIJzVtkA-5" vertex="1">
|
||||
<mxGeometry x="10" y="480" width="180" height="20" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="54zimUUJfCheyulekPPo-15" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;exitX=0;exitY=0.5;exitDx=0;exitDy=0;strokeColor=#FF6666;flowAnimation=1;" edge="1" parent="dEHQTlttWntmzIJzVtkA-5" source="dEHQTlttWntmzIJzVtkA-83">
|
||||
<mxGeometry relative="1" as="geometry">
|
||||
<mxPoint x="10" y="570" as="targetPoint" />
|
||||
<Array as="points">
|
||||
<mxPoint x="-30" y="650" />
|
||||
<mxPoint x="-30" y="570" />
|
||||
<mxPoint x="9" y="570" />
|
||||
</Array>
|
||||
</mxGeometry>
|
||||
</mxCell>
|
||||
<mxCell id="dEHQTlttWntmzIJzVtkA-83" value="ViewTable" style="whiteSpace=wrap;html=1;" parent="dEHQTlttWntmzIJzVtkA-5" vertex="1">
|
||||
<mxGeometry x="10" y="640" width="180" height="20" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="dEHQTlttWntmzIJzVtkA-7" value="Final Object Representation" style="swimlane;whiteSpace=wrap;html=1;" parent="WIyWlLk6GJQsqaUBKTNV-1" vertex="1">
|
||||
<mxGeometry x="320" y="470" width="200" height="60" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="dEHQTlttWntmzIJzVtkA-69" value="FinalData" style="whiteSpace=wrap;html=1;" parent="dEHQTlttWntmzIJzVtkA-7" vertex="1">
|
||||
<mxGeometry x="10" y="30" width="180" height="20" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="dEHQTlttWntmzIJzVtkA-67" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;exitX=1;exitY=0.5;exitDx=0;exitDy=0;entryX=1;entryY=0;entryDx=0;entryDy=0;jumpStyle=arc;" parent="WIyWlLk6GJQsqaUBKTNV-1" source="dEHQTlttWntmzIJzVtkA-8" target="dEHQTlttWntmzIJzVtkA-29" edge="1">
|
||||
<mxGeometry relative="1" as="geometry">
|
||||
<Array as="points">
|
||||
<mxPoint x="580" y="395" />
|
||||
<mxPoint x="580" y="570" />
|
||||
</Array>
|
||||
</mxGeometry>
|
||||
</mxCell>
|
||||
<mxCell id="dEHQTlttWntmzIJzVtkA-68" value="Into" style="edgeLabel;html=1;align=center;verticalAlign=middle;resizable=0;points=[];fontColor=#FF1616;fontStyle=1;rotation=90;" parent="dEHQTlttWntmzIJzVtkA-67" vertex="1" connectable="0">
|
||||
<mxGeometry x="0.288" relative="1" as="geometry">
|
||||
<mxPoint y="-56" as="offset" />
|
||||
</mxGeometry>
|
||||
</mxCell>
|
||||
<mxCell id="dEHQTlttWntmzIJzVtkA-8" value="List of Recipies" style="swimlane;whiteSpace=wrap;html=1;" parent="WIyWlLk6GJQsqaUBKTNV-1" vertex="1">
|
||||
<mxGeometry x="320" y="350" width="200" height="90" as="geometry">
|
||||
<mxRectangle x="300" y="150" width="120" height="30" as="alternateBounds" />
|
||||
</mxGeometry>
|
||||
</mxCell>
|
||||
<mxCell id="dEHQTlttWntmzIJzVtkA-15" value="Vec&lt;Data&gt;" style="whiteSpace=wrap;html=1;" parent="dEHQTlttWntmzIJzVtkA-8" vertex="1">
|
||||
<mxGeometry x="10" y="30" width="180" height="20" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="dEHQTlttWntmzIJzVtkA-45" value="FilterFunction" style="whiteSpace=wrap;html=1;" parent="dEHQTlttWntmzIJzVtkA-8" vertex="1">
|
||||
<mxGeometry x="10" y="60" width="180" height="20" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="dEHQTlttWntmzIJzVtkA-20" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;exitX=1;exitY=0.5;exitDx=0;exitDy=0;entryX=0;entryY=0.5;entryDx=0;entryDy=0;" parent="WIyWlLk6GJQsqaUBKTNV-1" source="dEHQTlttWntmzIJzVtkA-18" target="dEHQTlttWntmzIJzVtkA-1" edge="1">
|
||||
<mxGeometry relative="1" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="dEHQTlttWntmzIJzVtkA-21" value="Impl" style="edgeLabel;html=1;align=center;verticalAlign=middle;resizable=0;points=[];" parent="dEHQTlttWntmzIJzVtkA-20" vertex="1" connectable="0">
|
||||
<mxGeometry x="-0.2207" y="-1" relative="1" as="geometry">
|
||||
<mxPoint x="5" y="-1" as="offset" />
|
||||
</mxGeometry>
|
||||
</mxCell>
|
||||
<mxCell id="dEHQTlttWntmzIJzVtkA-22" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;exitX=1;exitY=0.5;exitDx=0;exitDy=0;entryX=0;entryY=0.5;entryDx=0;entryDy=0;" parent="WIyWlLk6GJQsqaUBKTNV-1" source="dEHQTlttWntmzIJzVtkA-6" target="dEHQTlttWntmzIJzVtkA-2" edge="1">
|
||||
<mxGeometry relative="1" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="dEHQTlttWntmzIJzVtkA-23" value="Impl" style="edgeLabel;html=1;align=center;verticalAlign=middle;resizable=0;points=[];" parent="dEHQTlttWntmzIJzVtkA-22" vertex="1" connectable="0">
|
||||
<mxGeometry x="-0.0828" y="-2" relative="1" as="geometry">
|
||||
<mxPoint y="-2" as="offset" />
|
||||
</mxGeometry>
|
||||
</mxCell>
|
||||
<mxCell id="dEHQTlttWntmzIJzVtkA-27" value="ViewTable" style="swimlane;whiteSpace=wrap;html=1;" parent="WIyWlLk6GJQsqaUBKTNV-1" vertex="1">
|
||||
<mxGeometry x="320" y="660" width="200" height="60" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="dEHQTlttWntmzIJzVtkA-28" value="Points of interest" style="whiteSpace=wrap;html=1;" parent="dEHQTlttWntmzIJzVtkA-27" vertex="1">
|
||||
<mxGeometry x="10" y="30" width="180" height="20" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="dEHQTlttWntmzIJzVtkA-29" value="List of FinalRecipies" style="swimlane;whiteSpace=wrap;html=1;" parent="WIyWlLk6GJQsqaUBKTNV-1" vertex="1">
|
||||
<mxGeometry x="320" y="570" width="200" height="60" as="geometry">
|
||||
<mxRectangle x="300" y="150" width="120" height="30" as="alternateBounds" />
|
||||
</mxGeometry>
|
||||
</mxCell>
|
||||
<mxCell id="dEHQTlttWntmzIJzVtkA-30" value="Vec&lt;FinalData&gt;" style="whiteSpace=wrap;html=1;" parent="dEHQTlttWntmzIJzVtkA-29" vertex="1">
|
||||
<mxGeometry x="10" y="30" width="180" height="20" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="dEHQTlttWntmzIJzVtkA-43" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;exitX=1;exitY=0.5;exitDx=0;exitDy=0;entryX=-0.014;entryY=0.167;entryDx=0;entryDy=0;entryPerimeter=0;" parent="WIyWlLk6GJQsqaUBKTNV-1" source="dEHQTlttWntmzIJzVtkA-17" target="dEHQTlttWntmzIJzVtkA-29" edge="1">
|
||||
<mxGeometry relative="1" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="dEHQTlttWntmzIJzVtkA-49" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;exitX=1;exitY=0.5;exitDx=0;exitDy=0;entryX=-0.014;entryY=0.102;entryDx=0;entryDy=0;entryPerimeter=0;jumpStyle=arc;" parent="WIyWlLk6GJQsqaUBKTNV-1" source="dEHQTlttWntmzIJzVtkA-41" target="dEHQTlttWntmzIJzVtkA-8" edge="1">
|
||||
<mxGeometry relative="1" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="dEHQTlttWntmzIJzVtkA-51" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;exitX=1;exitY=0.5;exitDx=0;exitDy=0;" parent="WIyWlLk6GJQsqaUBKTNV-1" source="dEHQTlttWntmzIJzVtkA-41" target="dEHQTlttWntmzIJzVtkA-45" edge="1">
|
||||
<mxGeometry relative="1" as="geometry">
|
||||
<Array as="points">
|
||||
<mxPoint x="260" y="360" />
|
||||
<mxPoint x="260" y="420" />
|
||||
</Array>
|
||||
</mxGeometry>
|
||||
</mxCell>
|
||||
<mxCell id="dEHQTlttWntmzIJzVtkA-52" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;exitX=1;exitY=0.5;exitDx=0;exitDy=0;entryX=0;entryY=0.5;entryDx=0;entryDy=0;jumpStyle=arc;" parent="WIyWlLk6GJQsqaUBKTNV-1" source="dEHQTlttWntmzIJzVtkA-31" target="dEHQTlttWntmzIJzVtkA-15" edge="1">
|
||||
<mxGeometry relative="1" as="geometry">
|
||||
<Array as="points">
|
||||
<mxPoint x="270" y="290" />
|
||||
<mxPoint x="270" y="390" />
|
||||
</Array>
|
||||
</mxGeometry>
|
||||
</mxCell>
|
||||
<mxCell id="dEHQTlttWntmzIJzVtkA-54" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;exitX=1;exitY=0.5;exitDx=0;exitDy=0;flowAnimation=0;entryX=-0.015;entryY=0.26;entryDx=0;entryDy=0;entryPerimeter=0;" parent="WIyWlLk6GJQsqaUBKTNV-1" source="dEHQTlttWntmzIJzVtkA-53" target="dEHQTlttWntmzIJzVtkA-29" edge="1">
|
||||
<mxGeometry relative="1" as="geometry">
|
||||
<mxPoint x="280" y="520" as="targetPoint" />
|
||||
</mxGeometry>
|
||||
</mxCell>
|
||||
<mxCell id="dEHQTlttWntmzIJzVtkA-57" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;exitX=1;exitY=0.5;exitDx=0;exitDy=0;entryX=0;entryY=0.25;entryDx=0;entryDy=0;" parent="WIyWlLk6GJQsqaUBKTNV-1" source="dEHQTlttWntmzIJzVtkA-31" target="dEHQTlttWntmzIJzVtkA-3" edge="1">
|
||||
<mxGeometry relative="1" as="geometry">
|
||||
<Array as="points">
|
||||
<mxPoint x="270" y="290" />
|
||||
<mxPoint x="270" y="265" />
|
||||
</Array>
|
||||
</mxGeometry>
|
||||
</mxCell>
|
||||
<mxCell id="dEHQTlttWntmzIJzVtkA-58" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;exitX=1;exitY=0.5;exitDx=0;exitDy=0;entryX=0.009;entryY=0.164;entryDx=0;entryDy=0;entryPerimeter=0;" parent="WIyWlLk6GJQsqaUBKTNV-1" source="dEHQTlttWntmzIJzVtkA-56" target="dEHQTlttWntmzIJzVtkA-3" edge="1">
|
||||
<mxGeometry relative="1" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="dEHQTlttWntmzIJzVtkA-65" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;exitX=1;exitY=0.5;exitDx=0;exitDy=0;" parent="WIyWlLk6GJQsqaUBKTNV-1" source="dEHQTlttWntmzIJzVtkA-61" target="dEHQTlttWntmzIJzVtkA-3" edge="1">
|
||||
<mxGeometry relative="1" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="dEHQTlttWntmzIJzVtkA-66" value="Into" style="edgeLabel;html=1;align=center;verticalAlign=middle;resizable=0;points=[];fontColor=#FF1616;fontStyle=1" parent="dEHQTlttWntmzIJzVtkA-65" vertex="1" connectable="0">
|
||||
<mxGeometry x="0.3009" relative="1" as="geometry">
|
||||
<mxPoint as="offset" />
|
||||
</mxGeometry>
|
||||
</mxCell>
|
||||
<mxCell id="dEHQTlttWntmzIJzVtkA-61" value="Intermediate Object Representation" style="swimlane;whiteSpace=wrap;html=1;" parent="WIyWlLk6GJQsqaUBKTNV-1" vertex="1">
|
||||
<mxGeometry x="300" y="150" width="230" height="60" as="geometry">
|
||||
<mxRectangle x="10" y="160" width="190" height="30" as="alternateBounds" />
|
||||
</mxGeometry>
|
||||
</mxCell>
|
||||
<mxCell id="dEHQTlttWntmzIJzVtkA-62" value="Data" style="whiteSpace=wrap;html=1;" parent="dEHQTlttWntmzIJzVtkA-61" vertex="1">
|
||||
<mxGeometry x="10" y="30" width="210" height="20" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="dEHQTlttWntmzIJzVtkA-63" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;exitX=1;exitY=0.5;exitDx=0;exitDy=0;" parent="WIyWlLk6GJQsqaUBKTNV-1" source="dEHQTlttWntmzIJzVtkA-1" target="dEHQTlttWntmzIJzVtkA-61" edge="1">
|
||||
<mxGeometry relative="1" as="geometry">
|
||||
<Array as="points">
|
||||
<mxPoint x="520" y="70" />
|
||||
<mxPoint x="520" y="130" />
|
||||
<mxPoint x="410" y="130" />
|
||||
</Array>
|
||||
</mxGeometry>
|
||||
</mxCell>
|
||||
<mxCell id="dEHQTlttWntmzIJzVtkA-80" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;exitX=1;exitY=0.5;exitDx=0;exitDy=0;entryX=0;entryY=0.5;entryDx=0;entryDy=0;" parent="WIyWlLk6GJQsqaUBKTNV-1" source="dEHQTlttWntmzIJzVtkA-79" target="dEHQTlttWntmzIJzVtkA-69" edge="1">
|
||||
<mxGeometry relative="1" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="dEHQTlttWntmzIJzVtkA-81" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;exitX=1;exitY=0.5;exitDx=0;exitDy=0;entryX=1;entryY=0.5;entryDx=0;entryDy=0;jumpStyle=arc;" parent="WIyWlLk6GJQsqaUBKTNV-1" source="dEHQTlttWntmzIJzVtkA-30" target="dEHQTlttWntmzIJzVtkA-69" edge="1">
|
||||
<mxGeometry relative="1" as="geometry">
|
||||
<Array as="points">
|
||||
<mxPoint x="560" y="610" />
|
||||
<mxPoint x="560" y="510" />
|
||||
</Array>
|
||||
</mxGeometry>
|
||||
</mxCell>
|
||||
<mxCell id="dEHQTlttWntmzIJzVtkA-82" value="Converted" style="edgeLabel;html=1;align=center;verticalAlign=middle;resizable=0;points=[];fontColor=#FF1616;fontStyle=1;rotation=90;" parent="dEHQTlttWntmzIJzVtkA-81" vertex="1" connectable="0">
|
||||
<mxGeometry x="-0.0474" y="3" relative="1" as="geometry">
|
||||
<mxPoint x="3" y="-25" as="offset" />
|
||||
</mxGeometry>
|
||||
</mxCell>
|
||||
<mxCell id="dEHQTlttWntmzIJzVtkA-84" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;exitX=1;exitY=0.5;exitDx=0;exitDy=0;entryX=0.007;entryY=0.164;entryDx=0;entryDy=0;entryPerimeter=0;" parent="WIyWlLk6GJQsqaUBKTNV-1" source="dEHQTlttWntmzIJzVtkA-83" target="dEHQTlttWntmzIJzVtkA-27" edge="1">
|
||||
<mxGeometry relative="1" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="dEHQTlttWntmzIJzVtkA-85" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;entryX=1;entryY=0.333;entryDx=0;entryDy=0;entryPerimeter=0;exitX=1;exitY=0.094;exitDx=0;exitDy=0;jumpStyle=arc;exitPerimeter=0;" parent="WIyWlLk6GJQsqaUBKTNV-1" source="dEHQTlttWntmzIJzVtkA-27" target="dEHQTlttWntmzIJzVtkA-29" edge="1">
|
||||
<mxGeometry relative="1" as="geometry">
|
||||
<Array as="points">
|
||||
<mxPoint x="580" y="666" />
|
||||
<mxPoint x="580" y="590" />
|
||||
</Array>
|
||||
<mxPoint x="540" y="660" as="sourcePoint" />
|
||||
</mxGeometry>
|
||||
</mxCell>
|
||||
<mxCell id="dEHQTlttWntmzIJzVtkA-86" value="Collect" style="edgeLabel;html=1;align=center;verticalAlign=middle;resizable=0;points=[];fontColor=#FF1616;fontStyle=1;rotation=90;" parent="dEHQTlttWntmzIJzVtkA-85" vertex="1" connectable="0">
|
||||
<mxGeometry x="0.0342" y="-1" relative="1" as="geometry">
|
||||
<mxPoint as="offset" />
|
||||
</mxGeometry>
|
||||
</mxCell>
|
||||
<mxCell id="54zimUUJfCheyulekPPo-16" value="Scenario" style="swimlane;whiteSpace=wrap;html=1;" vertex="1" parent="WIyWlLk6GJQsqaUBKTNV-1">
|
||||
<mxGeometry x="630" y="20" width="190" height="710" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="54zimUUJfCheyulekPPo-27" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;exitX=0.5;exitY=1;exitDx=0;exitDy=0;" edge="1" parent="54zimUUJfCheyulekPPo-16" source="54zimUUJfCheyulekPPo-17" target="54zimUUJfCheyulekPPo-23">
|
||||
<mxGeometry relative="1" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="54zimUUJfCheyulekPPo-17" value="Database" style="whiteSpace=wrap;html=1;" vertex="1" parent="54zimUUJfCheyulekPPo-16">
|
||||
<mxGeometry x="5" y="30" width="180" height="20" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="54zimUUJfCheyulekPPo-19" value="Final List" style="whiteSpace=wrap;html=1;" vertex="1" parent="54zimUUJfCheyulekPPo-16">
|
||||
<mxGeometry x="5" y="550" width="180" height="20" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="54zimUUJfCheyulekPPo-28" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;exitX=0.5;exitY=1;exitDx=0;exitDy=0;" edge="1" parent="54zimUUJfCheyulekPPo-16" source="54zimUUJfCheyulekPPo-23" target="54zimUUJfCheyulekPPo-25">
|
||||
<mxGeometry relative="1" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="54zimUUJfCheyulekPPo-23" value="Inner Intermediate Repr" style="whiteSpace=wrap;html=1;dashed=1;dashPattern=8 8;" vertex="1" parent="54zimUUJfCheyulekPPo-16">
|
||||
<mxGeometry x="5" y="130" width="180" height="20" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="54zimUUJfCheyulekPPo-29" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;exitX=0.5;exitY=1;exitDx=0;exitDy=0;" edge="1" parent="54zimUUJfCheyulekPPo-16" source="54zimUUJfCheyulekPPo-25" target="54zimUUJfCheyulekPPo-19">
|
||||
<mxGeometry relative="1" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="54zimUUJfCheyulekPPo-25" value="List of Recipies" style="whiteSpace=wrap;html=1;" vertex="1" parent="54zimUUJfCheyulekPPo-16">
|
||||
<mxGeometry x="5" y="330" width="180" height="20" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="54zimUUJfCheyulekPPo-33" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;exitX=0.5;exitY=0;exitDx=0;exitDy=0;entryX=0.5;entryY=1;entryDx=0;entryDy=0;startArrow=classic;startFill=1;" edge="1" parent="54zimUUJfCheyulekPPo-16" source="54zimUUJfCheyulekPPo-31" target="54zimUUJfCheyulekPPo-19">
|
||||
<mxGeometry relative="1" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="54zimUUJfCheyulekPPo-31" value="Loaded View Tables" style="whiteSpace=wrap;html=1;" vertex="1" parent="54zimUUJfCheyulekPPo-16">
|
||||
<mxGeometry x="5" y="640" width="180" height="20" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="54zimUUJfCheyulekPPo-18" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;exitX=0;exitY=0.5;exitDx=0;exitDy=0;entryX=1.003;entryY=0.153;entryDx=0;entryDy=0;entryPerimeter=0;" edge="1" parent="WIyWlLk6GJQsqaUBKTNV-1" source="54zimUUJfCheyulekPPo-17" target="dEHQTlttWntmzIJzVtkA-0">
|
||||
<mxGeometry relative="1" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="54zimUUJfCheyulekPPo-24" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;exitX=0;exitY=0.5;exitDx=0;exitDy=0;entryX=1.007;entryY=0.156;entryDx=0;entryDy=0;entryPerimeter=0;dashed=1;endArrow=none;startFill=1;startArrow=classic;" edge="1" parent="WIyWlLk6GJQsqaUBKTNV-1" source="54zimUUJfCheyulekPPo-23" target="dEHQTlttWntmzIJzVtkA-61">
|
||||
<mxGeometry relative="1" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="54zimUUJfCheyulekPPo-26" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;exitX=0;exitY=0.5;exitDx=0;exitDy=0;entryX=1.003;entryY=0.104;entryDx=0;entryDy=0;entryPerimeter=0;endArrow=none;startFill=1;startArrow=classic;" edge="1" parent="WIyWlLk6GJQsqaUBKTNV-1" source="54zimUUJfCheyulekPPo-25" target="dEHQTlttWntmzIJzVtkA-8">
|
||||
<mxGeometry relative="1" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="54zimUUJfCheyulekPPo-30" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;exitX=0;exitY=0.5;exitDx=0;exitDy=0;entryX=1.008;entryY=0.183;entryDx=0;entryDy=0;entryPerimeter=0;startArrow=classic;startFill=0;endArrow=none;jumpStyle=arc;" edge="1" parent="WIyWlLk6GJQsqaUBKTNV-1" source="54zimUUJfCheyulekPPo-19" target="dEHQTlttWntmzIJzVtkA-29">
|
||||
<mxGeometry relative="1" as="geometry">
|
||||
<Array as="points">
|
||||
<mxPoint x="522" y="580" />
|
||||
</Array>
|
||||
</mxGeometry>
|
||||
</mxCell>
|
||||
<mxCell id="54zimUUJfCheyulekPPo-32" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;exitX=0;exitY=0.5;exitDx=0;exitDy=0;entryX=0.998;entryY=0.167;entryDx=0;entryDy=0;entryPerimeter=0;" edge="1" parent="WIyWlLk6GJQsqaUBKTNV-1" source="54zimUUJfCheyulekPPo-31" target="dEHQTlttWntmzIJzVtkA-27">
|
||||
<mxGeometry relative="1" as="geometry" />
|
||||
</mxCell>
|
||||
</root>
|
||||
</mxGraphModel>
|
||||
</diagram>
|
||||
</mxfile>
|
||||
|
|
@ -0,0 +1,156 @@
|
|||
// 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()))
|
||||
}
|
||||
|
|
@ -0,0 +1,143 @@
|
|||
// Workspace: weaponry
|
||||
// File: weaponry/src/database.rs
|
||||
//! Database handiling module
|
||||
//! Implements the basics deserialisation from a database to the weaponry components
|
||||
//! Should dump whole database in a vec of structs from weaponry_structs
|
||||
#![allow(dead_code)]
|
||||
use rusqlite::{self};
|
||||
use serde::de::DeserializeOwned;
|
||||
|
||||
use crate::error::FatalEquipementError;
|
||||
|
||||
/// Public function to get data from db. Returns the result as a vec with structs
|
||||
pub fn get_data<T>(
|
||||
conn: &rusqlite::Connection,
|
||||
table_name: &str,
|
||||
filter: Option<&str>,
|
||||
) -> Result<Vec<T>, FatalEquipementError>
|
||||
where
|
||||
T: DeserializeOwned + more_fields::FieldsAsSlice,
|
||||
{
|
||||
let mut connection = conn.prepare(&generate_select_query::<T>(table_name, filter))?;
|
||||
let rows = connection.query([])?;
|
||||
serde_rusqlite::from_rows::<T>(rows)
|
||||
.enumerate()
|
||||
.map(|(row_id, result)| {
|
||||
result.map_err(|error| FatalEquipementError::SerdeRusqlite { error, row_id })
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Generate a SELECT query with fields generated from a struct. Returns a SQL request as a String
|
||||
#[inline]
|
||||
#[cfg_attr(feature = "dev-analysis", coverage(off))] // INCORRECT: Error with line report
|
||||
fn generate_select_query<T: more_fields::FieldsAsSlice>(
|
||||
table_name: &str,
|
||||
filter: 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)
|
||||
)
|
||||
}
|
||||
|
||||
/// Generate create table_name with fields as columns
|
||||
/// This function expects a hash map containing (column name, sqlite type)
|
||||
pub fn generate_create_table_query(table_name: &str, fields: &[(&str, &str)]) -> String {
|
||||
format!(
|
||||
"CREATE TABLE IF NOT EXISTS {} ({}, PRIMARY KEY('id' AUTOINCREMENT));",
|
||||
table_name,
|
||||
fields
|
||||
.iter()
|
||||
.map(|(k, v)| format!("{} {}", k, v))
|
||||
.collect::<Vec<_>>()
|
||||
.join(",")
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::*;
|
||||
use crate::{
|
||||
interfaces::RecipeDatabase, weaponry_structs::equipement_impl_database::EquipementDatabase,
|
||||
};
|
||||
use more_fields::FieldsAsSlice;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde::Deserialize;
|
||||
|
||||
#[derive(FieldsAsSlice, Deserialize, Debug, PartialEq)]
|
||||
struct TestStruct {
|
||||
#[INTEGER]
|
||||
id: usize,
|
||||
#[TEXT]
|
||||
name: String,
|
||||
}
|
||||
/// setting up test db and table, also adding arbitrary data inside
|
||||
fn mock_set_up(db_filename: &str) -> EquipementDatabase {
|
||||
let _ = std::fs::remove_file(db_filename);
|
||||
let equip_db = EquipementDatabase::new(db_filename).unwrap();
|
||||
equip_db.conn.execute("CREATE TABLE IF NOT EXISTS TestStruct (id INTEGER UNIQUE, name TEXT, PRIMARY KEY('id' AUTOINCREMENT));",()).unwrap();
|
||||
equip_db
|
||||
.conn
|
||||
.execute(
|
||||
"INSERT INTO TestStruct (id, name) VALUES (1, 'dupont'), (2, 'durand');",
|
||||
(),
|
||||
)
|
||||
.unwrap();
|
||||
equip_db
|
||||
}
|
||||
/// tearing down all test setup
|
||||
fn tear_down(filename: &str, db_conn: rusqlite::Connection) {
|
||||
db_conn.close().unwrap();
|
||||
std::fs::remove_file(filename).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_generate_query() {
|
||||
assert_eq!(
|
||||
generate_select_query::<TestStruct>("TestStruct", None),
|
||||
"SELECT id,name FROM TestStruct;"
|
||||
);
|
||||
assert_eq!(
|
||||
generate_select_query::<TestStruct>("TestStruct", Some("id=id")),
|
||||
"SELECT id,name FROM TestStruct WHERE id=id;"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn get_data_from_fields() {
|
||||
let filename = "test.db";
|
||||
let conn = mock_set_up(filename);
|
||||
let result = conn
|
||||
.serialize_vec_from_table::<TestStruct>("TestStruct", None)
|
||||
.unwrap();
|
||||
tear_down(filename, conn.conn);
|
||||
assert_eq!(
|
||||
result,
|
||||
vec![
|
||||
TestStruct {
|
||||
id: 1,
|
||||
name: "dupont".to_string()
|
||||
},
|
||||
TestStruct {
|
||||
id: 2,
|
||||
name: "durand".to_string()
|
||||
}
|
||||
]
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_generate_create_table_query() {
|
||||
let query = generate_create_table_query("TestStruct", TestStruct::attributes_slice());
|
||||
assert_eq!(
|
||||
query, "CREATE TABLE IF NOT EXISTS TestStruct (id INTEGER,name TEXT, PRIMARY KEY('id' AUTOINCREMENT));".to_string()
|
||||
)
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,85 @@
|
|||
// Workspace: weaponry
|
||||
// File: weaponry/src/error.rs
|
||||
//! Inner weaponry error definition
|
||||
#![allow(missing_docs, clippy::missing_docs_in_private_items)]
|
||||
|
||||
use charming::EchartsError;
|
||||
use thiserror::Error;
|
||||
|
||||
#[derive(Error, Debug)]
|
||||
/// Unrecoverable Error, all these error cannot gracefully fail and must return to the User for further handling
|
||||
pub enum FatalEquipementError {
|
||||
#[error("Rusqlite failed to connect to the given path {0}")]
|
||||
RusqliteConnection(#[from] rusqlite::Error),
|
||||
|
||||
#[error("Deserialization from object failed : rowid {row_id} \n{error}")]
|
||||
SerdeRusqlite {
|
||||
error: serde_rusqlite::Error,
|
||||
row_id: usize,
|
||||
},
|
||||
|
||||
#[error("Deserialisation from json failed : {0}")]
|
||||
SerdeJSON(#[from] serde_json::Error),
|
||||
|
||||
#[error("Error making the template: {0}")]
|
||||
TemplatingError(#[from] handlebars::TemplateError),
|
||||
|
||||
#[error("Error rendering the template: {0}")]
|
||||
RenderError(#[from] handlebars::RenderError),
|
||||
|
||||
#[error(
|
||||
"Deserialisation from json failed at line {line} on file {file} while trying to parse the value: {parsed_value}: {error}]"
|
||||
)]
|
||||
SerdeJSONAt {
|
||||
line: String,
|
||||
file: String,
|
||||
error: serde_json::Error,
|
||||
parsed_value: String,
|
||||
},
|
||||
|
||||
#[error("Couldn't convert into type {origin_type} with data {data}")]
|
||||
Conversion { origin_type: String, data: String },
|
||||
|
||||
#[error("An error occured with your current CLI configuration: {0}")]
|
||||
CLISelection(String),
|
||||
|
||||
#[error("Couldn't save the chart as an error occured during the process : {0}")]
|
||||
SaveCharmingChart(#[from] EchartsError),
|
||||
|
||||
#[error("Couldn't parse the CLI argument given \"{0}\"")]
|
||||
CLIParseError(String),
|
||||
|
||||
#[error("Couldn't serialize the object to make a query: \n{0}")]
|
||||
SerdeRSQLite(#[from] serde_rusqlite::Error),
|
||||
}
|
||||
|
||||
#[derive(Error, Debug)]
|
||||
/// Generic error handling
|
||||
pub enum WeaponGenerationError {
|
||||
#[error("An unexpected error occured")]
|
||||
Unexpected,
|
||||
|
||||
#[error("An error was encountered while generating equipement")]
|
||||
FatalEquipementError(#[from] FatalEquipementError),
|
||||
|
||||
#[error("An error occured while writing the file")]
|
||||
IOError(#[from] std::io::Error),
|
||||
}
|
||||
|
||||
// #[derive(Error, Debug)]
|
||||
// /// Recoverable error, all these error exist to signal a retry or another path that should be taken by the program
|
||||
// pub enum LocalEquipementError {
|
||||
// #[error("Very simple error")]
|
||||
// Oops,
|
||||
// }
|
||||
|
||||
// #[derive(Error, Debug)]
|
||||
// /// An equipement error, either unrecoverable, indicating a that the execution
|
||||
// /// flow must be stopped and only an user input can solve the issue
|
||||
// pub enum EquipementError {
|
||||
// #[error("An unrecoverable error occured: {0}")]
|
||||
// Fatal(#[from] FatalEquipementError),
|
||||
|
||||
// #[error("A local error occured an wasn't recovered from: {0}")]
|
||||
// Local(#[from] LocalEquipementError),
|
||||
// }
|
||||
|
|
@ -0,0 +1,183 @@
|
|||
// Workspace: weaponry
|
||||
// File: weaponry/src/export.rs
|
||||
//! Module regrouping all generic function related to the exporting
|
||||
//!
|
||||
//! Mostly graphs and csv auto conversion
|
||||
|
||||
use charming::{
|
||||
Chart,
|
||||
component::{self, Axis, Grid, Title},
|
||||
element::{Tooltip, Trigger},
|
||||
};
|
||||
|
||||
/// A very complex macro created to add criterias to the graph
|
||||
/// without repeating self explanatory parameter names in strings
|
||||
///
|
||||
/// The syntax involved in the usage of this macro hence become esoteric
|
||||
///
|
||||
/// # Example
|
||||
/// ```
|
||||
/// # use weaponry::interfaces::RecipeCollection;
|
||||
/// # use weaponry::add_field_to_chart;
|
||||
/// # use weaponry::weaponry_structs::RefinedEquipementList;
|
||||
/// # use weaponry::export::initial_chart;
|
||||
/// # let self_ = RefinedEquipementList::default();
|
||||
/// # let initial_chart: charming::Chart = initial_chart("Damage for all cross-gen products");
|
||||
/// add_field_to_chart!(
|
||||
/// self_, // Usually used inside the implementation and therefore self there
|
||||
/// initial_chart,
|
||||
/// (
|
||||
/// index # &String,
|
||||
/// dps_safe # f64,
|
||||
/// ),
|
||||
/// |ref_equipement| {
|
||||
/// (
|
||||
/// &ref_equipement.advanced.display_name,
|
||||
/// ref_equipement.advanced.max_damage_per_attack,
|
||||
/// )
|
||||
/// }
|
||||
/// );
|
||||
/// ```
|
||||
///
|
||||
/// # Complexity and maintanability
|
||||
///
|
||||
/// While the added complexity cannot be understated, the whole existence of this macro is
|
||||
/// first and foremost based on the desire NOT to iterate multiple times on a dataset
|
||||
/// which could easily reach 600k elements
|
||||
///
|
||||
/// Knowing this tradeoff, the difficulty to maintain is considered an acceptable tradeoff
|
||||
// TODO[4]: If the field accessed are only in advanced, remove the closure entirely and auto_generate it
|
||||
// TODO[4]: A good part of this code shouldn't be generic and instead in weaponry
|
||||
#[macro_export]
|
||||
macro_rules! add_field_to_chart {
|
||||
($base_struct:expr, $chart:ident, ($names:ident # $name_type:ty, $($table_names:ident # $table_type:ty),* $(,)*), | $closure_name:ident | {($($fields:expr,)*)}
|
||||
) => {
|
||||
let $chart = {
|
||||
let data_collection = $base_struct.inner.iter().map(|$closure_name| ( $($fields,)*) );
|
||||
let ($names, $($table_names),*) = data_collection.collect::<(Vec<$name_type>, $(Vec<$table_type>,)*)>();
|
||||
let $chart = $chart
|
||||
.x_axis(
|
||||
charming::component::Axis::new()
|
||||
.data($names.to_vec())
|
||||
.type_(charming::element::AxisType::Category),
|
||||
);
|
||||
$(
|
||||
let $chart = $chart
|
||||
.series(
|
||||
charming::series::Line::new()
|
||||
// .stack("Total")
|
||||
.data($table_names)
|
||||
.name(stringify!($table_names))
|
||||
.mark_point(charming::element::MarkPoint::new().data(vec![("max", "Max"), ("min", "Min")]))
|
||||
.mark_line(charming::element::MarkLine::new().data(vec![charming::element::MarkLineVariant::Simple(
|
||||
charming::element::MarkLineData::new()
|
||||
.type_(charming::element::MarkLineDataType::Average)
|
||||
.name("Avg"),
|
||||
)])),
|
||||
);
|
||||
)*
|
||||
|
||||
$chart.legend(
|
||||
charming::component::Legend::new()
|
||||
.left(10)
|
||||
.top("middle")
|
||||
.orient(charming::element::Orient::Vertical)
|
||||
.data(vec![
|
||||
$(stringify!($table_names),)*
|
||||
]),
|
||||
)
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/// Generate a generic graph, ready to be filled with data
|
||||
pub fn initial_chart(chart_name: &str) -> Chart {
|
||||
Chart::new()
|
||||
.title(component::Title::new().text(chart_name).left("center"))
|
||||
.tooltip(charming::element::Tooltip::new().trigger(charming::element::Trigger::Axis))
|
||||
.data_zoom(
|
||||
component::DataZoom::new()
|
||||
.type_(component::DataZoomType::Inside)
|
||||
.start(0)
|
||||
.end(100),
|
||||
)
|
||||
.data_zoom(component::DataZoom::new().start(0).end(100))
|
||||
.toolbox(
|
||||
component::Toolbox::new().feature(
|
||||
component::Feature::new()
|
||||
.data_zoom(component::ToolboxDataZoom::new().y_axis_index("none"))
|
||||
.restore(component::Restore::new())
|
||||
.save_as_image(component::SaveAsImage::new()), // .brush(Brush::new().type_(vec![BrushType::LineX, BrushType::Clear])),
|
||||
),
|
||||
)
|
||||
.tooltip(charming::element::Tooltip::new().trigger(charming::element::Trigger::Axis))
|
||||
.y_axis(component::Axis::new())
|
||||
.grid(component::Grid::new().contain_label(true))
|
||||
}
|
||||
|
||||
/// Generate a new plot chart
|
||||
pub fn initial_plot_chart(chart_name: &str, sub_charts: &[&str]) -> Chart {
|
||||
// charming::Chart::new()
|
||||
Chart::new()
|
||||
.title(Title::new().text(chart_name).left("center"))
|
||||
.title(Title::new().text(sub_charts[0]).left("17%").top("5%"))
|
||||
.title(Title::new().text(sub_charts[1]).left("17%").top("52%"))
|
||||
.title(Title::new().text(sub_charts[2]).right("12%").top("5%"))
|
||||
.title(Title::new().text(sub_charts[3]).right("12%").top("52%"))
|
||||
.tooltip(Tooltip::new().trigger(Trigger::Axis))
|
||||
.data_zoom(
|
||||
component::DataZoom::new()
|
||||
.type_(component::DataZoomType::Inside)
|
||||
.start(0)
|
||||
.end(100),
|
||||
)
|
||||
.tooltip(charming::element::Tooltip::new().trigger(charming::element::Trigger::Axis))
|
||||
.toolbox(
|
||||
component::Toolbox::new().feature(
|
||||
component::Feature::new()
|
||||
.data_zoom(component::ToolboxDataZoom::new().y_axis_index("none"))
|
||||
.restore(component::Restore::new())
|
||||
.save_as_image(component::SaveAsImage::new()), // .brush(Brush::new().type_(vec![BrushType::LineX, BrushType::Clear])),
|
||||
),
|
||||
)
|
||||
.grid(
|
||||
Grid::new()
|
||||
.left("7%")
|
||||
.top("7%")
|
||||
.width("38%")
|
||||
.height("38%")
|
||||
.contain_label(true),
|
||||
)
|
||||
.grid(
|
||||
Grid::new()
|
||||
.right("7%")
|
||||
.top("7%")
|
||||
.width("38%")
|
||||
.height("38%")
|
||||
.contain_label(true),
|
||||
)
|
||||
.grid(
|
||||
Grid::new()
|
||||
.left("7%")
|
||||
.bottom("7%")
|
||||
.width("38%")
|
||||
.height("38%")
|
||||
.contain_label(true),
|
||||
)
|
||||
.grid(
|
||||
Grid::new()
|
||||
.right("7%")
|
||||
.bottom("7%")
|
||||
.width("38%")
|
||||
.height("38%")
|
||||
.contain_label(true),
|
||||
)
|
||||
.x_axis(Axis::new().grid_index(0).min(1))
|
||||
.x_axis(Axis::new().grid_index(1).min(1))
|
||||
.x_axis(Axis::new().grid_index(2).min(1))
|
||||
.x_axis(Axis::new().grid_index(3).min(1))
|
||||
.y_axis(Axis::new().grid_index(0).min(0))
|
||||
.y_axis(Axis::new().grid_index(1).min(0))
|
||||
.y_axis(Axis::new().grid_index(2).min(0))
|
||||
.y_axis(Axis::new().grid_index(3).min(0))
|
||||
}
|
||||
|
|
@ -0,0 +1,53 @@
|
|||
// 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(())
|
||||
}
|
||||
|
|
@ -0,0 +1,364 @@
|
|||
// Workspace: weaponry
|
||||
// File: weaponry/src/interfaces.rs
|
||||
//! Interface module holding all necesary traits
|
||||
//! A good amount of effort is made to keep the code polymorphic enough to allow
|
||||
//! handling of the whole crafting process when the times comes
|
||||
#![allow(dead_code)]
|
||||
|
||||
use std::{path::Path, rc::Rc};
|
||||
|
||||
use cli_parser::Config;
|
||||
use more_fields::FieldsAsSlice;
|
||||
use rusqlite::Connection;
|
||||
use serde::{Serialize, de::DeserializeOwned};
|
||||
|
||||
use crate::error::FatalEquipementError;
|
||||
|
||||
/// Trait representing a view table
|
||||
///
|
||||
/// These table exist to allow to link several point of interest to a RecipeCollection
|
||||
/// Please note that while FinalRepresentations and ViewTable are two separate traits,
|
||||
/// they are always tied together as a view table will alway take specific assumptions
|
||||
/// on the data present inside therefore not allowing many variations on the underlying
|
||||
/// implementation of the representation
|
||||
pub trait ViewTable {
|
||||
/// The inner type of element that one would be peeking into
|
||||
///
|
||||
/// Usually the final representation of an Item
|
||||
type InterestElementList: RefinedList;
|
||||
|
||||
/// Give a list of interesting element indicises to further analyse
|
||||
fn index_of_interest_points(&self) -> Vec<usize>;
|
||||
|
||||
/// Interrogate the FinalRepresentation to find interesting elements
|
||||
fn find_points_of_interest(representation: &Self::InterestElementList) -> Self;
|
||||
// An alternative, non Self::Typed way of doing since there is only one usage for now
|
||||
// fn find_points_of_interest(&self, representation: &impl FinalRepresentation);
|
||||
}
|
||||
|
||||
/// Trait implemented by any struct holding the final representation of a RecipeCollection
|
||||
///
|
||||
/// This trait is rather placeholder, reminding the user to give only objects that are indeed
|
||||
/// final representations and contains all important fields calculated
|
||||
///
|
||||
/// While it is possible to enforce from_recipe_collection, doing so would require the viewtable
|
||||
/// lock itseld to a particular recipe.
|
||||
/// While it is the case as of now, matters are not yet set in stone
|
||||
pub trait RefinedList: ToTex + ToCSV + ToAnalysis {
|
||||
// Must implement From<RecipeCollection>, is it worth adding as a prerequite type ?
|
||||
// type OriginCollection: Into<Self>;
|
||||
}
|
||||
|
||||
/// Trait implemented for the final collection of a recipe, allowing it to be combined with parts
|
||||
///
|
||||
/// A recipe list will be combined with a part list to be updated and generate all combinaisons, so on and so forth
|
||||
pub trait RecipeCollection
|
||||
where
|
||||
for<'a> &'a <<Self as RecipeCollection>::Recipes as Combinable>::Inner: std::ops::Add,
|
||||
{
|
||||
/// The type of the inner recipes, this type must be combinable
|
||||
type Recipes: Combinable;
|
||||
|
||||
/// A blanket implementation giving all combinaisons of recipes with another RecipeCollection
|
||||
///
|
||||
/// This method doesn't make use of parallel iterators as the workload is way faster than would be the memory dispatch
|
||||
#[cfg_attr(feature = "dev-analysis", coverage(off))] // Tarpaulin cannot deal with iter and long lines
|
||||
fn combine_all<G>(&mut self, other: &G)
|
||||
where
|
||||
G: RecipeCollection<Recipes = Self::Recipes>,
|
||||
{
|
||||
self.assign_inner(
|
||||
self.ref_inner()
|
||||
.iter() // Iterate over every recipe
|
||||
.flat_map(|inner_recipes| {
|
||||
other
|
||||
.ref_inner() // Take a reference of <other> recipe
|
||||
.iter() // Iterate overe every recipe
|
||||
.filter(|&external_recipes| external_recipes.backward_filter(inner_recipes))
|
||||
.map(|external_recipes: &Self::Recipes| {
|
||||
inner_recipes.add_ref_to_self(external_recipes)
|
||||
})
|
||||
.collect::<Vec<_>>() // Collect all a vector of recipe
|
||||
}) // Flatten all the vector of recipes into a big vector
|
||||
.collect::<Vec<Self::Recipes>>(), // Updates the inner collection to the collected recipes
|
||||
);
|
||||
}
|
||||
|
||||
/// Assign the inner value from an owned value, used for blanket implementations
|
||||
fn assign_inner(&mut self, inner: Vec<Self::Recipes>);
|
||||
|
||||
/// Gives access to a reference of the inner list
|
||||
///
|
||||
/// This allows to only clone when needed
|
||||
fn ref_inner(&self) -> &Vec<Self::Recipes>;
|
||||
|
||||
/// Create a collection from a vector
|
||||
fn from_vectored(list: Vec<Self::Recipes>) -> Self;
|
||||
|
||||
/// Create a collection from an iterator of intermediate values T
|
||||
#[cfg_attr(feature = "dev-analysis", coverage(off))] // INCORRECT: Error with line report
|
||||
fn from_iter_intermediate<T>(
|
||||
iter_inter: impl Iterator<Item = Result<T, FatalEquipementError>>,
|
||||
) -> Result<Self, FatalEquipementError>
|
||||
where
|
||||
Self: std::marker::Sized,
|
||||
T: Into<Self::Recipes>,
|
||||
{
|
||||
Ok(Self::from_vectored(
|
||||
iter_inter
|
||||
.map(|r| r.map(|eq_inter| Into::<Self::Recipes>::into(eq_inter)))
|
||||
.collect::<Result<Vec<Self::Recipes>, FatalEquipementError>>()?,
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
/// Trait that ensure that two elements of a recipe are combinable,
|
||||
///
|
||||
/// Being combinable means it can be coerced into elements that implement add
|
||||
pub trait Combinable
|
||||
where
|
||||
for<'a> &'a <Self as Combinable>::Inner: std::ops::Add,
|
||||
{
|
||||
/// The inner type of the combined elements, this type must implement Add<&Inner>
|
||||
type Inner;
|
||||
|
||||
/// Give access to a reference of the underlying data to be combined
|
||||
///
|
||||
/// The designed combinaison method is std::ops::Add
|
||||
fn combinable_part(&self) -> &Self::Inner;
|
||||
|
||||
/// Add an element to self and generate a new Self
|
||||
///
|
||||
/// As the signature implies, it will not mutate self not rhs and will generate a new value from the operation
|
||||
/// This pushes the actual requirement to &Inner : Add<&Inner>
|
||||
fn add_ref_to_self<T>(&self, rhs: &T) -> Self
|
||||
where
|
||||
T: Combinable<Inner = Self::Inner>;
|
||||
|
||||
/// Filter to decide if the addition should be done
|
||||
///
|
||||
///
|
||||
/// Please note that this comparison is done from the new element perspective,
|
||||
/// asking it if it will allow itself to be added as There is as of now no forward filtering
|
||||
/// Most filters will defer an internal FilterFunction into the Inner to do all inner working,
|
||||
/// but the implementation specifics are left open
|
||||
fn backward_filter<T>(&self, lhs: &T) -> bool
|
||||
where
|
||||
T: Combinable<Inner = Self::Inner>;
|
||||
}
|
||||
|
||||
/// Type alias represinting the inner function parameter
|
||||
// #![feature(trait_alias)]
|
||||
pub(super) type FilterFunctionType<T> = dyn Fn(&T, &T) -> bool;
|
||||
/// Type alias representing a filter
|
||||
pub(super) type FilterType<T> = Box<Rc<FilterFunctionType<T>>>;
|
||||
|
||||
#[derive(Clone)]
|
||||
/// A generic Filtering function
|
||||
// DONE: Not implementing deref and allowing for a super pub allows
|
||||
// implementation to be a little more flexible, however this might
|
||||
// also be an oversight
|
||||
pub(crate) struct FilterFunction<T>(pub(super) FilterType<T>);
|
||||
|
||||
/// This element can be converted to tex
|
||||
pub trait ToTex {
|
||||
/// Export the object to a Tex string
|
||||
fn to_tex(&self, config: &Config) -> Result<String, FatalEquipementError>;
|
||||
}
|
||||
|
||||
/// This element can be converted to a csv for further analysis
|
||||
pub trait ToCSV {
|
||||
/// Convert this object into a csv
|
||||
fn write_csv(&self, path: &Path) -> csv::Result<()>;
|
||||
}
|
||||
|
||||
/// This element can be converted to an interactive .html
|
||||
pub trait ToAnalysis {
|
||||
/// The explicit type of the underlying data
|
||||
type InnerData;
|
||||
|
||||
/// Sort the inner data with a given closure
|
||||
fn inner_sort<T>(&mut self, closure: T)
|
||||
where
|
||||
T: FnMut(&Self::InnerData, &Self::InnerData) -> std::cmp::Ordering;
|
||||
|
||||
/// Apply a filter to the inner data
|
||||
///
|
||||
/// Careful this filter will consume the original data to avoir reallocating
|
||||
fn inner_filter<T>(self, closure: T) -> Self
|
||||
where
|
||||
T: FnMut(&Self::InnerData) -> bool;
|
||||
|
||||
/// Write as html
|
||||
fn write_html(&self, path: &str) -> Result<(), FatalEquipementError>;
|
||||
}
|
||||
|
||||
/// A generic database+connection, handling all the deserialization of the inner types
|
||||
pub trait RecipeDatabase {
|
||||
/// The initial Deserialisation struct, SQL will be deserialized into this
|
||||
type DeserialisationType: DeserializeOwned;
|
||||
/// The used type that Deserialisation type will be converted into
|
||||
type InnerType: TryFrom<Self::DeserialisationType>;
|
||||
|
||||
/// Create the database from a file
|
||||
fn new(origin: &str) -> Result<Self, FatalEquipementError>
|
||||
where
|
||||
Self: std::marker::Sized;
|
||||
|
||||
/// Serialize a vector of objects of the given type in the specified table with an optional filter of the underlying database
|
||||
/// The FROM type is the original data, directly deserialized from the table
|
||||
// POI: This element is partly responsible for the difficulty simplifying and generalizing deserialisation
|
||||
fn serialize_vec_from_table<FROM: DeserializeOwned + more_fields::FieldsAsSlice>(
|
||||
&self,
|
||||
table: &str,
|
||||
filter: Option<&str>,
|
||||
) -> Result<Vec<FROM>, crate::error::FatalEquipementError> {
|
||||
crate::database::get_data(self.get_connection(), table, filter)
|
||||
}
|
||||
|
||||
/// Get a reference to the underlying database connection
|
||||
fn get_connection(&self) -> &Connection;
|
||||
|
||||
/// Initialize an empty database & table
|
||||
fn initialize_empty_table<T: more_fields::FieldsAsSlice>(
|
||||
&self,
|
||||
table: &str,
|
||||
) -> Result<(), crate::error::FatalEquipementError> {
|
||||
// A vector of <attribute, type>
|
||||
self.get_connection().execute(
|
||||
crate::database::generate_create_table_query(table, T::attributes_slice()).as_str(),
|
||||
(),
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Insert a row inside the database, while mostly unused this function is needed to initialize the empty table with an empty row if needed
|
||||
#[cfg_attr(feature = "dev-analysis", coverage(off))] // INCORRECT: Error with line report
|
||||
fn insert_row<T: FieldsAsSlice + Serialize>(
|
||||
&self,
|
||||
table_name: &str,
|
||||
row: T,
|
||||
) -> Result<(), FatalEquipementError> {
|
||||
let query = format!(
|
||||
"INSERT INTO {} ({}) VALUES ({});",
|
||||
table_name,
|
||||
T::attributes_slice()
|
||||
.iter()
|
||||
.map(|(k, _v)| *k)
|
||||
.collect::<Vec<_>>()
|
||||
.join(","),
|
||||
T::attributes_slice()
|
||||
.iter()
|
||||
.map(|(k, _v)| ":".to_owned() + *k)
|
||||
.collect::<Vec<_>>()
|
||||
.join(","),
|
||||
);
|
||||
self.get_connection().execute(
|
||||
&query,
|
||||
serde_rusqlite::to_params_named(row)?.to_slice().as_slice(),
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Serialize a request into an intermediate T representation,
|
||||
/// T having all the implementation specifics of the part in details
|
||||
/// eg. EqShape, EqPart etc..
|
||||
fn serialize_into_intermediate<T>(
|
||||
&self,
|
||||
table: &str,
|
||||
filter: Option<&str>,
|
||||
) -> Result<impl Iterator<Item = Result<T, FatalEquipementError>> + '_, FatalEquipementError>
|
||||
where
|
||||
T: From<Self::InnerType>;
|
||||
}
|
||||
|
||||
/// Trait implemented by any struct aiming to be a public recipe
|
||||
pub trait FixedRecipe {
|
||||
// /// Struct representing the database type, most likely a string
|
||||
// type Database;
|
||||
/// Struct representing the keylist type, most likely a usize
|
||||
type KeyList; // TODO: Add the restriction &traits to use the result afterwards
|
||||
|
||||
/// Get the list of elements corresponding to the recipe
|
||||
///
|
||||
/// These elements will either be iteratively fetched from the database or scoured through in the data depending on the scenario
|
||||
fn get_elements_from_table(
|
||||
&self,
|
||||
table: &str,
|
||||
) -> Result<Vec<Self::KeyList>, FatalEquipementError>;
|
||||
}
|
||||
|
||||
/// Trait ensuring a status report can be inferred from the structure
|
||||
pub trait Reportable {
|
||||
/// Get a detailled inner status report with as many useful informations as possible
|
||||
///
|
||||
/// This report should give detailled information about the inner data, without showing the actual inner data
|
||||
fn get_report(&self, title: Option<&str>) -> String;
|
||||
}
|
||||
|
||||
/// A recipe full stack scenario, from loading database through view table generation
|
||||
///
|
||||
/// The inner working while somehow abstracted are very tied together and tied to the impl
|
||||
pub trait Scenario where for<'a> &'a <<<Self as Scenario>::InitialEquipementListType as RecipeCollection>::Recipes as Combinable>::Inner: std::ops::Add
|
||||
// where
|
||||
// for<'a> &'a <<Self as Scenario>::Recipe as Combinable>::Inner: std::ops::Add, for<'a> &'a <<<Self as Scenario>::InitialEquipementListType as RecipeCollection>::Recipes as Combinable>::Inner: std::ops::Add
|
||||
{
|
||||
/// The inner database type
|
||||
type DatabaseType: RecipeDatabase;
|
||||
/// The type of the final recipe list
|
||||
type FinalListType: RefinedList + ToTex + ToCSV + ToAnalysis;
|
||||
/// Inner configuration
|
||||
type Config;
|
||||
/// The initial equipement type, the database serialisation will be to be converted into this type
|
||||
// TODO[!]: Try to remove as it is present in Database
|
||||
type InitialEquipementType;
|
||||
/// The initial equipement list, about to be converted into a refined list
|
||||
type InitialEquipementListType: RecipeCollection; //: Into<impl RecipeCollection<Recipes = Self::Recipe>>;
|
||||
|
||||
// /// The inner element that all serialised data will be serialized into after the intermediate step
|
||||
// type Recipe;
|
||||
|
||||
// for<'a> &'a <<Self as RecipeCollection>::Recipes as Combinable>::Inner: std::ops::Add,
|
||||
|
||||
/// Create a Scenario from a given config
|
||||
fn new_with_config(config: Self::Config) -> Result<Self, FatalEquipementError>
|
||||
where
|
||||
Self: Sized;
|
||||
|
||||
/// Generate the final list type
|
||||
fn generate_refined_recipes(&self) -> Result<Self::FinalListType, FatalEquipementError>;
|
||||
|
||||
/// Retrieve a reference to the inner database
|
||||
fn get_database(&self) -> &Self::DatabaseType;
|
||||
|
||||
/// Retrieve A config
|
||||
fn get_tablename(&self) -> &str;
|
||||
|
||||
|
||||
/// Automatically deserialize into an equipement
|
||||
fn deserde_into_processed_representation<T>(
|
||||
&self,
|
||||
filter: Option<&str>,
|
||||
) -> Result<Self::InitialEquipementListType, FatalEquipementError>
|
||||
where
|
||||
T: From<<<Self as Scenario>::DatabaseType as RecipeDatabase>::InnerType>
|
||||
+ Into<<<Self as Scenario>::InitialEquipementListType as RecipeCollection>::Recipes>,
|
||||
{
|
||||
RecipeCollection::from_iter_intermediate::<T>(
|
||||
self.get_database()
|
||||
.serialize_into_intermediate::<T>(self.get_tablename(), filter)?,
|
||||
)
|
||||
}
|
||||
}
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::RecipeCollection;
|
||||
use crate::weaponry_structs::{InitialEquipementList, equipement_structs::EqShape};
|
||||
|
||||
#[test]
|
||||
fn test_from_iter_intermediate() {
|
||||
let _b = <InitialEquipementList as RecipeCollection>::from_iter_intermediate::<EqShape>(
|
||||
[Ok(EqShape::default()), Ok(EqShape::default())].into_iter(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,24 @@
|
|||
// Workspace: weaponry
|
||||
// File: weaponry/src/lib.rs
|
||||
//! Weaponry module, handling all weaponry creation and analysis
|
||||
|
||||
#![cfg_attr(feature = "dev-analysis", feature(coverage_attribute))]
|
||||
#![warn(missing_docs, clippy::missing_docs_in_private_items)]
|
||||
// #![feature(iter_intersperse)]
|
||||
|
||||
pub mod analysis;
|
||||
mod database;
|
||||
pub mod error;
|
||||
pub mod export;
|
||||
pub mod interfaces;
|
||||
#[macro_use]
|
||||
pub mod weaponry_structs;
|
||||
pub mod export_tex;
|
||||
|
||||
/// Signals the function running is unfinished
|
||||
#[macro_export]
|
||||
macro_rules! unfinished {
|
||||
() => {
|
||||
println!("UNFINISHED FUNCTION CALLED AT {} LINE {}", file!(), line!());
|
||||
};
|
||||
}
|
||||
|
|
@ -0,0 +1,87 @@
|
|||
// 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!()
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,511 @@
|
|||
// Workspace: weaponry
|
||||
// File: weaponry/src/weaponry_structs/equipement_advanced_repr.rs
|
||||
//! Give an advanced representation of the equipement, infering more fields (such a dpt, max_dps etc...)
|
||||
//!
|
||||
//! The generation of this fields is primordial to allow post filtering and visualisation
|
||||
//!
|
||||
//! Note that while ALL fields and representation will likely be backed into a megablob,
|
||||
//! nothing prevents us to implement the trait for other objects and avoid massive computation
|
||||
//! of all the fields even when the user will not be interested in them
|
||||
#![allow(dead_code)]
|
||||
use super::{
|
||||
equipement_advanced_tools::{
|
||||
BestDamageScenarios, get_damage_with_simulation, get_sustained_damage,
|
||||
},
|
||||
equipement_thin_types::{Actions, Attacks},
|
||||
};
|
||||
use crate::{
|
||||
add_field_to_chart,
|
||||
error::FatalEquipementError,
|
||||
export::{initial_chart, initial_plot_chart},
|
||||
interfaces::{RecipeCollection, RefinedList, ToAnalysis},
|
||||
weaponry_structs::{
|
||||
Equipement, InitialEquipementList, WeaponBaseShape,
|
||||
equipement_fields::WeaponBaseSize,
|
||||
equipement_structs::InnerEquipementStats,
|
||||
equipement_thin_types::{Dices, Precision},
|
||||
},
|
||||
};
|
||||
use charming::{Chart, component::LegendSelectedMode};
|
||||
use core::f64;
|
||||
use serde::Serialize;
|
||||
use std::{cmp::Ordering, ops::Deref};
|
||||
|
||||
/// The final representation of the equipement inplementing all the fields needed for processing
|
||||
// TODO: Add a public getter for the inner data
|
||||
pub struct RefinedEquipement {
|
||||
/// The original inner stats
|
||||
///
|
||||
/// This structs takes ownership of the inner data
|
||||
pub inner: InnerEquipementStats,
|
||||
|
||||
/// Advanced stats
|
||||
pub advanced: AdvancedStats,
|
||||
}
|
||||
|
||||
/// The complete equipement list, refined with all advanced stats
|
||||
pub struct RefinedEquipementList {
|
||||
/// Inner list of Refined Equipements
|
||||
// TODO[!]: The use of pub stays for the usage of the example showcasing the macro in export
|
||||
pub inner: Vec<RefinedEquipement>,
|
||||
}
|
||||
|
||||
#[allow(clippy::missing_docs_in_private_items)]
|
||||
/// The exportable equipement minimum precalculated stats
|
||||
#[derive(Serialize)]
|
||||
pub struct ExportableEquipement {
|
||||
pub name: String,
|
||||
pub category: Option<WeaponBaseShape>,
|
||||
pub maniement: String,
|
||||
pub damage_base: i8,
|
||||
pub damage_per: i8,
|
||||
pub rmax: i8,
|
||||
pub arbreak: i8,
|
||||
pub protection: i8,
|
||||
pub integrity: i8,
|
||||
pub torque_one_handed: Option<i8>,
|
||||
pub torque_two_handed: Option<i8>,
|
||||
pub modes: String,
|
||||
pub esquive: String,
|
||||
pub parrade: String,
|
||||
pub vitesse: String,
|
||||
pub discretion: String,
|
||||
pub difficulty: String,
|
||||
pub cost: String,
|
||||
pub special: String,
|
||||
pub needs_break: bool,
|
||||
}
|
||||
|
||||
/// Put half numbers
|
||||
fn halves(f: f32) -> String {
|
||||
let base = f.floor();
|
||||
let extra = f - base;
|
||||
if !(-0.1..=0.1).contains(&extra) {
|
||||
if base == 0. {
|
||||
"\\half{}".to_string()
|
||||
} else {
|
||||
format!("{base:0}\\half{{}}")
|
||||
}
|
||||
} else {
|
||||
format!("{base}")
|
||||
}
|
||||
}
|
||||
impl From<&RefinedEquipement> for ExportableEquipement {
|
||||
fn from(value: &RefinedEquipement) -> Self {
|
||||
let mut special = Vec::new();
|
||||
if value.inner.action_cost != 0 && value.inner.action_cost != 1 {
|
||||
special.push(format!(r"{}A", value.inner.action_cost));
|
||||
}
|
||||
if let Some(cost) = value.inner.reload_cost {
|
||||
special.push(format!(r"{cost}\reload{{}}"));
|
||||
};
|
||||
if value.inner.armor_pierce != 0 {
|
||||
let mut parmure = value.inner.armor_pierce;
|
||||
match (&value.inner.category_base, &value.inner.category_size) {
|
||||
(&Some(WeaponBaseShape::Ranged), Some(WeaponBaseSize::Heavy)) => parmure += 1,
|
||||
(&Some(WeaponBaseShape::Ranged), Some(WeaponBaseSize::SuperHeavy)) => parmure += 1,
|
||||
_ => (),
|
||||
}
|
||||
special.push(format!(r"\glssymbol{{parmure}} {parmure}"));
|
||||
}
|
||||
if value.inner.range != 0 {
|
||||
let mut range = value.inner.range;
|
||||
match (&value.inner.category_base, &value.inner.category_size) {
|
||||
(&Some(WeaponBaseShape::Ranged), Some(WeaponBaseSize::Heavy)) => range += 30,
|
||||
(&Some(WeaponBaseShape::Ranged), Some(WeaponBaseSize::SuperHeavy)) => range += 60,
|
||||
_ => (),
|
||||
}
|
||||
special.push(format!(r"{range}m"));
|
||||
}
|
||||
if value.inner.precision != 0 {
|
||||
special.push(format!(
|
||||
r"\glssymbol{{precision}} {:+}",
|
||||
value.inner.precision
|
||||
));
|
||||
}
|
||||
if value.inner.agility_bonus != 0. {
|
||||
special.push(format!(r"Ag {}", halves(value.inner.agility_bonus)));
|
||||
}
|
||||
Self {
|
||||
name: value.advanced.display_name.clone(),
|
||||
maniement: value.inner.get_maniement(),
|
||||
damage_base: value.inner.damage,
|
||||
damage_per: value.inner.p_damage,
|
||||
rmax: value.inner.rmax,
|
||||
arbreak: value.inner.armor_break,
|
||||
protection: value.inner.protection,
|
||||
integrity: value.inner.integrity,
|
||||
torque_one_handed: value.inner.torque_one_handed,
|
||||
torque_two_handed: value.inner.torque_two_handed,
|
||||
modes: value.inner.get_modes(),
|
||||
esquive: halves(value.inner.dodge),
|
||||
parrade: value.inner.parry.to_string(),
|
||||
vitesse: value.inner.speed.to_string(),
|
||||
discretion: value.inner.stealth.to_string(),
|
||||
difficulty: value.inner.difficulty.to_string(),
|
||||
category: value.inner.category_base,
|
||||
special: special.join(", "),
|
||||
needs_break: false,
|
||||
cost: value.inner.cost.to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// DONE: The use of Deref could be a subtle gotcha
|
||||
impl Deref for RefinedEquipementList {
|
||||
type Target = Vec<RefinedEquipement>;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.inner
|
||||
}
|
||||
}
|
||||
|
||||
// Just a checkmark
|
||||
impl RefinedList for RefinedEquipementList {}
|
||||
|
||||
impl ToAnalysis for RefinedEquipementList {
|
||||
type InnerData = RefinedEquipement;
|
||||
|
||||
fn inner_sort<T>(&mut self, closure: T)
|
||||
where
|
||||
T: FnMut(&RefinedEquipement, &RefinedEquipement) -> Ordering,
|
||||
{
|
||||
self.inner.sort_by(closure)
|
||||
}
|
||||
|
||||
fn inner_filter<T>(self, closure: T) -> Self
|
||||
where
|
||||
T: FnMut(&RefinedEquipement) -> bool,
|
||||
{
|
||||
Self {
|
||||
inner: self.inner.into_iter().filter(closure).collect::<Vec<_>>(),
|
||||
}
|
||||
}
|
||||
|
||||
// DONE: While a custom config would allow some personalisation, there is no reason to beleive a more meaningfull name would be choosen
|
||||
fn write_html(&self, save_path: &str) -> Result<(), FatalEquipementError> {
|
||||
let mut renderer = charming::HtmlRenderer::new("Ravenous Bob", 1920, 900)
|
||||
.theme(charming::theme::Theme::Dark);
|
||||
|
||||
let initial_chart = self.make_regular_graph();
|
||||
renderer.save(&initial_chart, format!("{save_path}.html"))?;
|
||||
|
||||
let plot_chart = self.make_cross_plots_graph();
|
||||
renderer.save(&plot_chart, format!("{save_path}_plots.html"))?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl RefinedEquipementList {
|
||||
/// Make the cross graphs
|
||||
fn make_cross_plots_graph(&self) -> Chart {
|
||||
let mut plot_chart = initial_plot_chart(
|
||||
"Damage Gradients Dice/Precision",
|
||||
&["Damage 4+2A", "Damage 5+2A", "Damage 5+3A", "Damage 6+3A"],
|
||||
);
|
||||
let mut names = Vec::with_capacity(self.inner.len());
|
||||
|
||||
for wpn in self.inner.iter() {
|
||||
let data_4_a2: Vec<Vec<f64>> = custom_scenario(&wpn.inner, Actions(4), Attacks(2));
|
||||
let data_5_a2: Vec<Vec<f64>> = custom_scenario(&wpn.inner, Actions(5), Attacks(2));
|
||||
let data_5_a3: Vec<Vec<f64>> = custom_scenario(&wpn.inner, Actions(5), Attacks(3));
|
||||
let data_6_a3: Vec<Vec<f64>> = custom_scenario(&wpn.inner, Actions(6), Attacks(3));
|
||||
plot_chart = add_serie(plot_chart, 0, wpn, data_4_a2);
|
||||
plot_chart = add_serie(plot_chart, 1, wpn, data_5_a2);
|
||||
plot_chart = add_serie(plot_chart, 2, wpn, data_5_a3);
|
||||
plot_chart = add_serie(plot_chart, 3, wpn, data_6_a3);
|
||||
names.push(wpn.advanced.display_name.as_str());
|
||||
}
|
||||
|
||||
plot_chart = plot_chart.legend(
|
||||
charming::component::Legend::new()
|
||||
.left(10)
|
||||
.top("middle")
|
||||
.orient(charming::element::Orient::Vertical)
|
||||
.data(names)
|
||||
.selected_mode(LegendSelectedMode::Multiple),
|
||||
);
|
||||
plot_chart
|
||||
}
|
||||
|
||||
/// Max the regular balancing plots
|
||||
fn make_regular_graph(&self) -> Chart {
|
||||
let initial_chart: Chart = initial_chart(&format!(
|
||||
"Damage for all cross-gen products ({} Elements)",
|
||||
self.inner.len()
|
||||
));
|
||||
|
||||
macro_rules! round {
|
||||
($a:expr) => {
|
||||
($a * 100.).round() / 100.
|
||||
};
|
||||
}
|
||||
add_field_to_chart!(
|
||||
self,
|
||||
initial_chart,
|
||||
(
|
||||
index # &String,
|
||||
max_damage_per_attack # f64,
|
||||
armor_break_per_attack # f64,
|
||||
// expected_armor_break_per_attack # f64,
|
||||
avg_damage_2a_safe # f64,
|
||||
avg_damage_2a_huge_hit # f64,
|
||||
// speed # f64,
|
||||
variance # f64,
|
||||
variance_pct # f64,
|
||||
scenario_damage # f64,
|
||||
defensive # f64,
|
||||
earlygame_sustained_damage_per_turn # f64,
|
||||
midgame_sustained_damage_per_turn # f64,
|
||||
endgame_sustained_damage_per_turn # f64,
|
||||
),
|
||||
|ref_equipement| {
|
||||
(
|
||||
&ref_equipement.advanced.display_name,
|
||||
round!(ref_equipement.advanced.max_damage_per_attack ),
|
||||
round!(ref_equipement.advanced.armor_break_per_attack ),
|
||||
// round!(ref_equipement.advanced.expected_armor_break_per_attack ),
|
||||
round!(ref_equipement.advanced.avg_damage_2a_safe ),
|
||||
round!(ref_equipement.advanced.avg_damage_2a_huge_hit ),
|
||||
// round!(ref_equipement.advanced.speed),
|
||||
round!(ref_equipement.advanced.variance),
|
||||
round!(ref_equipement.advanced.variance_pct ),
|
||||
round!(ref_equipement.advanced.scenario_damage ),
|
||||
round!(ref_equipement.advanced.defensive ),
|
||||
round!(ref_equipement.advanced.earlygame_sustained_damage_per_turn ),
|
||||
round!(ref_equipement.advanced.midgame_sustained_damage_per_turn ),
|
||||
round!(ref_equipement.advanced.endgame_sustained_damage_per_turn ),
|
||||
)
|
||||
}
|
||||
);
|
||||
initial_chart
|
||||
}
|
||||
}
|
||||
|
||||
/// Inner function to add a serie to a plot
|
||||
fn add_serie(plot_chart: Chart, id: u8, wpn: &RefinedEquipement, serie: Vec<Vec<f64>>) -> Chart {
|
||||
plot_chart.series(
|
||||
charming::series::Line::new()
|
||||
.x_axis_index(id)
|
||||
.y_axis_index(id)
|
||||
.data(serie)
|
||||
.name(&wpn.advanced.display_name),
|
||||
)
|
||||
}
|
||||
|
||||
/// Custom scenario for creating scatter plot
|
||||
fn custom_scenario(
|
||||
equipement_stats: &InnerEquipementStats,
|
||||
actions: Actions,
|
||||
attacks: Attacks,
|
||||
) -> Vec<Vec<f64>> {
|
||||
(1..11)
|
||||
.map(|dice| {
|
||||
vec![
|
||||
dice as f64,
|
||||
BestDamageScenarios::from_action_constraints_it(
|
||||
equipement_stats,
|
||||
actions,
|
||||
attacks,
|
||||
Dices(dice),
|
||||
Precision(9),
|
||||
)
|
||||
.unwrap_or_default()
|
||||
.damage_done,
|
||||
]
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The list of advanced stats infered from an Equipement
|
||||
#[derive(Serialize)]
|
||||
pub struct AdvancedStats {
|
||||
/// A simple name created by merging all components
|
||||
pub display_name: String,
|
||||
/// The absolute maximum damage done with each attack
|
||||
pub max_damage_per_attack: f64,
|
||||
// /// The absolute maximum damage done every turn (with two attacks)
|
||||
// pub max_damage_per_turn: f64,
|
||||
/// The armor break per attack
|
||||
pub armor_break_per_attack: f64,
|
||||
// This category of every result, using this would be better than id shenenigans
|
||||
// pub category: Option<WeaponMacroCategory>,
|
||||
/// Armor break factoring in the damage output:
|
||||
/// While a weapon might have high AB, not having any damage will seriously hinder that AB
|
||||
pub expected_armor_break_per_attack: f64,
|
||||
/// Dps with two actions and 5 dices over a variety of scenarios
|
||||
pub avg_damage_2a_safe: f64,
|
||||
/// Dps with four actions and 11 dices over a variety of scenarios
|
||||
pub avg_damage_2a_huge_hit: f64,
|
||||
/// The speed given by the weapon
|
||||
pub speed: f64,
|
||||
/// The damage obtained after a 10 turn pseudo scenario
|
||||
pub scenario_damage: f64,
|
||||
/// A defensive metric giving the best defense bonus for the weapon
|
||||
pub defensive: f64,
|
||||
/// The sustained damage of an earlygame character, normalized over 10 turns
|
||||
pub earlygame_sustained_damage_per_turn: f64,
|
||||
/// The sustained damage of an earlygame character, normalized over 10 turns
|
||||
pub midgame_sustained_damage_per_turn: f64,
|
||||
/// The sustained damage of an endgame character, normalized over 10 turns
|
||||
pub endgame_sustained_damage_per_turn: f64,
|
||||
/// The damage variance between the base damage and the potential damage
|
||||
pub variance: f64,
|
||||
/// This same variance as a percent
|
||||
pub variance_pct: f64,
|
||||
// QOL Metrics
|
||||
}
|
||||
impl From<&InnerEquipementStats> for AdvancedStats {
|
||||
fn from(value: &InnerEquipementStats) -> Self {
|
||||
let max_damage_per_attack = (value.damage + value.p_damage * (value.rmax - 1)) as f64;
|
||||
let armor_break_per_attack =
|
||||
(value.armor_break as f64 + value.antimaterial as f64).min(max_damage_per_attack);
|
||||
let variance = (value.p_damage * value.rmax) as f64;
|
||||
Self {
|
||||
display_name: value.name.join(" "),
|
||||
max_damage_per_attack,
|
||||
speed: value.speed.into(),
|
||||
armor_break_per_attack,
|
||||
// Adds the base strength, substracts the expected protection
|
||||
expected_armor_break_per_attack: (max_damage_per_attack + 6. - 8.)
|
||||
.min(armor_break_per_attack)
|
||||
* 2.
|
||||
/ value.action_cost as f64,
|
||||
scenario_damage: get_damage_with_simulation(value, Actions(4), Attacks(2)),
|
||||
defensive: (value.parry as f64).max(value.dodge.into()),
|
||||
variance,
|
||||
variance_pct: variance / value.damage as f64,
|
||||
avg_damage_2a_safe: BestDamageScenarios::from_action_constraints_it(
|
||||
value,
|
||||
Actions(2),
|
||||
Attacks(2),
|
||||
Dices(4),
|
||||
Precision(8),
|
||||
)
|
||||
.map(|f| *f)
|
||||
.unwrap_or_default(),
|
||||
avg_damage_2a_huge_hit: BestDamageScenarios::from_action_constraints_it(
|
||||
value,
|
||||
Actions(2),
|
||||
Attacks(2),
|
||||
Dices(10),
|
||||
Precision(9),
|
||||
)
|
||||
.map(|f| *f)
|
||||
.unwrap_or_default(),
|
||||
earlygame_sustained_damage_per_turn: get_sustained_damage(
|
||||
value,
|
||||
Actions(4),
|
||||
Attacks(2),
|
||||
Dices(9),
|
||||
Precision(8),
|
||||
),
|
||||
midgame_sustained_damage_per_turn: get_sustained_damage(
|
||||
value,
|
||||
Actions(5),
|
||||
Attacks(3),
|
||||
Dices(11),
|
||||
Precision(9),
|
||||
),
|
||||
|
||||
endgame_sustained_damage_per_turn: get_sustained_damage(
|
||||
value,
|
||||
Actions(6),
|
||||
Attacks(3),
|
||||
Dices(13),
|
||||
Precision(10),
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Serialize for RefinedEquipement {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: serde::Serializer,
|
||||
{
|
||||
self.advanced.serialize(serializer)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Equipement> for RefinedEquipement {
|
||||
fn from(value: Equipement) -> Self {
|
||||
Self {
|
||||
advanced: AdvancedStats::from(&value.stats),
|
||||
inner: value.stats,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<InitialEquipementList> for RefinedEquipementList {
|
||||
fn from(value: InitialEquipementList) -> Self {
|
||||
Self {
|
||||
inner: value
|
||||
.inner
|
||||
.into_iter()
|
||||
.map(RefinedEquipement::from)
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// #[cfg(test)] // Used in exemples
|
||||
impl Default for RefinedEquipementList {
|
||||
fn default() -> Self {
|
||||
let eq = InitialEquipementList::from_vectored(vec![Equipement::default(); 10]);
|
||||
RefinedEquipementList::from(eq)
|
||||
}
|
||||
}
|
||||
#[macro_export]
|
||||
/// A simple macro to sort the inner advanced field by a specific field
|
||||
// TODO[6] find a way to not have to import the refinedequipement
|
||||
macro_rules! sort_by {
|
||||
($field:ident) => {
|
||||
|a: &RefinedEquipement, b: &RefinedEquipement| {
|
||||
a.advanced.$field.total_cmp(&b.advanced.$field)
|
||||
}
|
||||
};
|
||||
}
|
||||
#[macro_export]
|
||||
/// A simple macro to sort the inner advanced field by a specific field
|
||||
// TODO[6] find a way to not have to import the refinedequipement
|
||||
macro_rules! sort_by_weapon_then {
|
||||
($field:ident) => {
|
||||
|a, b| match a.inner.id[0].cmp(&b.inner.id[0]) {
|
||||
std::cmp::Ordering::Equal => a.advanced.$field.total_cmp(&b.advanced.$field),
|
||||
ord => ord,
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
#[macro_export]
|
||||
/// Sort by size first, then by the given field
|
||||
macro_rules! sort_by_cat_then {
|
||||
($field:ident) => {
|
||||
|a, b| {
|
||||
if let (Some(c), Some(d)) = (
|
||||
a.inner.category_size.as_ref(),
|
||||
b.inner.category_size.as_ref(),
|
||||
) {
|
||||
match c.cmp(d) {
|
||||
std::cmp::Ordering::Equal => a.advanced.$field.total_cmp(&b.advanced.$field),
|
||||
ord => ord,
|
||||
}
|
||||
} else {
|
||||
a.advanced.$field.total_cmp(&b.advanced.$field)
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
#[macro_export]
|
||||
/// A simple macro to sort the inner advanced field by a specific field
|
||||
// TODO[6] find a way to not have to import the refinedequipement
|
||||
macro_rules! sort_by_size_then {
|
||||
($field:ident) => {
|
||||
|a, b| match a.inner.category_size.cmp(&b.inner.category_size) {
|
||||
std::cmp::Ordering::Equal => a.advanced.$field.total_cmp(&b.advanced.$field),
|
||||
ord => ord,
|
||||
}
|
||||
};
|
||||
}
|
||||
|
|
@ -0,0 +1,613 @@
|
|||
// Workspace: weaponry
|
||||
// File: weaponry/src/weaponry_structs/equipement_advanced_tools.rs
|
||||
//! Tools for the advanced representation, all grouped in a module for convenience
|
||||
use crate::weaponry_structs::equipement_structs::InnerEquipementStats;
|
||||
use probability::distribution::Discrete;
|
||||
use probability::prelude::Binomial;
|
||||
use std::ops::Add;
|
||||
use std::ops::Deref;
|
||||
|
||||
use super::equipement_thin_types::Actions;
|
||||
use super::equipement_thin_types::Attacks;
|
||||
use super::equipement_thin_types::Dices;
|
||||
use super::equipement_thin_types::Precision;
|
||||
|
||||
/// Create the damage profile with the following simulation:
|
||||
/// 10turns total
|
||||
/// - 1 turn no damage
|
||||
/// - 2 turns full damage (12 dice, 130% precision)
|
||||
/// - 2 turns safe attacks (5 dice, 50%p)
|
||||
/// - 1 turn highspeed/range hit (7 dice, 80% precision)
|
||||
/// - 4 turns normal damage (7 dice, 90% precision)
|
||||
pub(super) fn get_damage_with_simulation(
|
||||
value: &InnerEquipementStats,
|
||||
actions: Actions,
|
||||
attacks: Attacks,
|
||||
) -> f64 {
|
||||
let mut turns = vec![
|
||||
TurnInfo {
|
||||
actions: Actions(0),
|
||||
attacks: Attacks(0),
|
||||
dices: Dices(0),
|
||||
precision: Precision(0),
|
||||
},
|
||||
TurnInfo {
|
||||
actions,
|
||||
attacks,
|
||||
dices: Dices(12),
|
||||
precision: Precision(13),
|
||||
},
|
||||
TurnInfo {
|
||||
actions,
|
||||
attacks,
|
||||
dices: Dices(12),
|
||||
precision: Precision(13),
|
||||
},
|
||||
TurnInfo {
|
||||
actions,
|
||||
attacks: attacks - Attacks(1),
|
||||
dices: Dices(5),
|
||||
precision: Precision(5),
|
||||
},
|
||||
TurnInfo {
|
||||
actions,
|
||||
attacks: attacks - Attacks(1),
|
||||
dices: Dices(5),
|
||||
precision: Precision(5),
|
||||
},
|
||||
// Cuck turn
|
||||
TurnInfo {
|
||||
actions,
|
||||
attacks,
|
||||
dices: Dices(7),
|
||||
precision: Precision(9),
|
||||
},
|
||||
TurnInfo {
|
||||
actions,
|
||||
attacks,
|
||||
dices: Dices(7),
|
||||
precision: Precision(9),
|
||||
},
|
||||
TurnInfo {
|
||||
actions,
|
||||
attacks,
|
||||
dices: Dices(7),
|
||||
precision: Precision(9),
|
||||
},
|
||||
TurnInfo {
|
||||
actions,
|
||||
attacks,
|
||||
dices: Dices(7),
|
||||
precision: Precision(9),
|
||||
},
|
||||
];
|
||||
if (value.speed >= 5) || (value.range > 0) {
|
||||
turns.push(TurnInfo {
|
||||
actions,
|
||||
attacks,
|
||||
dices: Dices(6),
|
||||
precision: Precision(5),
|
||||
});
|
||||
} else {
|
||||
turns.push(TurnInfo {
|
||||
actions: Actions(1),
|
||||
attacks: Attacks(1),
|
||||
dices: Dices(6),
|
||||
precision: Precision(5),
|
||||
});
|
||||
}
|
||||
|
||||
damage_over_turns(value, &turns) / 10.
|
||||
}
|
||||
|
||||
/// Sustained damage
|
||||
///
|
||||
/// Average damage factoring reload, calculated with 9 dice and 90% precision
|
||||
pub(super) fn get_sustained_damage(
|
||||
value: &InnerEquipementStats,
|
||||
actions: Actions,
|
||||
attacks: Attacks,
|
||||
dices: Dices,
|
||||
precision: Precision,
|
||||
) -> f64 {
|
||||
// Actions total and damage total are arbitrarely choosen
|
||||
|
||||
let l = &[TurnInfo {
|
||||
actions,
|
||||
attacks,
|
||||
dices,
|
||||
precision,
|
||||
}; 10];
|
||||
damage_over_turns(value, l) / 10.
|
||||
// Iterate 10 turns, every turn we need to substract the leftover reloading
|
||||
// value.damage.into()
|
||||
}
|
||||
|
||||
/// Exists internally to pass variables
|
||||
#[derive(Clone, Copy)]
|
||||
#[allow(clippy::missing_docs_in_private_items)]
|
||||
struct TurnInfo {
|
||||
actions: Actions,
|
||||
attacks: Attacks,
|
||||
dices: Dices,
|
||||
precision: Precision,
|
||||
}
|
||||
|
||||
/// Calculate the damage over a series of consecutive turns using the given slice of turn info
|
||||
fn damage_over_turns(value: &InnerEquipementStats, turn_info: &[TurnInfo]) -> f64 {
|
||||
// With reload, damage calculation is rather complicated, since you can half reload but cant half attack
|
||||
// so a reload is valid even if you don't reload fully, but you have to start your turn with less actions
|
||||
// instead of building a complex scenario, the attack pattern is always: Ac:Attack + Re:Reload(and maybe reminder) every turn
|
||||
let mut reloading_left = Actions(0);
|
||||
let mut total_damage = 0.;
|
||||
for TurnInfo {
|
||||
actions,
|
||||
attacks,
|
||||
dices,
|
||||
precision,
|
||||
} in turn_info
|
||||
{
|
||||
if let Some(BestDamageScenarios {
|
||||
actions_used: _,
|
||||
attacks_used: _,
|
||||
damage_done,
|
||||
reload_remaining,
|
||||
}) = BestDamageScenarios::from_action_constraints_it(
|
||||
value,
|
||||
*actions - reloading_left,
|
||||
*attacks,
|
||||
*dices,
|
||||
*precision,
|
||||
) {
|
||||
reloading_left = reload_remaining;
|
||||
total_damage += damage_done;
|
||||
}
|
||||
}
|
||||
total_damage
|
||||
}
|
||||
|
||||
/// The best resulting attack pattern of a virtual scenrio where some conditions are given
|
||||
#[derive(Debug, Default)]
|
||||
#[cfg_attr(test, derive(Clone))]
|
||||
pub struct BestDamageScenarios {
|
||||
/// How many actions were used by the best attack
|
||||
pub actions_used: Actions,
|
||||
/// Attacks actions used by the scenario
|
||||
pub attacks_used: Attacks,
|
||||
/// Resulting damage
|
||||
pub damage_done: f64,
|
||||
/// Remaining actions that need to be used to finish reload
|
||||
pub reload_remaining: Actions,
|
||||
}
|
||||
|
||||
impl Add for BestDamageScenarios {
|
||||
type Output = Self;
|
||||
|
||||
fn add(self, rhs: Self) -> Self::Output {
|
||||
Self {
|
||||
actions_used: self.actions_used + rhs.actions_used,
|
||||
attacks_used: self.attacks_used + rhs.attacks_used,
|
||||
damage_done: self.damage_done + rhs.damage_done,
|
||||
reload_remaining: self.reload_remaining + rhs.reload_remaining,
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Deref for BestDamageScenarios {
|
||||
type Target = f64;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.damage_done
|
||||
}
|
||||
}
|
||||
|
||||
impl BestDamageScenarios {
|
||||
/// Calculate the best alternative with a set of contraints
|
||||
///
|
||||
/// Returns None if the scenario cant exist with the current conditions (too few actions for an attack to be launched)
|
||||
// DONE: While this abomination is really subpar code, there is no time to clean things that work
|
||||
pub fn from_action_constraints_it(
|
||||
equipement_stats: &InnerEquipementStats,
|
||||
actions_allowed: Actions,
|
||||
attacks_allowed: Attacks,
|
||||
dices_allowed: Dices,
|
||||
precision: Precision,
|
||||
) -> Option<Self> {
|
||||
let full_attack_cost =
|
||||
equipement_stats.action_cost + equipement_stats.reload_cost.unwrap_or_default();
|
||||
if full_attack_cost == 0 {
|
||||
return None;
|
||||
}
|
||||
let nb_max_attacks_reload = actions_allowed.div_euclid(full_attack_cost);
|
||||
let remaining_actions = actions_allowed.rem_euclid(full_attack_cost);
|
||||
let (remaining_reload, extra_attack) = if remaining_actions >= equipement_stats.action_cost
|
||||
{
|
||||
(-(remaining_actions - *attacks_allowed), Attacks(1))
|
||||
} else {
|
||||
(0, Attacks(0))
|
||||
};
|
||||
|
||||
// Loop from the extra attack and go down
|
||||
let mut values: Vec<(i8, i8, f64)> = (1..=(nb_max_attacks_reload + *extra_attack)
|
||||
.clamp(0, *attacks_allowed))
|
||||
.map(|attacks| {
|
||||
(
|
||||
attacks,
|
||||
{
|
||||
if nb_max_attacks_reload + *extra_attack == attacks {
|
||||
remaining_reload
|
||||
} else {
|
||||
0
|
||||
}
|
||||
},
|
||||
stack_binomials(equipement_stats, dices_allowed, precision, attacks),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
|
||||
values.sort_by(|(_, _, v1), (_, _, v2)| v2.total_cmp(v1));
|
||||
(!values.is_empty()).then(|| Self {
|
||||
actions_used: Actions((values[0].0 * full_attack_cost).clamp(0, *actions_allowed)),
|
||||
attacks_used: Attacks(values[0].0),
|
||||
damage_done: values[0].2,
|
||||
reload_remaining: Actions(values[0].1),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Do as many binomials as there are attacks
|
||||
fn stack_binomials(
|
||||
equipement_stats: &InnerEquipementStats,
|
||||
dices_allowed: Dices,
|
||||
precision: Precision,
|
||||
attacks: i8,
|
||||
) -> f64 {
|
||||
(binomial_dice_distribution(
|
||||
equipement_stats,
|
||||
precision,
|
||||
Dices(dices_allowed.div_euclid(attacks.try_into().unwrap())),
|
||||
) * (attacks - 1) as f64)
|
||||
+ (binomial_dice_distribution(
|
||||
equipement_stats,
|
||||
precision,
|
||||
Dices(
|
||||
dices_allowed.div_euclid(attacks.try_into().unwrap())
|
||||
+ dices_allowed.rem_euclid(attacks.try_into().unwrap()),
|
||||
),
|
||||
))
|
||||
}
|
||||
|
||||
/// Calculate the binomial distribution and average the damage from there
|
||||
pub(super) fn binomial_dice_distribution(
|
||||
equipement: &InnerEquipementStats,
|
||||
precision: Precision,
|
||||
dices: Dices,
|
||||
) -> f64 {
|
||||
let p = ((*precision + equipement.precision) as f64 / 10.).clamp(0. + 1E-10, 1. - 1E-10);
|
||||
let binomial = Binomial::new(*dices, p);
|
||||
|
||||
(0..*dices + 1)
|
||||
.map(|target_dices| {
|
||||
let probability_success = binomial.mass(target_dices); // Let's have weird half dices as usize;
|
||||
if target_dices >= 1 {
|
||||
(equipement.damage as f64
|
||||
+ equipement.p_damage as f64
|
||||
* (target_dices
|
||||
.saturating_sub(1)
|
||||
.clamp(0, (equipement.rmax - 1) as usize))
|
||||
as f64)
|
||||
* probability_success
|
||||
} else {
|
||||
0.
|
||||
}
|
||||
})
|
||||
.fold(0., |a, b| a + b)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use crate::weaponry_structs::{
|
||||
equipement_structs::InnerEquipementStats,
|
||||
equipement_thin_types::{Actions, Attacks},
|
||||
};
|
||||
|
||||
use super::{
|
||||
BestDamageScenarios, Dices, Precision, binomial_dice_distribution,
|
||||
get_damage_with_simulation,
|
||||
};
|
||||
|
||||
fn new_inner_eq() -> InnerEquipementStats {
|
||||
InnerEquipementStats {
|
||||
damage: 10,
|
||||
p_damage: 2,
|
||||
precision: 0,
|
||||
rmax: 2,
|
||||
armor_break: 2,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! assert_close {
|
||||
($a:expr, $b:expr) => {
|
||||
println!("{} ~= {}", $a, $b);
|
||||
assert!(($a - $b).abs() < 1E-3);
|
||||
};
|
||||
}
|
||||
|
||||
pub(super) fn average_damage(
|
||||
equipement: &InnerEquipementStats,
|
||||
precisions: &[Precision],
|
||||
list_dices: &[Dices],
|
||||
) -> f64 {
|
||||
precisions
|
||||
.iter()
|
||||
.map(|precision| {
|
||||
list_dices
|
||||
.iter()
|
||||
.map(|dices| binomial_dice_distribution(equipement, *precision, *dices))
|
||||
.sum::<f64>()
|
||||
})
|
||||
.sum::<f64>()
|
||||
/ (precisions.len() as f64 * list_dices.len() as f64)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn basic_binomial() {
|
||||
let eq = new_inner_eq();
|
||||
assert_close!(
|
||||
average_damage(&eq, &[Precision(9)], &[Dices(9)]),
|
||||
11.999999826
|
||||
);
|
||||
assert_close!(average_damage(&eq, &[Precision(4)], &[Dices(4)]), 9.753599);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_damage_optimisation_it() {
|
||||
let eq = InnerEquipementStats {
|
||||
damage: 10,
|
||||
p_damage: 2,
|
||||
precision: 0,
|
||||
rmax: 2,
|
||||
action_cost: 1,
|
||||
..Default::default()
|
||||
};
|
||||
let eq2 = InnerEquipementStats {
|
||||
damage: 10,
|
||||
p_damage: 2,
|
||||
precision: 0,
|
||||
rmax: 2,
|
||||
speed: 10,
|
||||
action_cost: 2,
|
||||
..Default::default()
|
||||
};
|
||||
let eq3 = InnerEquipementStats {
|
||||
damage: 10,
|
||||
p_damage: 2,
|
||||
precision: 0,
|
||||
rmax: 2,
|
||||
range: 10,
|
||||
action_cost: 2,
|
||||
reload_cost: Some(2),
|
||||
..Default::default()
|
||||
};
|
||||
let known_data = &[
|
||||
(
|
||||
BestDamageScenarios::from_action_constraints_it(
|
||||
&eq,
|
||||
Actions(2),
|
||||
Attacks(1),
|
||||
Dices(3),
|
||||
Precision(10),
|
||||
),
|
||||
12.,
|
||||
),
|
||||
(
|
||||
BestDamageScenarios::from_action_constraints_it(
|
||||
&eq,
|
||||
Actions(2),
|
||||
Attacks(2),
|
||||
Dices(3),
|
||||
Precision(10),
|
||||
),
|
||||
22.,
|
||||
),
|
||||
(
|
||||
BestDamageScenarios::from_action_constraints_it(
|
||||
&eq,
|
||||
Actions(3),
|
||||
Attacks(3),
|
||||
Dices(3),
|
||||
Precision(10),
|
||||
),
|
||||
30.,
|
||||
),
|
||||
(
|
||||
BestDamageScenarios::from_action_constraints_it(
|
||||
&eq,
|
||||
Actions(3),
|
||||
Attacks(3),
|
||||
Dices(6),
|
||||
Precision(10),
|
||||
),
|
||||
36.,
|
||||
),
|
||||
(
|
||||
BestDamageScenarios::from_action_constraints_it(
|
||||
&eq,
|
||||
Actions(3),
|
||||
Attacks(3),
|
||||
Dices(6),
|
||||
Precision(10),
|
||||
),
|
||||
36.,
|
||||
),
|
||||
(
|
||||
BestDamageScenarios::from_action_constraints_it(
|
||||
&eq2,
|
||||
Actions(1),
|
||||
Attacks(1),
|
||||
Dices(3),
|
||||
Precision(10),
|
||||
),
|
||||
0.,
|
||||
),
|
||||
(
|
||||
BestDamageScenarios::from_action_constraints_it(
|
||||
&eq2,
|
||||
Actions(2),
|
||||
Attacks(1),
|
||||
Dices(3),
|
||||
Precision(10),
|
||||
),
|
||||
12.,
|
||||
),
|
||||
(
|
||||
BestDamageScenarios::from_action_constraints_it(
|
||||
&eq2,
|
||||
Actions(4),
|
||||
Attacks(2),
|
||||
Dices(3),
|
||||
Precision(10),
|
||||
),
|
||||
22.,
|
||||
),
|
||||
(
|
||||
BestDamageScenarios::from_action_constraints_it(
|
||||
&eq2,
|
||||
Actions(5),
|
||||
Attacks(3),
|
||||
Dices(6),
|
||||
Precision(10),
|
||||
),
|
||||
24.,
|
||||
),
|
||||
(
|
||||
BestDamageScenarios::from_action_constraints_it(
|
||||
&eq2,
|
||||
Actions(6),
|
||||
Attacks(3),
|
||||
Dices(6),
|
||||
Precision(10),
|
||||
),
|
||||
36.,
|
||||
),
|
||||
(
|
||||
BestDamageScenarios::from_action_constraints_it(
|
||||
&eq3,
|
||||
Actions(2),
|
||||
Attacks(1),
|
||||
Dices(3),
|
||||
Precision(10),
|
||||
),
|
||||
12.,
|
||||
),
|
||||
(
|
||||
BestDamageScenarios::from_action_constraints_it(
|
||||
&eq3,
|
||||
Actions(4),
|
||||
Attacks(2),
|
||||
Dices(3),
|
||||
Precision(10),
|
||||
),
|
||||
12.,
|
||||
),
|
||||
(
|
||||
BestDamageScenarios::from_action_constraints_it(
|
||||
&eq3,
|
||||
Actions(6),
|
||||
Attacks(2),
|
||||
Dices(3),
|
||||
Precision(10),
|
||||
),
|
||||
22.,
|
||||
),
|
||||
(
|
||||
BestDamageScenarios::from_action_constraints_it(
|
||||
&eq3,
|
||||
Actions(6),
|
||||
Attacks(3),
|
||||
Dices(6),
|
||||
Precision(10),
|
||||
),
|
||||
24.,
|
||||
),
|
||||
(
|
||||
BestDamageScenarios::from_action_constraints_it(
|
||||
&eq3,
|
||||
Actions(10),
|
||||
Attacks(3),
|
||||
Dices(6),
|
||||
Precision(10),
|
||||
),
|
||||
36.,
|
||||
),
|
||||
];
|
||||
known_data.iter().enumerate().for_each(|(i, (val, res))| {
|
||||
println!("[{i}] {:?} ~= {res}", val.clone().unwrap_or_default());
|
||||
assert_close!(val.clone().map_or(0., |v| v.damage_done), res);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_scenario_damage() {
|
||||
let eq1 = InnerEquipementStats {
|
||||
damage: 10,
|
||||
p_damage: 2,
|
||||
precision: 0,
|
||||
rmax: 2,
|
||||
action_cost: 2,
|
||||
..Default::default()
|
||||
};
|
||||
let eq2 = InnerEquipementStats {
|
||||
damage: 10,
|
||||
p_damage: 2,
|
||||
precision: 0,
|
||||
rmax: 2,
|
||||
speed: 10,
|
||||
action_cost: 2,
|
||||
..Default::default()
|
||||
};
|
||||
let eq3 = InnerEquipementStats {
|
||||
damage: 10,
|
||||
p_damage: 2,
|
||||
precision: 0,
|
||||
rmax: 2,
|
||||
range: 10,
|
||||
action_cost: 2,
|
||||
reload_cost: Some(2),
|
||||
..Default::default()
|
||||
};
|
||||
assert_close!(
|
||||
get_damage_with_simulation(&eq1, Actions(2), Attacks(1)),
|
||||
7.1999
|
||||
);
|
||||
assert_close!(
|
||||
get_damage_with_simulation(&eq2, Actions(2), Attacks(1)),
|
||||
8.3624
|
||||
);
|
||||
assert_close!(
|
||||
get_damage_with_simulation(&eq3, Actions(2), Attacks(1)),
|
||||
8.36249
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn test_basic_impl_damage_scenario() {
|
||||
let eq1 = InnerEquipementStats {
|
||||
damage: 10,
|
||||
p_damage: 2,
|
||||
precision: 0,
|
||||
rmax: 2,
|
||||
action_cost: 2,
|
||||
..Default::default()
|
||||
};
|
||||
let d1 = BestDamageScenarios::from_action_constraints_it(
|
||||
&eq1,
|
||||
Actions(2),
|
||||
Attacks(2),
|
||||
Dices(2),
|
||||
Precision(2),
|
||||
)
|
||||
.unwrap();
|
||||
let d2 = d1.clone() + d1;
|
||||
let _deref_damage = *d2;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,342 @@
|
|||
// Workspace: weaponry
|
||||
// File: weaponry/src/weaponry_structs/equipement_fields.rs
|
||||
//! The inner fields used by the super structs
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::fmt::Display;
|
||||
use std::ops::{Add, Deref, DerefMut};
|
||||
use strum::Display;
|
||||
|
||||
#[derive(Clone, Default, Debug, Deserialize, Serialize)]
|
||||
#[cfg_attr(test, derive(PartialEq))]
|
||||
/// The special category, a vec of string, for display purposes only
|
||||
pub struct SpecialField(Vec<String>);
|
||||
|
||||
impl SpecialField {
|
||||
/// Create a special field from a vector
|
||||
pub fn new(inner_data: Vec<String>) -> Self {
|
||||
Self(inner_data)
|
||||
}
|
||||
}
|
||||
impl Deref for SpecialField {
|
||||
type Target = Vec<String>;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl DerefMut for SpecialField {
|
||||
fn deref_mut(&mut self) -> &mut Self::Target {
|
||||
&mut self.0
|
||||
}
|
||||
}
|
||||
|
||||
// TODO[6]: This cross target specification existed for combines weapons,
|
||||
// : that do not really need any balancing and only rendering
|
||||
// : therefore migh need cleanup
|
||||
/// The kind of target this nature can apply to
|
||||
#[derive(Clone)]
|
||||
pub enum NatureTarget {
|
||||
/// Can apply to a weapon and is unique
|
||||
WeaponUnique,
|
||||
/// Can apply to a weapon and must be combined with another
|
||||
WeaponCombined,
|
||||
/// Can apply to an armor (all armor nature are unique)
|
||||
Armor,
|
||||
}
|
||||
|
||||
/// Enum of all different physical weapon damage types
|
||||
#[allow(clippy::missing_docs_in_private_items, missing_docs)]
|
||||
#[derive(Copy, Clone, Debug, Deserialize, Serialize, PartialEq, Eq, PartialOrd, Ord)]
|
||||
// #[cfg_attr(test, derive(PartialEq))]
|
||||
pub enum PhysicalDamageType {
|
||||
Blunt,
|
||||
Slash,
|
||||
Pierce,
|
||||
}
|
||||
|
||||
impl PhysicalDamageType {
|
||||
/// Get a exportable representation
|
||||
pub fn export(&self) -> String {
|
||||
match self {
|
||||
PhysicalDamageType::Blunt => "\\blunt".to_string(),
|
||||
PhysicalDamageType::Slash => "\\slash".to_string(),
|
||||
PhysicalDamageType::Pierce => "\\pierce".to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Weapon damage, combining the base weapon damage type and it's level
|
||||
///
|
||||
/// Signifying wether the damage is pure or \[secondary\] or \[\[tertiary\]\]
|
||||
#[allow(clippy::missing_docs_in_private_items, missing_docs)]
|
||||
#[derive(Clone, Debug, Display, Deserialize, Serialize, Eq, PartialEq, PartialOrd, Ord)]
|
||||
pub enum DamageMod {
|
||||
Primary(PhysicalDamageType),
|
||||
Secondary(PhysicalDamageType),
|
||||
Tertiary(PhysicalDamageType),
|
||||
}
|
||||
|
||||
impl DamageMod {
|
||||
/// Get the underlying value of the mod
|
||||
pub fn underlying(&self) -> PhysicalDamageType {
|
||||
match self {
|
||||
DamageMod::Primary(physical_damage_type) => *physical_damage_type,
|
||||
DamageMod::Secondary(physical_damage_type) => *physical_damage_type,
|
||||
DamageMod::Tertiary(physical_damage_type) => *physical_damage_type,
|
||||
}
|
||||
}
|
||||
/// Get a exportable representation
|
||||
pub fn export(&self) -> String {
|
||||
match self {
|
||||
DamageMod::Primary(phy) => phy.export(),
|
||||
DamageMod::Secondary(phy) => format!(r"[{}]", phy.export()),
|
||||
DamageMod::Tertiary(phy) => format!(r"[[{}]]", phy.export()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Does the damagemode contain this physical type
|
||||
pub fn contains(&self, value: &PhysicalDamageType) -> bool {
|
||||
self.underlying() == *value
|
||||
}
|
||||
|
||||
// /// Does the other mod have a better mod variant, only true if the underlying value is the same
|
||||
// pub fn upgrade(&self, value: &DamageMod) -> bool {
|
||||
// value > self
|
||||
// }
|
||||
}
|
||||
|
||||
/// Combined damage type, as a vector of all damage types
|
||||
///
|
||||
/// Meant to be serialised to tex and deserialized directly from the table
|
||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
||||
#[cfg_attr(test, derive(PartialEq))]
|
||||
// TODO: avoid pub make an impl ?
|
||||
pub struct DamageType(Vec<DamageMod>);
|
||||
|
||||
impl DamageType {
|
||||
/// Get the best modes from self, stripping redundant ones
|
||||
pub fn get_best_modes(&self) -> DamageType {
|
||||
let mut best: Vec<DamageMod> = Vec::new();
|
||||
for m in self.iter() {
|
||||
if let Some(_v) = best.iter().find(|v| v.contains(&m.underlying())) {
|
||||
} else {
|
||||
best.push(m.clone());
|
||||
}
|
||||
}
|
||||
Self(best)
|
||||
}
|
||||
}
|
||||
|
||||
impl Deref for DamageType {
|
||||
type Target = Vec<DamageMod>;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl DamageType {
|
||||
/// Create a new DamageType from a vector of *DamageMod*
|
||||
pub fn new(inner_data: Vec<DamageMod>) -> Self {
|
||||
Self(inner_data)
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for DamageType {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(
|
||||
f,
|
||||
"{}",
|
||||
self.0
|
||||
.iter()
|
||||
.fold(String::new(), |res, new| format!("{res}, {new}"))
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl Add for DamageType {
|
||||
type Output = Self;
|
||||
|
||||
fn add(self, rhs: Self) -> Self::Output {
|
||||
Self(self.0.iter().chain(rhs.0.iter()).cloned().collect())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
// use super::*;
|
||||
|
||||
#[ignore]
|
||||
#[test]
|
||||
fn test_fields_serialisation() {
|
||||
unimplemented!()
|
||||
}
|
||||
|
||||
#[ignore]
|
||||
#[test]
|
||||
fn test_fields_deserialisation() {
|
||||
unimplemented!()
|
||||
}
|
||||
}
|
||||
// // TODO[!]: Implement all the soundness below
|
||||
|
||||
// /// The final enum of all categories to be given to the character sheet
|
||||
// ///
|
||||
// /// This enum is only created at the end of the refining process with all the given information
|
||||
// /// Note that some weapons might not be created or might be too niche to be created by the recipes
|
||||
// /// however the full cross implementation should cover all weapons or reconsider the validity of said implementation
|
||||
// #[allow(dead_code, clippy::missing_docs_in_private_items)]
|
||||
// pub enum FinalWeaponCategory {
|
||||
// Hast(HastSpecialties),
|
||||
// Slash(SlashSpecialties),
|
||||
// Blunt(BluntSpecialties),
|
||||
// Collosal(ColossalSpeciaties),
|
||||
// Ranged(RangedSpecialties),
|
||||
// Throw(ThrowSpecialties),
|
||||
// }
|
||||
|
||||
// #[allow(dead_code, clippy::missing_docs_in_private_items)]
|
||||
// pub enum HastSpecialties {
|
||||
// Lance,
|
||||
// Staff,
|
||||
// }
|
||||
|
||||
// #[allow(dead_code, clippy::missing_docs_in_private_items)]
|
||||
// pub enum SlashSpecialties {
|
||||
// Sword,
|
||||
// #[deprecated]
|
||||
// Dagger,
|
||||
// Axe,
|
||||
// Claws,
|
||||
// }
|
||||
|
||||
// #[allow(dead_code, clippy::missing_docs_in_private_items)]
|
||||
// pub enum BluntSpecialties {
|
||||
// Hammer,
|
||||
// Improvised,
|
||||
// }
|
||||
|
||||
// #[allow(dead_code, clippy::missing_docs_in_private_items)]
|
||||
// pub enum ColossalSpeciaties {
|
||||
// Rhodarak,
|
||||
// Haroth,
|
||||
// Kahml,
|
||||
// Landscapper,
|
||||
// }
|
||||
|
||||
// #[allow(dead_code, clippy::missing_docs_in_private_items)]
|
||||
// pub enum RangedSpecialties {
|
||||
// Bow,
|
||||
// Crossbow,
|
||||
// Cannon,
|
||||
// }
|
||||
|
||||
// #[allow(dead_code, clippy::missing_docs_in_private_items)]
|
||||
// pub enum ThrowSpecialties {
|
||||
// Light,
|
||||
// Lances,
|
||||
// Improvised,
|
||||
// }
|
||||
|
||||
// TODO[4]: Have a final weapon category tied to the speciality, if any appliable to the character
|
||||
// : Since this is not needed for balencing, this will be left alone for a while
|
||||
// impl FinalWeaponCategory{
|
||||
// fn from_category_and_size(macro_category: &WeaponBaseShape, size: &WeaponBaseSize) -> Self {
|
||||
// match (macro_category, size) {
|
||||
// (WeaponBaseShape::Axe, WeaponBaseSize::SuperHeavy) => Self::Colossal(..),
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
// TODO[!]: This is the real initial category for the shapes, as only shapes should be described by shapes
|
||||
// TODO[!]: Shapes should also have a generic category of course (weapons/armor/shield) to help the filter to apply to it
|
||||
/// The list of initial weapon meta categories
|
||||
// TODO[!]: This enum should only include Weapons, Shields, Armors and no <BaseShape>
|
||||
#[allow(clippy::missing_docs_in_private_items, missing_docs)]
|
||||
#[derive(Clone, Debug, Display, Deserialize, Serialize, strum::EnumString)]
|
||||
pub enum EquipementSerializedCategory {
|
||||
Staves,
|
||||
Blunt,
|
||||
Slash,
|
||||
Ranged,
|
||||
Exotic,
|
||||
/// Armor generic category, will be converted into EquipementSection
|
||||
Armors,
|
||||
/// Shield generic category, will be converted into EquipementSection
|
||||
Shields,
|
||||
/// A custom None category, used to forbid a part to be cast upon or from
|
||||
None,
|
||||
/// Light size, will be converted to a WeaponBaseSize
|
||||
Light,
|
||||
/// Medium size, will be converted to a WeaponBaseSize
|
||||
Medium,
|
||||
/// Heavy size, will be converted to a WeaponBaseSize
|
||||
Heavy,
|
||||
/// SuperHeavy size, will be converted to a WeaponBaseSize
|
||||
SuperHeavy,
|
||||
}
|
||||
|
||||
// TODO[!] : This is the corrected real initial shape
|
||||
// : This should replace the used MacroCategory
|
||||
/// The Base Shape of the weapon, used to infer the final category of the weapon
|
||||
#[allow(clippy::missing_docs_in_private_items, missing_docs)]
|
||||
#[derive(
|
||||
Copy, Clone, Debug, Display, Deserialize, Serialize, strum::EnumString, Default, PartialEq,
|
||||
)]
|
||||
pub enum WeaponBaseShape {
|
||||
Staves,
|
||||
Blunt,
|
||||
Slash,
|
||||
Ranged,
|
||||
Armors,
|
||||
Shields,
|
||||
Exotic,
|
||||
#[default]
|
||||
None,
|
||||
}
|
||||
|
||||
// TODO[!]: While maybe not directly filling a field these categories should be inferred by the BaseShape for comparison
|
||||
// [!]: However using a new column for this Section will greatly help in the Serde soundness and avoidance on over-reliance of implicit conversions
|
||||
/// Specifies the exact nature of the weapon, used for generic filter mainly
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
|
||||
#[allow(dead_code, clippy::missing_docs_in_private_items, missing_docs)]
|
||||
pub enum EquipementTargets {
|
||||
Weapons,
|
||||
Armors,
|
||||
Shields,
|
||||
Ranged,
|
||||
}
|
||||
|
||||
impl EquipementTargets {
|
||||
/// Assert wether a target can be applied to an original shape
|
||||
pub fn can_apply_onto(&self, lsh: &WeaponBaseShape) -> bool {
|
||||
match (self, lsh) {
|
||||
(EquipementTargets::Weapons, WeaponBaseShape::Staves) => true,
|
||||
(EquipementTargets::Weapons, WeaponBaseShape::Blunt) => true,
|
||||
(EquipementTargets::Weapons, WeaponBaseShape::Slash) => true,
|
||||
(EquipementTargets::Weapons, WeaponBaseShape::Ranged) => true,
|
||||
(EquipementTargets::Weapons, WeaponBaseShape::Exotic) => true,
|
||||
// (EquipementTargets::Weapons, WeaponBaseShape::Shields) => true,
|
||||
(EquipementTargets::Armors, WeaponBaseShape::Armors) => true,
|
||||
(EquipementTargets::Shields, WeaponBaseShape::Shields) => true,
|
||||
(EquipementTargets::Ranged, WeaponBaseShape::Ranged) => true,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TODO[!] : This part is initialized by the natures subtable and might be better of being a new column in the database
|
||||
/// The Base Size of the weapon, used to infer the final category of the weapon
|
||||
#[allow(clippy::missing_docs_in_private_items, missing_docs)]
|
||||
#[derive(
|
||||
Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Display, Deserialize, Serialize, strum::EnumString,
|
||||
)]
|
||||
// #[cfg_attr(test, derive(PartialEq))]
|
||||
pub enum WeaponBaseSize {
|
||||
Light,
|
||||
Medium,
|
||||
Heavy,
|
||||
SuperHeavy,
|
||||
}
|
||||
|
|
@ -0,0 +1,437 @@
|
|||
// 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]);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,155 @@
|
|||
// Workspace: weaponry
|
||||
// File: weaponry/src/weaponry_structs/equipement_impl_database.rs
|
||||
//! All database specific implementations
|
||||
|
||||
use super::EquipementSerializedCategory;
|
||||
use super::equipement_fields::{WeaponBaseShape, WeaponBaseSize};
|
||||
use super::equipement_structs::{DatabaseEquipementStats, InnerEquipementStats};
|
||||
use crate::error::FatalEquipementError;
|
||||
use crate::interfaces::{FixedRecipe, RecipeDatabase};
|
||||
use rusqlite::Connection;
|
||||
|
||||
/// Struct for database connection.
|
||||
#[derive(Debug)]
|
||||
pub struct EquipementDatabase {
|
||||
/// Connection parameter for rusqlite
|
||||
pub conn: rusqlite::Connection,
|
||||
}
|
||||
|
||||
impl RecipeDatabase for EquipementDatabase {
|
||||
type DeserialisationType = DatabaseEquipementStats;
|
||||
type InnerType = InnerEquipementStats;
|
||||
|
||||
fn new(filename: &str) -> Result<Self, FatalEquipementError> {
|
||||
Ok(EquipementDatabase {
|
||||
conn: Connection::open(filename)?,
|
||||
})
|
||||
}
|
||||
|
||||
fn get_connection(&self) -> &Connection {
|
||||
&self.conn
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "dev-analysis", coverage(off))] // INCORRECT: Error with line report
|
||||
fn serialize_into_intermediate<T>(
|
||||
&self,
|
||||
table: &str,
|
||||
filter: Option<&str>,
|
||||
) -> Result<impl Iterator<Item = Result<T, FatalEquipementError>> + '_, FatalEquipementError>
|
||||
where
|
||||
T: From<Self::InnerType>,
|
||||
{
|
||||
// Start with Self::DatabaseType
|
||||
Ok(self
|
||||
.serialize_vec_from_table::<Self::DeserialisationType>(table, filter)?
|
||||
.into_iter()
|
||||
.map(|db_element| {
|
||||
Self::InnerType::try_from(db_element).map(|inner_eq| T::from(inner_eq))
|
||||
}))
|
||||
}
|
||||
}
|
||||
#[allow(missing_docs)]
|
||||
pub struct EquipementFixedRecipe {
|
||||
pub conn: rusqlite::Connection,
|
||||
}
|
||||
|
||||
#[allow(missing_docs)]
|
||||
pub struct MockRecipe {}
|
||||
|
||||
// TODO[1] : Add fixed recipes
|
||||
impl FixedRecipe for EquipementFixedRecipe {
|
||||
type KeyList = MockRecipe;
|
||||
|
||||
fn get_elements_from_table(
|
||||
&self,
|
||||
table: &str,
|
||||
) -> Result<Vec<Self::KeyList>, FatalEquipementError> {
|
||||
let _ = table;
|
||||
todo!()
|
||||
}
|
||||
}
|
||||
|
||||
// TODO[3]: Migrate ASAP from this manual implementation
|
||||
/// Macro converting a value using serde and mapping an in house error
|
||||
macro_rules! from_serde {
|
||||
($value: expr) => {
|
||||
serde_json::from_str(&$value).map_err(|error| FatalEquipementError::SerdeJSONAt {
|
||||
line: line!().to_string(),
|
||||
file: file!().to_string(),
|
||||
parsed_value: $value.to_string(),
|
||||
error,
|
||||
})
|
||||
};
|
||||
}
|
||||
|
||||
// #[allow(clippy::useless_conversion)]
|
||||
impl TryFrom<DatabaseEquipementStats> for InnerEquipementStats {
|
||||
type Error = FatalEquipementError;
|
||||
|
||||
fn try_from(value: DatabaseEquipementStats) -> Result<Self, Self::Error> {
|
||||
let (category_base, category_size): SubCategories =
|
||||
get_sub_categories_from_serde(&value.category)?;
|
||||
Ok(Self {
|
||||
id: vec![value.id], // Special case where manual is better than serde
|
||||
name: vec![value.name],
|
||||
adjective: value.adjective,
|
||||
rarity: value.rarity, // Generic case, into(), serde or cast are equivalent
|
||||
cost: value.cost,
|
||||
difficulty: value.difficulty,
|
||||
// tier: value.tier,
|
||||
tier: 0,
|
||||
damage: value.damage,
|
||||
p_damage: value.p_damage,
|
||||
precision: value.precision,
|
||||
rmax: value.rmax,
|
||||
armor_break: value.armor_break,
|
||||
armor_pierce: value.armor_pierce,
|
||||
antimaterial: value.antimaterial,
|
||||
damage_type: from_serde!(&value.damage_type)?, // Serde and derive are godsent
|
||||
protection: value.protection,
|
||||
integrity: value.integrity,
|
||||
torque_two_handed: from_serde!(&value.torque_two_handed)?,
|
||||
torque_one_handed: from_serde!(&value.torque_one_handed)?,
|
||||
dodge: value.dodge,
|
||||
parry: value.parry,
|
||||
speed: value.speed,
|
||||
stealth: value.stealth,
|
||||
// macro_category: from_serde!(&value.category)?,
|
||||
// target: from_serde!(&value.target)?,
|
||||
special: from_serde!(&value.special)?,
|
||||
action_cost: value.action_cost,
|
||||
reload_cost: from_serde!(&value.reload_cost)?,
|
||||
range: value.range as i16,
|
||||
agility_bonus: value.agility_bonus,
|
||||
category_base,
|
||||
category_size,
|
||||
target_category: from_serde!(value.target)?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// A type englobing the three subcategores
|
||||
type SubCategories = (Option<WeaponBaseShape>, Option<WeaponBaseSize>);
|
||||
|
||||
/// Infer all subcategories from a deserialized DatabaseCategory
|
||||
#[cfg_attr(feature = "dev-analysis", coverage(off))] // A test would literally be a copy paste of this match
|
||||
fn get_sub_categories_from_serde(category: &str) -> Result<SubCategories, FatalEquipementError> {
|
||||
Ok(if let Some(category) = from_serde!(category)? {
|
||||
match category {
|
||||
EquipementSerializedCategory::Staves => (Some(WeaponBaseShape::Staves), None),
|
||||
EquipementSerializedCategory::Blunt => (Some(WeaponBaseShape::Blunt), None),
|
||||
EquipementSerializedCategory::Slash => (Some(WeaponBaseShape::Slash), None),
|
||||
EquipementSerializedCategory::Ranged => (Some(WeaponBaseShape::Ranged), None),
|
||||
EquipementSerializedCategory::Exotic => (Some(WeaponBaseShape::Exotic), None),
|
||||
EquipementSerializedCategory::Armors => (Some(WeaponBaseShape::Armors), None),
|
||||
EquipementSerializedCategory::Shields => (Some(WeaponBaseShape::Shields), None),
|
||||
EquipementSerializedCategory::None => (Some(WeaponBaseShape::None), None),
|
||||
EquipementSerializedCategory::Light => (None, Some(WeaponBaseSize::Light)),
|
||||
EquipementSerializedCategory::Medium => (None, Some(WeaponBaseSize::Medium)),
|
||||
EquipementSerializedCategory::Heavy => (None, Some(WeaponBaseSize::Heavy)),
|
||||
EquipementSerializedCategory::SuperHeavy => (None, Some(WeaponBaseSize::SuperHeavy)),
|
||||
}
|
||||
} else {
|
||||
(None, None)
|
||||
})
|
||||
}
|
||||
|
|
@ -0,0 +1,80 @@
|
|||
// Workspace: weaponry
|
||||
// File: weaponry/src/weaponry_structs/equipement_impl_io.rs
|
||||
//! All implementation IO specific (mainly export and serde)
|
||||
|
||||
use cli_parser::Config;
|
||||
use handlebars::Handlebars;
|
||||
|
||||
use super::equipement_advanced_repr::RefinedEquipementList;
|
||||
use crate::{
|
||||
error::FatalEquipementError,
|
||||
interfaces::{ToCSV, ToTex},
|
||||
weaponry_structs::equipement_advanced_repr::ExportableEquipement,
|
||||
};
|
||||
use std::path::Path;
|
||||
|
||||
impl ToCSV for RefinedEquipementList {
|
||||
fn write_csv(&self, path: &Path) -> csv::Result<()> {
|
||||
let mut wtr = csv::Writer::from_path(path)?; // wtr.serialize
|
||||
for record in self.iter() {
|
||||
wtr.serialize(record)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl ToTex for RefinedEquipementList {
|
||||
fn to_tex(&self, config: &Config) -> Result<String, FatalEquipementError> {
|
||||
let mut template = Handlebars::new();
|
||||
template.register_template_string("weapons", &config.weapons.template)?;
|
||||
let mut data = self
|
||||
.iter()
|
||||
.map(std::convert::Into::<ExportableEquipement>::into)
|
||||
.collect::<Vec<ExportableEquipement>>();
|
||||
|
||||
for i in 0..data.len() - 1 {
|
||||
if data[i].category != data[i + 1].category
|
||||
// && data[i + 1].category == Some(super::WeaponBaseShape::Shields)
|
||||
{
|
||||
data[i].needs_break = true;
|
||||
}
|
||||
}
|
||||
let r = template.render("weapons", &data)?;
|
||||
// println!("{}", r);
|
||||
Ok(r)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
// use super::*;
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use crate::{
|
||||
interfaces::ToCSV,
|
||||
weaponry_structs::{
|
||||
equipement_advanced_repr::{AdvancedStats, RefinedEquipementList},
|
||||
equipement_structs::InnerEquipementStats,
|
||||
},
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn test_structs_serialisation() {
|
||||
let adv = AdvancedStats::from(&InnerEquipementStats::default());
|
||||
// let mut wtr = csv::Writer::from_path("bob.csv").unwrap(); // wtr.serialize
|
||||
let mut wtr = csv::Writer::from_writer(Vec::new());
|
||||
wtr.serialize(adv).unwrap();
|
||||
wtr.flush().unwrap();
|
||||
|
||||
RefinedEquipementList::default()
|
||||
.write_csv(Path::new("/dev/null"))
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[ignore]
|
||||
#[test]
|
||||
fn test_structs_deserialisation() {
|
||||
unimplemented!()
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,187 @@
|
|||
// Workspace: weaponry
|
||||
// File: weaponry/src/weaponry_structs/equipement_impl_logic.rs
|
||||
//! Implementation of the logic traits, used for equipement generation
|
||||
|
||||
use crate::interfaces::{Combinable, RecipeCollection};
|
||||
|
||||
use super::{Equipement, InitialEquipementList, equipement_structs::InnerEquipementStats};
|
||||
|
||||
impl Combinable for Equipement {
|
||||
type Inner = InnerEquipementStats;
|
||||
|
||||
fn combinable_part(&self) -> &Self::Inner {
|
||||
&self.stats
|
||||
}
|
||||
|
||||
fn add_ref_to_self<T>(&self, rhs: &T) -> Self
|
||||
where
|
||||
T: Combinable<Inner = Self::Inner>,
|
||||
{
|
||||
Self {
|
||||
stats: self.combinable_part() + rhs.combinable_part(),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn backward_filter<T>(&self, lhs: &T) -> bool
|
||||
where
|
||||
T: Combinable<Inner = Self::Inner>,
|
||||
{
|
||||
self.filter_function.0(self.combinable_part(), lhs.combinable_part())
|
||||
}
|
||||
}
|
||||
|
||||
impl RecipeCollection for InitialEquipementList {
|
||||
type Recipes = Equipement;
|
||||
|
||||
// Should likely be internal
|
||||
fn from_vectored(list: Vec<Self::Recipes>) -> Self {
|
||||
Self { inner: list }
|
||||
}
|
||||
|
||||
fn ref_inner(&self) -> &Vec<Self::Recipes> {
|
||||
&self.inner
|
||||
}
|
||||
|
||||
fn assign_inner(&mut self, inner: Vec<Self::Recipes>) {
|
||||
self.inner = inner;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use crate::{
|
||||
interfaces::RecipeCollection,
|
||||
weaponry_structs::{
|
||||
DamageMod, DamageType, Equipement, InitialEquipementList, SpecialField,
|
||||
equipement_fields::{PhysicalDamageType, WeaponBaseShape},
|
||||
equipement_structs::InnerEquipementStats,
|
||||
},
|
||||
};
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn test_blanket_struct_generation() {
|
||||
let mut f = InitialEquipementList::from_vectored(vec![
|
||||
Equipement::newish(&["a"], 1),
|
||||
Equipement::newish(&["b"], 2),
|
||||
]);
|
||||
let g = InitialEquipementList::from_vectored(vec![
|
||||
Equipement::newish(&["c"], 4),
|
||||
Equipement::newish(&["d"], 8),
|
||||
]);
|
||||
|
||||
assert_eq!(
|
||||
f.ref_inner(),
|
||||
&vec![Equipement::newish(&["a"], 1), Equipement::newish(&["b"], 2)]
|
||||
);
|
||||
|
||||
f.combine_all(&g);
|
||||
assert_eq!(
|
||||
f,
|
||||
InitialEquipementList::from_vectored(vec![
|
||||
Equipement::newish(&["a", "c"], 5),
|
||||
Equipement::newish(&["a", "d"], 9),
|
||||
Equipement::newish(&["b", "c"], 6),
|
||||
Equipement::newish(&["b", "d"], 10)
|
||||
])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_base_operation() {
|
||||
let i1 = InnerEquipementStats {
|
||||
rarity: 1,
|
||||
integrity: 2,
|
||||
range: 3,
|
||||
agility_bonus: 4.,
|
||||
category_base: Some(WeaponBaseShape::Staves),
|
||||
special: SpecialField::new(vec!["zero".into()]),
|
||||
damage_type: Some(DamageType::new(vec![DamageMod::Secondary(
|
||||
PhysicalDamageType::Slash,
|
||||
)])),
|
||||
..Default::default()
|
||||
};
|
||||
let i2 = InnerEquipementStats {
|
||||
integrity: 3,
|
||||
agility_bonus: 5.,
|
||||
damage: 10,
|
||||
damage_type: Some(DamageType::new(vec![DamageMod::Primary(
|
||||
PhysicalDamageType::Blunt,
|
||||
)])),
|
||||
special: SpecialField::new(vec!["one".into(), "two".into()]),
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(
|
||||
&i1 + &i2,
|
||||
InnerEquipementStats {
|
||||
rarity: 1,
|
||||
integrity: 5,
|
||||
agility_bonus: 9.,
|
||||
damage: 10,
|
||||
range: 3,
|
||||
category_base: Some(WeaponBaseShape::Staves),
|
||||
special: SpecialField::new(vec!["zero".into(), "one".into(), "two".into()]),
|
||||
damage_type: Some(DamageType::new(vec![
|
||||
DamageMod::Secondary(PhysicalDamageType::Slash,),
|
||||
DamageMod::Primary(PhysicalDamageType::Blunt,),
|
||||
])),
|
||||
..Default::default()
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
&InnerEquipementStats {
|
||||
damage_type: Some(DamageType::new(vec![
|
||||
DamageMod::Secondary(PhysicalDamageType::Slash,),
|
||||
DamageMod::Primary(PhysicalDamageType::Blunt,),
|
||||
])),
|
||||
..Default::default()
|
||||
} + &InnerEquipementStats::default(),
|
||||
InnerEquipementStats {
|
||||
damage_type: Some(DamageType::new(vec![
|
||||
DamageMod::Secondary(PhysicalDamageType::Slash,),
|
||||
DamageMod::Primary(PhysicalDamageType::Blunt,),
|
||||
])),
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
assert_eq!(
|
||||
&InnerEquipementStats::default()
|
||||
+ &InnerEquipementStats {
|
||||
damage_type: Some(DamageType::new(vec![
|
||||
DamageMod::Secondary(PhysicalDamageType::Slash,),
|
||||
DamageMod::Primary(PhysicalDamageType::Blunt,),
|
||||
])),
|
||||
..Default::default()
|
||||
},
|
||||
InnerEquipementStats {
|
||||
damage_type: Some(DamageType::new(vec![
|
||||
DamageMod::Secondary(PhysicalDamageType::Slash,),
|
||||
DamageMod::Primary(PhysicalDamageType::Blunt,),
|
||||
])),
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
#[ignore]
|
||||
#[test]
|
||||
fn test_generator_function() {}
|
||||
|
||||
#[ignore]
|
||||
#[test]
|
||||
fn test_basic_logic() {}
|
||||
|
||||
impl Equipement {
|
||||
fn newish(name: &[&str], i: i8) -> Self {
|
||||
Equipement {
|
||||
stats: InnerEquipementStats {
|
||||
name: name.iter().map(|s| s.to_string()).collect(),
|
||||
rarity: i,
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,187 @@
|
|||
// Workspace: weaponry
|
||||
// File: weaponry/src/weaponry_structs/equipement_scenario.rs
|
||||
//! Implementations of a full scenario,
|
||||
//!
|
||||
//! These implementation must take care of everything from database retrieval to view exporting,
|
||||
//! however all they mostly do is glue together all the parts designed in the interface,
|
||||
//! and therefore mostly serves as a TO-DO list
|
||||
//!
|
||||
|
||||
use crate::{
|
||||
error::FatalEquipementError,
|
||||
interfaces::{RecipeCollection, RecipeDatabase, Scenario},
|
||||
weaponry_structs::{
|
||||
InitialEquipementList, RefinedEquipementList,
|
||||
equipement_impl_database::EquipementDatabase,
|
||||
equipement_structs::{EqFinishing, EqMaterial, EqNature, EqShape, InnerEquipementStats},
|
||||
},
|
||||
};
|
||||
|
||||
/// Base Equipement Scenario config
|
||||
pub struct ConfigEquipementScenario {
|
||||
/// Table Name
|
||||
pub table_name: String,
|
||||
/// Database path
|
||||
pub db_path: String,
|
||||
// TODO[2]: Add something smart here to take care of the selection process
|
||||
/// Wether the shapes are selected
|
||||
pub shape: Option<()>,
|
||||
/// Wether the materials are selected, and how many iteration there are
|
||||
pub materials: Option<usize>,
|
||||
/// Wether the natures are selected
|
||||
pub nature: Option<()>,
|
||||
/// Wether the finishing touches are selected
|
||||
pub finishing: Option<()>,
|
||||
}
|
||||
|
||||
/// A simple cross recipe scenario
|
||||
#[allow(clippy::missing_docs_in_private_items)]
|
||||
pub struct CrossRecipeScenario {
|
||||
database: EquipementDatabase,
|
||||
config: ConfigEquipementScenario,
|
||||
}
|
||||
|
||||
/// All recipes
|
||||
#[allow(clippy::missing_docs_in_private_items, dead_code)]
|
||||
pub struct RecipesScenario {
|
||||
database: EquipementDatabase,
|
||||
config: ConfigEquipementScenario,
|
||||
}
|
||||
|
||||
/// A scenario exporting all individual elements
|
||||
#[allow(clippy::missing_docs_in_private_items, dead_code)]
|
||||
pub struct IndividualElementsScenario {
|
||||
database: EquipementDatabase,
|
||||
config: ConfigEquipementScenario,
|
||||
}
|
||||
|
||||
impl CrossRecipeScenario {
|
||||
/// Generate all the operations to be processed with the current config
|
||||
// TODO[!]: Consider adding to interface
|
||||
fn generate_selected_operation(
|
||||
&self,
|
||||
) -> Result<Vec<InitialEquipementList>, FatalEquipementError> {
|
||||
let mut operations = Vec::with_capacity(8);
|
||||
if self.config.shape.is_some() {
|
||||
operations.push(self.deserde_into_processed_representation::<EqShape>(Some(
|
||||
"META_CATEGORY LIKE 'Shape'",
|
||||
))?);
|
||||
}
|
||||
if let Some(qt) = self.config.materials {
|
||||
for _ in 0..qt {
|
||||
operations.push(
|
||||
self.deserde_into_processed_representation::<EqMaterial>(Some(
|
||||
"META_CATEGORY LIKE 'Materials'",
|
||||
))?,
|
||||
);
|
||||
}
|
||||
}
|
||||
if self.config.nature.is_some() {
|
||||
operations.push(self.deserde_into_processed_representation::<EqNature>(Some(
|
||||
"META_CATEGORY LIKE 'Nature'",
|
||||
))?);
|
||||
}
|
||||
if self.config.finishing.is_some() {
|
||||
operations.push(
|
||||
self.deserde_into_processed_representation::<EqFinishing>(Some(
|
||||
"META_CATEGORY LIKE 'Finishing'",
|
||||
))?,
|
||||
);
|
||||
}
|
||||
if operations.is_empty() {
|
||||
return Err(FatalEquipementError::CLISelection(
|
||||
"No step was selected for generation, please select at least one step".into(),
|
||||
));
|
||||
};
|
||||
Ok(operations)
|
||||
}
|
||||
}
|
||||
|
||||
impl Scenario for CrossRecipeScenario {
|
||||
type DatabaseType = EquipementDatabase;
|
||||
type FinalListType = RefinedEquipementList;
|
||||
type Config = ConfigEquipementScenario;
|
||||
type InitialEquipementType = InnerEquipementStats;
|
||||
type InitialEquipementListType = InitialEquipementList;
|
||||
// type Recipe = Equipement;
|
||||
|
||||
fn new_with_config(config: Self::Config) -> Result<Self, FatalEquipementError>
|
||||
where
|
||||
Self: Sized,
|
||||
{
|
||||
Ok(Self {
|
||||
database: Self::DatabaseType::new(&config.db_path)?,
|
||||
config,
|
||||
})
|
||||
}
|
||||
|
||||
fn generate_refined_recipes(&self) -> Result<Self::FinalListType, FatalEquipementError> {
|
||||
let operations = self.generate_selected_operation()?;
|
||||
|
||||
let mut opertation_it = operations.into_iter();
|
||||
let mut refined_list = opertation_it.next().unwrap();
|
||||
|
||||
opertation_it.for_each(|operation| refined_list.combine_all(&operation));
|
||||
|
||||
Ok(refined_list.into())
|
||||
}
|
||||
|
||||
// type InitialElementList;
|
||||
|
||||
// type InitialDatabaseStruct;
|
||||
|
||||
fn get_tablename(&self) -> &str {
|
||||
&self.config.table_name
|
||||
}
|
||||
|
||||
fn get_database(&self) -> &Self::DatabaseType {
|
||||
&self.database
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use crate::{
|
||||
interfaces::{RecipeDatabase, Scenario},
|
||||
weaponry_structs::{
|
||||
equipement_impl_database::EquipementDatabase,
|
||||
equipement_structs::{DatabaseEquipementStats, EqFinishing},
|
||||
},
|
||||
};
|
||||
|
||||
use super::{ConfigEquipementScenario, CrossRecipeScenario};
|
||||
|
||||
#[test]
|
||||
fn test_scenario() {}
|
||||
#[test]
|
||||
fn test_deserde_into() {
|
||||
let b = CrossRecipeScenario {
|
||||
database: EquipementDatabase {
|
||||
conn: rusqlite::Connection::open_in_memory().unwrap(),
|
||||
},
|
||||
config: ConfigEquipementScenario {
|
||||
table_name: "Finishing".to_owned(),
|
||||
db_path: "None".to_owned(),
|
||||
shape: None,
|
||||
materials: None,
|
||||
nature: None,
|
||||
finishing: None,
|
||||
},
|
||||
};
|
||||
|
||||
b.get_database()
|
||||
.initialize_empty_table::<DatabaseEquipementStats>("Finishing")
|
||||
.unwrap();
|
||||
b.get_database()
|
||||
.insert_row::<DatabaseEquipementStats>(
|
||||
"Finishing",
|
||||
DatabaseEquipementStats::random_new(),
|
||||
)
|
||||
.unwrap();
|
||||
<CrossRecipeScenario as Scenario>::get_database(&b);
|
||||
let r = b
|
||||
.deserde_into_processed_representation::<EqFinishing>(None)
|
||||
.unwrap();
|
||||
assert_eq!(r.inner.len(), 1);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,321 @@
|
|||
// Workspace: weaponry
|
||||
// File: weaponry/src/weaponry_structs/equipement_structs.rs
|
||||
//! Base equipement structures
|
||||
|
||||
use std::rc::Rc;
|
||||
|
||||
use crate::interfaces::{FilterFunction, FilterFunctionType};
|
||||
use more_fields::FieldsAsSlice;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use super::{
|
||||
DamageType, SpecialField,
|
||||
equipement_fields::{
|
||||
EquipementSerializedCategory, EquipementTargets, WeaponBaseShape, WeaponBaseSize,
|
||||
},
|
||||
};
|
||||
|
||||
/// The final equipement list
|
||||
///
|
||||
/// This list is initialized with the base part and updated by succesive combinaisons
|
||||
#[derive(Clone, Debug)]
|
||||
#[cfg_attr(test, derive(PartialEq))]
|
||||
pub struct InitialEquipementList {
|
||||
/// Inner List of final equipements
|
||||
pub(super) inner: Vec<Equipement>,
|
||||
}
|
||||
|
||||
/// The final equipement, obtained by combining all parts
|
||||
#[derive(Clone, Debug)]
|
||||
#[cfg_attr(test, derive(PartialEq))]
|
||||
pub struct Equipement {
|
||||
/// The inner stats used by the equipement
|
||||
pub(super) stats: InnerEquipementStats,
|
||||
/// The filter, used to determine if adding is warranted
|
||||
pub(super) filter_function: FilterFunction<InnerEquipementStats>,
|
||||
}
|
||||
|
||||
impl Default for Equipement {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
filter_function: FilterFunction::new(filter_id_unique()),
|
||||
stats: InnerEquipementStats::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The default filter to use, usefull to implement a new filter function that also uses the default filter
|
||||
pub(crate) fn filter_id_unique()
|
||||
-> &'static impl Fn(&InnerEquipementStats, &InnerEquipementStats) -> bool {
|
||||
&|self_, lhs| lhs.id.iter().all(|a| *a != self_.id[0])
|
||||
}
|
||||
|
||||
/// Create a new filter function mandating the object be of the right category
|
||||
// TODO[5]: Testing this method should be a priority for refactoring
|
||||
pub(crate) fn filter_id_unique_and_right_category()
|
||||
-> &'static impl Fn(&InnerEquipementStats, &InnerEquipementStats) -> bool {
|
||||
&|sel, lhs| {
|
||||
lhs.id.iter().all(|a| *a != sel.id[0])
|
||||
& match (&sel.target_category, &lhs.category_base) {
|
||||
// There is a specific target and the part about to be added has a category
|
||||
(Some(a), Some(b)) => a.can_apply_onto(b),
|
||||
// TODO: Unsound to have a generic nature, this should be caught at serialisation
|
||||
// There is no target and the part about to be added is generic
|
||||
(None, _) => false, //panic!("The part about to be added cannot be generic"),
|
||||
(Some(_), None) => false, //panic!("The part about to be added unto cannot be generic"),
|
||||
}
|
||||
}
|
||||
}
|
||||
impl<T> FilterFunction<T> {
|
||||
/// Generate and save a new filter,
|
||||
/// the use of a static reference allows for reuse of a generic filter
|
||||
pub fn new(filter: &'static FilterFunctionType<T>) -> Self {
|
||||
Self(Box::new(Rc::new(filter)))
|
||||
}
|
||||
}
|
||||
/// The inner statistics of the equipement, used across all parts and final weapon
|
||||
#[allow(clippy::missing_docs_in_private_items, missing_docs)]
|
||||
#[derive(Clone, Default, FieldsAsSlice, Debug)]
|
||||
#[cfg_attr(test, derive(PartialEq))]
|
||||
pub struct InnerEquipementStats {
|
||||
pub id: Vec<u8>,
|
||||
pub name: Vec<String>,
|
||||
pub adjective: Option<String>,
|
||||
pub(super) rarity: i8,
|
||||
pub(super) cost: i8,
|
||||
pub(super) difficulty: i8,
|
||||
pub(super) tier: i8,
|
||||
pub(super) damage: i8,
|
||||
pub(super) p_damage: i8,
|
||||
pub(super) precision: i8,
|
||||
pub(super) rmax: i8,
|
||||
pub(super) armor_break: i8,
|
||||
pub(super) armor_pierce: i8,
|
||||
pub(super) antimaterial: i8,
|
||||
pub(super) damage_type: Option<DamageType>,
|
||||
pub(super) protection: i8,
|
||||
pub(super) integrity: i8,
|
||||
pub(super) torque_two_handed: Option<i8>, // Might be option (single claw)
|
||||
pub(super) torque_one_handed: Option<i8>, // Should be option (bows)
|
||||
pub(super) dodge: f32, // I could also use a custom HalfValue
|
||||
pub(super) parry: i8,
|
||||
pub(super) speed: i8,
|
||||
pub(super) stealth: i8,
|
||||
/// The category as [WeaponBaseShape] representing what kind of equipement is used
|
||||
///
|
||||
/// The categories are: Staves, Blunt, Slash, Ranged, Armors, Shields, Exotic, None,
|
||||
pub category_base: Option<WeaponBaseShape>,
|
||||
/// The category size as WeaponBaseSize
|
||||
///
|
||||
/// Categories are : (Light, Medium, Heavy and SuperHeavy)
|
||||
pub category_size: Option<WeaponBaseSize>,
|
||||
/// The section of an equipement (Weapon, Shield, Armor)
|
||||
/// The Section the target applies to
|
||||
pub target_category: Option<EquipementTargets>,
|
||||
pub(super) special: SpecialField,
|
||||
pub(super) action_cost: i8,
|
||||
pub(super) reload_cost: Option<i8>, // Shouldn't it be Option ?
|
||||
pub(super) range: i16, // Shoudln't it be Option ?
|
||||
pub(super) agility_bonus: f32, // Also convert this one to HalfValue
|
||||
}
|
||||
|
||||
// TODO: This implementation of default is painfull
|
||||
// : Have either an auto-macro implementation or a manual one
|
||||
// : This implementation is Quasi-redondant
|
||||
// : Have a way to limit code duplication
|
||||
#[allow(clippy::missing_docs_in_private_items, missing_docs)]
|
||||
#[derive(Clone, FieldsAsSlice, Debug, Deserialize, Serialize)]
|
||||
#[cfg_attr(test, derive(PartialEq))]
|
||||
pub struct DatabaseEquipementStats {
|
||||
#[INTEGER]
|
||||
pub id: u8,
|
||||
pub meta_category: String,
|
||||
pub name: String,
|
||||
#[TEXT]
|
||||
pub adjective: Option<String>,
|
||||
#[INTEGER]
|
||||
pub rarity: i8,
|
||||
#[INTEGER]
|
||||
pub cost: i8,
|
||||
#[INTEGER]
|
||||
pub difficulty: i8,
|
||||
#[INTEGER]
|
||||
pub tier: i8,
|
||||
#[INTEGER]
|
||||
pub damage: i8,
|
||||
#[INTEGER]
|
||||
pub p_damage: i8,
|
||||
#[INTEGER]
|
||||
pub precision: i8,
|
||||
#[INTEGER]
|
||||
pub rmax: i8,
|
||||
#[INTEGER]
|
||||
pub armor_break: i8,
|
||||
#[INTEGER]
|
||||
pub armor_pierce: i8,
|
||||
#[INTEGER]
|
||||
pub antimaterial: i8,
|
||||
pub damage_type: String,
|
||||
#[INTEGER]
|
||||
pub protection: i8,
|
||||
#[INTEGER]
|
||||
pub integrity: i8,
|
||||
pub torque_two_handed: String,
|
||||
pub torque_one_handed: String,
|
||||
#[REAL]
|
||||
pub dodge: f32,
|
||||
#[INTEGER]
|
||||
pub parry: i8,
|
||||
#[INTEGER]
|
||||
pub speed: i8,
|
||||
#[INTEGER]
|
||||
pub stealth: i8,
|
||||
pub category: String,
|
||||
pub target: String,
|
||||
pub special: String,
|
||||
#[INTEGER]
|
||||
pub action_cost: i8,
|
||||
pub reload_cost: String,
|
||||
#[INTEGER]
|
||||
pub range: i8,
|
||||
#[REAL]
|
||||
pub agility_bonus: f32,
|
||||
}
|
||||
|
||||
impl Default for DatabaseEquipementStats {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
id: 0,
|
||||
meta_category: "EqShape".to_string(),
|
||||
name: String::new(),
|
||||
damage_type: serde_json::to_string(&None::<DamageType>).unwrap(),
|
||||
category: serde_json::to_string(&None::<EquipementSerializedCategory>).unwrap(),
|
||||
target: serde_json::to_string(&None::<EquipementTargets>).unwrap(),
|
||||
special: serde_json::to_string(&SpecialField::default()).unwrap(),
|
||||
reload_cost: serde_json::to_string(&None::<u8>).unwrap(),
|
||||
rarity: 0,
|
||||
cost: 0,
|
||||
difficulty: 0,
|
||||
tier: 0,
|
||||
damage: 0,
|
||||
p_damage: 0,
|
||||
precision: 0,
|
||||
rmax: 0,
|
||||
armor_break: 0,
|
||||
armor_pierce: 0,
|
||||
antimaterial: 0,
|
||||
protection: 0,
|
||||
integrity: 0,
|
||||
torque_two_handed: serde_json::to_string(&0).unwrap(),
|
||||
torque_one_handed: serde_json::to_string(&None::<u8>).unwrap(),
|
||||
dodge: 0.,
|
||||
parry: 0,
|
||||
speed: 0,
|
||||
stealth: 0,
|
||||
range: 0,
|
||||
agility_bonus: 0.,
|
||||
action_cost: 0,
|
||||
adjective: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Shape of the equipement, first mandatory part of an equipement
|
||||
#[derive(Default)]
|
||||
pub struct EqShape {
|
||||
/// The inner stats of the part
|
||||
pub(super) stats: InnerEquipementStats,
|
||||
}
|
||||
|
||||
impl From<InnerEquipementStats> for EqShape {
|
||||
fn from(value: InnerEquipementStats) -> Self {
|
||||
Self { stats: value }
|
||||
}
|
||||
}
|
||||
|
||||
/// Material used for the equipement, all equipements are crafted with 1-2 materials
|
||||
#[derive(Default)]
|
||||
pub struct EqMaterial {
|
||||
/// The inner stats of the part
|
||||
pub(super) stats: InnerEquipementStats,
|
||||
}
|
||||
|
||||
impl From<InnerEquipementStats> for EqMaterial {
|
||||
fn from(value: InnerEquipementStats) -> Self {
|
||||
Self { stats: value }
|
||||
}
|
||||
}
|
||||
|
||||
/// Nature of the equipement, some natures are reserved and some can be chained
|
||||
///
|
||||
/// Deciding on the combinaison can be tricky an will need an extra field
|
||||
#[derive(Default)]
|
||||
pub struct EqNature {
|
||||
/// The inner stats of the part
|
||||
pub(super) stats: InnerEquipementStats,
|
||||
}
|
||||
|
||||
impl From<InnerEquipementStats> for EqNature {
|
||||
fn from(value: InnerEquipementStats) -> Self {
|
||||
Self { stats: value }
|
||||
}
|
||||
}
|
||||
|
||||
/// Finishing touches, since all of them have a cost, they are treated in a special fashion
|
||||
#[derive(Default)]
|
||||
pub struct EqFinishing {
|
||||
/// The inner stats of the part
|
||||
pub(super) stats: InnerEquipementStats,
|
||||
}
|
||||
|
||||
impl From<InnerEquipementStats> for EqFinishing {
|
||||
fn from(value: InnerEquipementStats) -> Self {
|
||||
Self { stats: value }
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::{
|
||||
EqFinishing, EqMaterial, EqShape, Equipement, InitialEquipementList, InnerEquipementStats,
|
||||
};
|
||||
use crate::interfaces::RecipeCollection;
|
||||
|
||||
fn list_equip() -> Vec<Equipement> {
|
||||
(0..10)
|
||||
.map(|_| Equipement {
|
||||
..Default::default()
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_struct_creation() {
|
||||
let _stats = InnerEquipementStats::default();
|
||||
let _eq1 = Equipement {
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let _list_eq = list_equip();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_creating_all_equipements() {
|
||||
let shape = vec![EqShape::default().into(), EqShape::default().into()];
|
||||
|
||||
// let _nature: Vec<Equipement> = vec![EqNature::default().into(), EqNature::default().into()];
|
||||
let material = vec![EqMaterial::default().into(), EqMaterial::default().into()];
|
||||
let finishing = vec![EqFinishing::default().into(), EqMaterial::default().into()];
|
||||
|
||||
let mut leq = InitialEquipementList::from_vectored(shape);
|
||||
// leq.combine_all(&InitialEquipementList::from_vectored(nature));
|
||||
leq.combine_all(&InitialEquipementList::from_vectored(material));
|
||||
leq.combine_all(&InitialEquipementList::from_vectored(finishing));
|
||||
}
|
||||
|
||||
#[ignore]
|
||||
#[test]
|
||||
fn test_default_behaviour() {
|
||||
unimplemented!()
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,120 @@
|
|||
// Workspace: weaponry
|
||||
// File: weaponry/src/weaponry_structs/equipement_thin_types.rs
|
||||
//! Important thin representation to avoid using direct and risky usage of usize,isize etc...
|
||||
|
||||
use std::{
|
||||
fmt::Display,
|
||||
ops::{Add, Sub},
|
||||
};
|
||||
|
||||
/// Thin representation of Precision to avoid mistakes
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct Precision(pub i8);
|
||||
|
||||
/// Thin representation of Dices to avoid mistakes
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct Dices(pub usize);
|
||||
|
||||
/// Thin representation of Attack to avoid mistakes
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
pub struct Attacks(pub i8);
|
||||
|
||||
impl Add for Attacks {
|
||||
type Output = Self;
|
||||
|
||||
fn add(self, rhs: Self) -> Self::Output {
|
||||
Self(self.0 + rhs.0)
|
||||
}
|
||||
}
|
||||
impl Sub for Attacks {
|
||||
type Output = Self;
|
||||
|
||||
fn sub(self, rhs: Self) -> Self::Output {
|
||||
Self(self.0 - rhs.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::ops::Deref for Attacks {
|
||||
type Target = i8;
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
impl Display for Attacks {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> core::fmt::Result {
|
||||
<i8 as Display>::fmt(&self.0, f)
|
||||
}
|
||||
}
|
||||
/// Thin representation of Actions to avoid mistakes
|
||||
#[derive(Clone, Copy, Default, Debug)]
|
||||
pub struct Actions(pub i8);
|
||||
|
||||
impl std::ops::Deref for Actions {
|
||||
type Target = i8;
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl Add for Actions {
|
||||
type Output = Self;
|
||||
|
||||
fn add(self, rhs: Self) -> Self::Output {
|
||||
Self(self.0 + rhs.0)
|
||||
}
|
||||
}
|
||||
impl Sub for Actions {
|
||||
type Output = Self;
|
||||
|
||||
fn sub(self, rhs: Self) -> Self::Output {
|
||||
Self(self.0 - rhs.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for Actions {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> core::fmt::Result {
|
||||
<i8 as Display>::fmt(&self.0, f)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::ops::Deref for Precision {
|
||||
type Target = i8;
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for Precision {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> core::fmt::Result {
|
||||
<i8 as Display>::fmt(&self.0, f)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::ops::Deref for Dices {
|
||||
type Target = usize;
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for Dices {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> core::fmt::Result {
|
||||
<usize as Display>::fmt(&self.0, f)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use crate::weaponry_structs::equipement_thin_types::{Actions, Attacks, Dices, Precision};
|
||||
|
||||
#[test]
|
||||
fn test_displays() {
|
||||
println!(
|
||||
"{}, {}, {}, {}",
|
||||
Attacks(0),
|
||||
Actions(1),
|
||||
Precision(2),
|
||||
Dices(3)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,49 @@
|
|||
// Workspace: weaponry
|
||||
// File: weaponry/src/weaponry_structs/mod.rs
|
||||
//! All weaponry intermod structures
|
||||
|
||||
// #![allow(dead_code)]
|
||||
// use mimalloc::MiMalloc;
|
||||
|
||||
// #[global_allocator]
|
||||
// static GLOBAL: MiMalloc = MiMalloc;
|
||||
|
||||
// #[cfg(not(target_env = "msvc"))]
|
||||
// use tikv_jemallocator::Jemalloc;
|
||||
|
||||
// #[cfg(not(target_env = "msvc"))]
|
||||
// #[global_allocator]
|
||||
// static GLOBAL: Jemalloc = Jemalloc;
|
||||
|
||||
#[macro_use]
|
||||
mod equipement_advanced_repr;
|
||||
mod equipement_advanced_tools;
|
||||
mod equipement_fields;
|
||||
mod equipement_impl_basics;
|
||||
pub mod equipement_impl_database;
|
||||
mod equipement_impl_io;
|
||||
mod equipement_impl_logic;
|
||||
pub mod equipement_scenario;
|
||||
pub mod equipement_structs;
|
||||
pub mod equipement_thin_types;
|
||||
|
||||
// Republishes the most used symbols
|
||||
// All generic structs
|
||||
pub use equipement_structs::{Equipement, InitialEquipementList};
|
||||
|
||||
// All generic fields
|
||||
// #[allow(unused_imports)]
|
||||
pub use crate::weaponry_structs::equipement_advanced_repr::RefinedEquipementList;
|
||||
pub use equipement_advanced_repr::RefinedEquipement;
|
||||
pub use equipement_fields::PhysicalDamageType;
|
||||
pub use equipement_fields::{
|
||||
DamageMod, DamageType, EquipementSerializedCategory, NatureTarget, SpecialField,
|
||||
WeaponBaseShape,
|
||||
};
|
||||
// Likely ? Final Re-Exports
|
||||
pub use equipement_scenario::CrossRecipeScenario;
|
||||
|
||||
// // TODO[!]: Add a sensible prelude
|
||||
// mod prelude{
|
||||
|
||||
// }
|
||||
|
|
@ -0,0 +1,18 @@
|
|||
# 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 ?
|
||||
Binary file not shown.
|
|
@ -0,0 +1,367 @@
|
|||
[data_generation]
|
||||
# This value should be overwriten by a relative path
|
||||
database = "./ravenous_databases/weapons.db"
|
||||
|
||||
[classes]
|
||||
header = '''\begin{}[
|
||||
presep = 0pt, postsep = 0pt,
|
||||
]{
|
||||
colspec = {Q[h,j,wd=3.5cm] Q[c,h, wd=0.52cm] h{2.5cm} Q[c,h,wd=0.75cm] Q[h,j,wd=8.4cm]},
|
||||
hspan = minimal, vspan=minimal,
|
||||
{} width = 1\columnwidth,
|
||||
colsep = 2mm, abovesep=0px,belowsep=0px, leftsep=3px, rightsep=3px,
|
||||
% row{1 } = {bg=coheaderschools, fg=white},
|
||||
row{even } = {bg=coevenschools},
|
||||
cells = {font = \footnotesize\selectfont},
|
||||
% measure = vbox,
|
||||
}
|
||||
'''
|
||||
|
||||
sep = ''' \SetRow{white }&&&&\\'''
|
||||
tier = ''' \SetCell[c=5]{white } {\normalsize \textbf{ Tiers {} }} \\
|
||||
\hline
|
||||
\SetRow{bg=coheaderschools}Technique & Niv & Type & Coût & Effet\\
|
||||
\hline'''
|
||||
|
||||
end = '''\end{longtblr}'''
|
||||
|
||||
[craft]
|
||||
header_alchemy = '''\begin{landscape}\begin{center}
|
||||
\begin{longtblr}[
|
||||
entry = none,
|
||||
label = none,
|
||||
]{
|
||||
colspec = {|X[-1]X[-1]X[-1]X[-1]X[-1]X[-1]X[-1]|},
|
||||
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,
|
||||
}
|
||||
\hline
|
||||
Ingrédient & Partie & Rareté & Effet (Principal) & Effets (Catalysé) & Difficulté & Toxicité \\
|
||||
\hline'''
|
||||
header_armors = '''\begin{landscape}\begin{center}
|
||||
\begin{longtblr}[
|
||||
entry = none,
|
||||
label = none,
|
||||
]{
|
||||
colspec = {|X[-1]X[-1]X[-1]X[-1]X[-1]X[-1]X[-1]X[-1]X[-1]X[-1]X[-1]X[-1]X[-1]X[-1]Q[wd=4cm]|},
|
||||
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,
|
||||
}
|
||||
\hline
|
||||
Nom & Rareté & Dégâts & + & R.Max & Armor.B & Prot & Int. & Deux M & Une M & Esq. & Parr. & Vitesse & Discrétion & Spécial \\
|
||||
\hline'''
|
||||
header_forge = ''' Ingrédient & Rareté & Densité & Effet Armes (Principal) & Effet Armures (Principal) & Effets Armes (Catalysé) & Effet Armures (C) & Difficulté & Préparation \\
|
||||
\hline'''
|
||||
header_weapons = '''\begin{landscape}\begin{center}
|
||||
\begin{longtblr}[
|
||||
entry = none,
|
||||
label = none,
|
||||
]{
|
||||
colspec = {|X[-1]X[-1]X[-1]X[-1]X[-1]X[-1]X[-1]X[-1]X[-1]X[-1]X[-1]X[-1]X[-1]X[-1]X[-1]X[-1]Q[wd=4cm]|},
|
||||
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,
|
||||
}
|
||||
\hline
|
||||
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} \\
|
||||
\hline'''
|
||||
header_food = '''\begin{landscape}\begin{center}
|
||||
\begin{longtblr}[
|
||||
entry = none,
|
||||
label = none,
|
||||
]{
|
||||
colspec = {|X[-1]X[-1]X[-1]X[-1]X[-1]X[-1]X[-1]X[-1]|},
|
||||
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,
|
||||
}
|
||||
\hline
|
||||
Ingrédient & Partie & Rareté & Satiété & Effet (Plat) & Effets (Accompagnement) & Difficulté & Toxicité \\
|
||||
\hline'''
|
||||
header_mtrap = '''\begin{landscape}\begin{center}
|
||||
\begin{longtblr}[
|
||||
entry = none,
|
||||
label = none,
|
||||
]{
|
||||
colspec = {|X[-1]X[-1]X[-1]X[-1]X[-1]|},
|
||||
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,
|
||||
}
|
||||
\hline
|
||||
Élément & Prix & Effet & Difficulté & Activation & Solidité \\
|
||||
\hline'''
|
||||
header_traps = ''' Nom & Type & Prix & Toxicité & Effet \\
|
||||
\hline'''
|
||||
header_gadgets ='''\begin{center}
|
||||
\begin{longtblr}[
|
||||
entry = none,
|
||||
label = none,
|
||||
]{
|
||||
colspec = {|X[-1]XX[-1]|},
|
||||
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,
|
||||
}
|
||||
\hline
|
||||
Nom & Effet & Prix\\'''
|
||||
header_potions = '''\begin{center}
|
||||
\begin{longtblr}[
|
||||
entry = none,
|
||||
label = none,
|
||||
]{
|
||||
colspec = {|X[-1]X[-1]X[-1]X[-1]X|},
|
||||
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,
|
||||
}
|
||||
\hline
|
||||
Nom & Type & Prix & Toxicité & Effet \\
|
||||
\hline'''
|
||||
end = ''' \hline
|
||||
\end{tblr}
|
||||
}'''
|
||||
end_long = ''' \hline
|
||||
\end{longtblr}
|
||||
\end{center}
|
||||
'''
|
||||
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} \\
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue