Merge pull request 'develop' (#18) from develop into releases
Reviewed-on: Dandaedre/rcraft_solver#18
This commit is contained in:
commit
f090c6551f
|
|
@ -1,11 +1,12 @@
|
|||
/target
|
||||
/.idea
|
||||
*.iml
|
||||
expected_values.md
|
||||
/bin.py
|
||||
python/dontlook.py
|
||||
expected_values.md
|
||||
releases/*
|
||||
.whl
|
||||
pyinstaller_log.txt
|
||||
|
||||
# Byte-compiled / optimized / DLL files
|
||||
__pycache__/
|
||||
|
|
@ -159,4 +160,4 @@ dmypy.json
|
|||
.pytype/
|
||||
|
||||
# Cython debug symbols
|
||||
cython_debug/
|
||||
cython_debug/
|
||||
|
|
|
|||
|
|
@ -553,7 +553,7 @@ checksum = "447660ad36a13288b1db4d4248e857b510e8c3a225c822ba4fb748c0aafecffd"
|
|||
|
||||
[[package]]
|
||||
name = "xiv_craft_solver"
|
||||
version = "0.1.3"
|
||||
version = "0.1.4"
|
||||
dependencies = [
|
||||
"clap",
|
||||
"lazy_static",
|
||||
|
|
|
|||
|
|
@ -1,9 +1,13 @@
|
|||
[package]
|
||||
name = "xiv_craft_solver"
|
||||
version = "0.1.3"
|
||||
version = "0.1.5"
|
||||
edition = "2021"
|
||||
authors = ["谭俊健","Dandaedre","Vkyfox"]
|
||||
description = "Small XIV solver library in rust, with python and rust bindings"
|
||||
homepage = "https://proxy.dandaedre.com/gitea/Dandaedre/rcraft_solver"
|
||||
documentation = "https://proxy.dandaedre.com/gitea/Dandaedre/rcraft_solver"
|
||||
repository = "https://proxy.dandaedre.com/gitea/Dandaedre/rcraft_solver.git"
|
||||
license = "MIT OR Apache-2.0"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,105 @@
|
|||
[tasks.release]
|
||||
dependencies = [
|
||||
"format",
|
||||
"clean",
|
||||
"build",
|
||||
"maturin",
|
||||
"maturin_build",
|
||||
"pip",
|
||||
"pyinstaller",
|
||||
"zip",
|
||||
]
|
||||
|
||||
[tasks.upload]
|
||||
script_runner="@shell"
|
||||
ignore_errors = true
|
||||
script = [
|
||||
"twine upload releases/ffcraft_solver*.whl --repository gitea",
|
||||
"twine upload releases/xiv_craft_solver*.whl --repository gitea",
|
||||
]
|
||||
|
||||
[tasks.format]
|
||||
install_crate = "rustfmt"
|
||||
command = "cargo"
|
||||
args = ["fmt", "--", "--emit=files"]
|
||||
|
||||
[tasks.clean]
|
||||
command = "cargo"
|
||||
args = ["clean"]
|
||||
dependencies = ["remove_tmp"]
|
||||
|
||||
[tasks.remove_tmp]
|
||||
script_runner = "@shell"
|
||||
ignore_errors = true
|
||||
script = '''
|
||||
rm -rf releases
|
||||
rm -rf python/build
|
||||
rm -rf python/dist
|
||||
'''
|
||||
|
||||
[tasks.zip]
|
||||
windows_alias = 'zip_win'
|
||||
linux_alias = 'zip_linux'
|
||||
|
||||
[tasks.zip_linux]
|
||||
script_runner = "@shell"
|
||||
script = '''
|
||||
mkdir -p releases # Add version as an arg and things
|
||||
cp target/wheels/*.whl releases/
|
||||
zip releases/ffcraft_solver_cli.zip -j target/release/ffcraft_solver_cli craft.toml -j target/release/libxiv_craft_solver.so
|
||||
cd python/dist/ && zip ../../releases/ffcraft_solver_gui.zip -r ffcraft_solver_gui_linux/
|
||||
'''
|
||||
|
||||
[tasks.zip_win]
|
||||
script_runner = "@shell"
|
||||
script = '''
|
||||
mkdir -p releases # Add version as an arg and things
|
||||
cp target/wheels/*.whl releases/
|
||||
tar acvf releases/ff_craft_solver_cli_win.zip .\craft.toml -C .\target\release\ ffcraft_solver_cli.exe libxiv_craft_solver.d
|
||||
tar acvf releases/ff_craft_solver_gui_win.zip -C .\python\dist\ .\ffcraft_solver_gui_win\*
|
||||
'''
|
||||
|
||||
[tasks.pip]
|
||||
script_runner = "@shell"
|
||||
ignore_errors = true
|
||||
script = '''
|
||||
cd python
|
||||
rm -rf build dist
|
||||
pip install -q -r requirements_dev.txt
|
||||
pip install -q -e .
|
||||
python -m pip wheel . --wheel-dir=../releases/
|
||||
'''
|
||||
|
||||
[tasks.pyinstaller]
|
||||
windows_alias = "windows_pyinstaller"
|
||||
linux_alias = "linux_pyinstaller"
|
||||
|
||||
[tasks.linux_pyinstaller]
|
||||
script_runner = "@shell"
|
||||
script = '''
|
||||
cd python
|
||||
pyinstaller src/ffcraft_solver/__main__.py -i "src/ffcraft_solver/ressources/ffcraft_solver.ico" --add-data "src/ffcraft_solver/configs/:ffcraft_solver/configs" --add-data "src/ffcraft_solver/ressources/:ffcraft_solver/ressources" --name ffcraft_solver_gui_linux -y
|
||||
'''
|
||||
|
||||
[tasks.windows_pyinstaller]
|
||||
script_runner = "@shell"
|
||||
script = '''
|
||||
cd python && pyinstaller src\ffcraft_solver\__main__.py --add-data "src\ffcraft_solver\configs\;ffcraft_solver\configs" --add-data "src\ffcraft_solver\ressources\;ffcraft_solver\ressources" --name ffcraft_solver_gui_win -y
|
||||
'''
|
||||
|
||||
[tasks.build]
|
||||
command = "cargo"
|
||||
args = ["build","--release"]
|
||||
dependencies = ["clean"]
|
||||
|
||||
[tasks.maturin]
|
||||
command = "maturin"
|
||||
args = ["develop", "--release"]
|
||||
|
||||
[tasks.maturin_build]
|
||||
command = "maturin"
|
||||
args = ["build", "--release"]
|
||||
|
||||
|
||||
[tasks.rust]
|
||||
dependencies = ["build","maturin"]
|
||||
|
|
@ -0,0 +1,30 @@
|
|||
# Pre-Release
|
||||
|
||||
## v0.2
|
||||
### Breaking
|
||||
✅ (GUI) Make macros work
|
||||
🟩 (GUI) Visual feedback when pressing solve
|
||||
🟩 (GUI) Update on the Quality %
|
||||
🟩 (GUI) Ability to save
|
||||
✅ (GUI) Make the logging work
|
||||
🟩 (PKG) Rename libs, bin, python, exe
|
||||
### Important
|
||||
✅ (PKG) Have cargo-make setup for release/cleanup/build
|
||||
✅ (PKG) Merge latest pre-release for the GUI
|
||||
### Features
|
||||
🟩 (GUI) Refactor code
|
||||
|
||||
# Roadmap
|
||||
## v1.0.0
|
||||
|
||||
### Important
|
||||
🟩 (LIB) Rust API docs
|
||||
🟩 (CLI) Accept and copy from the base recipes
|
||||
🟩 (CLI) Accept and copy pots & food
|
||||
🟩 (PKG) Have a unified toml/yaml way of registering recipes
|
||||
🟩 (LIB) Tests
|
||||
|
||||
### Features
|
||||
🟩 (GUI) Have full documentation
|
||||
🟩 (LIB) Benchmarks
|
||||
🟩 (GUI) Code coverage
|
||||
27
makefile
27
makefile
|
|
@ -1,27 +0,0 @@
|
|||
clean:
|
||||
@echo "[MAKE] Cleaning last release"
|
||||
cargo clean
|
||||
rm -rf releases
|
||||
rm -rf python/build
|
||||
rm -rf python/dist
|
||||
|
||||
rust:
|
||||
@echo "[MAKE] Building the libraries"
|
||||
maturin develop --release -q
|
||||
cargo build --release -q # --features="no_python"
|
||||
|
||||
python:
|
||||
@echo "[MAKE] Building the python project"
|
||||
cd python && rm -rf build dist
|
||||
cd python && pip install -q -r requirements_dev.txt
|
||||
cd python && pip install -q -e .
|
||||
cd python && pyinstaller src/ffcraft_solver/__main__.py -i "src/ffcraft_solver/ressources/ffcraft_solver.ico" --add-data "src/ffcraft_solver/configs/:ffcraft_solver/configs" --add-data "src/ffcraft_solver/ressources/:ffcraft_solver/ressources" --name ffcraft_solver_gui -y > /dev/null 2>pyinstaller_log.txt
|
||||
|
||||
|
||||
|
||||
.PHONY: clean rust python
|
||||
release: clean rust python
|
||||
mkdir -p releases # Add version as an arg and things
|
||||
@echo "[MAKE] Copying releases in the releases/ directory"
|
||||
zip releases/ffcraft_solver_cli.zip -q -j target/release/ffcraft_solver_cli craft.toml -j target/release/libxiv_craft_solver.so
|
||||
cd python/dist/ && zip -q ../../releases/ffcraft_solver_gui.zip -r ffcraft_solver_gui/
|
||||
|
|
@ -5,7 +5,7 @@ build-backend = "maturin"
|
|||
[project] # The rust bindings
|
||||
name = "xiv_craft_solver"
|
||||
requires-python = ">=3.7"
|
||||
version = "0.0.4"
|
||||
version = "0.1.5"
|
||||
classifiers = [
|
||||
"Programming Language :: Rust",
|
||||
"Programming Language :: Python :: Implementation :: CPython",
|
||||
|
|
|
|||
Binary file not shown.
|
|
@ -1,58 +0,0 @@
|
|||
71 INFO: PyInstaller: 5.8.0
|
||||
71 INFO: Python: 3.10.6
|
||||
72 INFO: Platform: Linux-6.1.11-76060111-generic-x86_64-with-glibc2.35
|
||||
72 INFO: wrote /home/dandaedre/Documents/Git/ffcraft_solver/python/ffcraft_solver_gui.spec
|
||||
74 INFO: UPX is available.
|
||||
74 INFO: Extending PYTHONPATH with paths
|
||||
['/home/dandaedre/Documents/Git/ffcraft_solver/python/src']
|
||||
166 INFO: checking Analysis
|
||||
166 INFO: Building Analysis because Analysis-00.toc is non existent
|
||||
166 INFO: Initializing module dependency graph...
|
||||
167 INFO: Caching module graph hooks...
|
||||
176 INFO: Analyzing base_library.zip ...
|
||||
581 INFO: Loading module hook 'hook-heapq.py' from '/home/dandaedre/Documents/Git/ffcraft_solver/.venv/lib/python3.10/site-packages/PyInstaller/hooks'...
|
||||
625 INFO: Loading module hook 'hook-encodings.py' from '/home/dandaedre/Documents/Git/ffcraft_solver/.venv/lib/python3.10/site-packages/PyInstaller/hooks'...
|
||||
1292 INFO: Loading module hook 'hook-pickle.py' from '/home/dandaedre/Documents/Git/ffcraft_solver/.venv/lib/python3.10/site-packages/PyInstaller/hooks'...
|
||||
2161 INFO: Caching module dependency graph...
|
||||
2221 INFO: running Analysis Analysis-00.toc
|
||||
2236 INFO: Analyzing /home/dandaedre/Documents/Git/ffcraft_solver/python/src/ffcraft_solver/__main__.py
|
||||
2508 INFO: Loading module hook 'hook-platform.py' from '/home/dandaedre/Documents/Git/ffcraft_solver/.venv/lib/python3.10/site-packages/PyInstaller/hooks'...
|
||||
2672 INFO: Loading module hook 'hook-pygments.py' from '/home/dandaedre/Documents/Git/ffcraft_solver/.venv/lib/python3.10/site-packages/PyInstaller/hooks'...
|
||||
3097 INFO: Loading module hook 'hook-pkg_resources.py' from '/home/dandaedre/Documents/Git/ffcraft_solver/.venv/lib/python3.10/site-packages/PyInstaller/hooks'...
|
||||
3438 INFO: Loading module hook 'hook-xml.py' from '/home/dandaedre/Documents/Git/ffcraft_solver/.venv/lib/python3.10/site-packages/PyInstaller/hooks'...
|
||||
3457 INFO: Loading module hook 'hook-sysconfig.py' from '/home/dandaedre/Documents/Git/ffcraft_solver/.venv/lib/python3.10/site-packages/PyInstaller/hooks'...
|
||||
4100 INFO: Processing module hooks...
|
||||
5030 INFO: Processing pre-safe import module hook win32com from '/home/dandaedre/Documents/Git/ffcraft_solver/.venv/lib/python3.10/site-packages/_pyinstaller_hooks_contrib/hooks/pre_safe_import_module/hook-win32com.py'.
|
||||
5209 INFO: Loading module hook 'hook-packaging.py' from '/home/dandaedre/Documents/Git/ffcraft_solver/.venv/lib/python3.10/site-packages/PyInstaller/hooks'...
|
||||
5271 INFO: Looking for ctypes DLLs
|
||||
5276 INFO: Analyzing run-time hooks ...
|
||||
5278 INFO: Including run-time hook '/home/dandaedre/Documents/Git/ffcraft_solver/.venv/lib/python3.10/site-packages/PyInstaller/hooks/rthooks/pyi_rth_inspect.py'
|
||||
5279 INFO: Including run-time hook '/home/dandaedre/Documents/Git/ffcraft_solver/.venv/lib/python3.10/site-packages/PyInstaller/hooks/rthooks/pyi_rth_pkgres.py'
|
||||
5281 INFO: Including run-time hook '/home/dandaedre/Documents/Git/ffcraft_solver/.venv/lib/python3.10/site-packages/PyInstaller/hooks/rthooks/pyi_rth_pkgutil.py'
|
||||
5288 INFO: Looking for dynamic libraries
|
||||
5630 INFO: Looking for eggs
|
||||
5630 INFO: Python library not among binary dependencies. Performing additional search...
|
||||
5642 INFO: Using Python library /lib/x86_64-linux-gnu/libpython3.10.so.1.0
|
||||
5644 INFO: Warnings written to /home/dandaedre/Documents/Git/ffcraft_solver/python/build/ffcraft_solver_gui/warn-ffcraft_solver_gui.txt
|
||||
5669 INFO: Graph cross-reference written to /home/dandaedre/Documents/Git/ffcraft_solver/python/build/ffcraft_solver_gui/xref-ffcraft_solver_gui.html
|
||||
5679 INFO: Appending 'datas' from .spec
|
||||
5684 INFO: checking PYZ
|
||||
5684 INFO: Building PYZ because PYZ-00.toc is non existent
|
||||
5684 INFO: Building PYZ (ZlibArchive) /home/dandaedre/Documents/Git/ffcraft_solver/python/build/ffcraft_solver_gui/PYZ-00.pyz
|
||||
6064 INFO: Building PYZ (ZlibArchive) /home/dandaedre/Documents/Git/ffcraft_solver/python/build/ffcraft_solver_gui/PYZ-00.pyz completed successfully.
|
||||
6073 WARNING: Ignoring icon; supported only on Windows and macOS!
|
||||
6073 INFO: checking PKG
|
||||
6073 INFO: Building PKG because PKG-00.toc is non existent
|
||||
6073 INFO: Building PKG (CArchive) ffcraft_solver_gui.pkg
|
||||
6087 INFO: Building PKG (CArchive) ffcraft_solver_gui.pkg completed successfully.
|
||||
6087 INFO: Bootloader /home/dandaedre/Documents/Git/ffcraft_solver/.venv/lib/python3.10/site-packages/PyInstaller/bootloader/Linux-64bit-intel/run
|
||||
6087 INFO: checking EXE
|
||||
6087 INFO: Building EXE because EXE-00.toc is non existent
|
||||
6087 INFO: Building EXE from EXE-00.toc
|
||||
6087 INFO: Copying bootloader EXE to /home/dandaedre/Documents/Git/ffcraft_solver/python/build/ffcraft_solver_gui/ffcraft_solver_gui
|
||||
6088 INFO: Appending PKG archive to custom ELF section in EXE
|
||||
6096 INFO: Building EXE from EXE-00.toc completed successfully.
|
||||
6096 INFO: checking COLLECT
|
||||
6096 INFO: Building COLLECT because COLLECT-00.toc is non existent
|
||||
6096 INFO: Building COLLECT COLLECT-00.toc
|
||||
6236 INFO: Building COLLECT COLLECT-00.toc completed successfully.
|
||||
|
|
@ -9,7 +9,7 @@ authors = [
|
|||
{name="Dandaedre"},
|
||||
]
|
||||
requires-python = ">=3.7"
|
||||
version = "0.0.4"
|
||||
version = "0.1.5"
|
||||
license = {text="Mozilla Public License Version 2.0"}
|
||||
classifiers = [
|
||||
"Programming Language :: Rust",
|
||||
|
|
|
|||
|
|
@ -1,14 +1,12 @@
|
|||
import time
|
||||
|
||||
import dearpygui.dearpygui as dpg
|
||||
import xiv_craft_solver as xcs
|
||||
from ffcraft_solver.modules import loader
|
||||
from ffcraft_solver.modules import loader, log, solver
|
||||
import rich
|
||||
|
||||
dpg.create_context()
|
||||
dpg.configure_app(manual_callback_management=True)
|
||||
dpg.create_viewport(title='XIV Solver', width=500, height=700)
|
||||
|
||||
class User:
|
||||
name = 'NEW'
|
||||
name = ' '
|
||||
food = ''
|
||||
pot = ''
|
||||
specialist = False
|
||||
|
|
@ -25,13 +23,16 @@ class User:
|
|||
dpg.set_value(food_combo, self.food)
|
||||
dpg.set_value(pot_combo, self.pot)
|
||||
dpg.set_value(user_effective_stats, [self.craftsmanship, self.control, self.cp])
|
||||
if self.name != ' ':
|
||||
dpg.set_value(save_user_as, self.name)
|
||||
else:
|
||||
dpg.set_value(save_user_as, '')
|
||||
return True
|
||||
|
||||
def compute_stats(self) -> list:
|
||||
food = []
|
||||
try:
|
||||
full_food = full_config.get_foods_dict()[self.food]
|
||||
# [[5, 120], [0, 0], [26, 82]]
|
||||
if user.initial_craftsmanship * full_food[0][0] / 100 > full_food[0][1]:
|
||||
food.append(full_food[0][1])
|
||||
else:
|
||||
|
|
@ -51,7 +52,6 @@ class User:
|
|||
pot = []
|
||||
try:
|
||||
full_pot = full_config.get_pots_dict()[self.pot]
|
||||
# [(0, 0), (0, 0), (6, 21)]
|
||||
if user.initial_craftsmanship * full_pot[0][0] / 100 > full_pot[0][1]:
|
||||
pot.append(full_pot[0][1])
|
||||
else:
|
||||
|
|
@ -77,6 +77,8 @@ class User:
|
|||
self.control = self.initial_control + food[1] + pot[1] + specialist[1]
|
||||
self.cp = self.initial_cp + food[2] + pot[2] + specialist[2]
|
||||
|
||||
return [self.craftsmanship, self.control, self.cp]
|
||||
|
||||
def set_initial_stats(self, _, app_data, __) -> list:
|
||||
self.initial_craftsmanship = app_data[0]
|
||||
self.initial_control = app_data[1]
|
||||
|
|
@ -102,81 +104,215 @@ class User:
|
|||
self.refresh_gui()
|
||||
return self.food
|
||||
|
||||
def set_name_combo(self, _, app_data, __) -> str:
|
||||
self.name = app_data
|
||||
self.set_initial_stats(0, full_config.get_users_dict()[self.name], None)
|
||||
dpg.set_value(user_stats, [self.initial_craftsmanship, self.initial_control, self.initial_cp])
|
||||
return self.name
|
||||
|
||||
|
||||
class Recipe:
|
||||
name = ''
|
||||
name = ' '
|
||||
progress = 0
|
||||
quality = 0
|
||||
difficulty = 0
|
||||
durability = 0
|
||||
quality_difficulty = 0
|
||||
progress_difficulty = 0
|
||||
quality_extra_difficulty = 0
|
||||
progress_extra_difficulty = 0
|
||||
|
||||
def set_recipe_stats(self, _, app_data, __):
|
||||
self.quality = app_data[0]
|
||||
self.difficulty = app_data[1]
|
||||
self.durability = app_data[2]
|
||||
return self.quality, self.difficulty, self.durability
|
||||
def refresh_gui(self):
|
||||
dpg.set_value(recipe_stats, self.get_recipe_stats()[0:3])
|
||||
dpg.set_value(advanced_recipe_stats, self.get_recipe_stats()[3:7])
|
||||
if self.name != ' ':
|
||||
dpg.set_value(save_recipe_as, self.name)
|
||||
else:
|
||||
dpg.set_value(save_recipe_as, '')
|
||||
|
||||
def get_recipe_stats(self):
|
||||
return self.quality, self.difficulty, self.durability
|
||||
def set_recipe_stats(self, tag, app_data, _) -> list[int, int, int, int, int, int, int]:
|
||||
stats = [0, 0, 0]
|
||||
advanced_stats = [0, 0, 0, 0]
|
||||
|
||||
if tag == 'recipe_tooltip':
|
||||
stats = app_data
|
||||
advanced_stats = dpg.get_value(advanced_recipe_stats)
|
||||
elif tag == 'advanced_recipe_tooltip':
|
||||
stats = dpg.get_value(recipe_stats)
|
||||
advanced_stats = app_data
|
||||
elif tag == 0:
|
||||
stats = [app_data[0], app_data[1], app_data[2]]
|
||||
advanced_stats = [app_data[3], app_data[4], app_data[5], app_data[6]]
|
||||
else:
|
||||
loggers.add_log('Something went very wrong in recipe stat assignment.')
|
||||
|
||||
self.progress = stats[0]
|
||||
self.quality = stats[1]
|
||||
self.durability = stats[2]
|
||||
self.progress_difficulty = advanced_stats[0]
|
||||
self.quality_difficulty = advanced_stats[1]
|
||||
self.progress_extra_difficulty = advanced_stats[2]
|
||||
self.quality_extra_difficulty = advanced_stats[3]
|
||||
|
||||
return [self.progress, self.quality, self.durability, self.progress_difficulty, self.quality_difficulty,
|
||||
self.progress_extra_difficulty, self.quality_extra_difficulty]
|
||||
|
||||
def get_recipe_stats(self) -> list[int, int, int, int, int, int, int]:
|
||||
return [self.progress, self.quality, self.durability, self.progress_difficulty, self.quality_difficulty,
|
||||
self.progress_extra_difficulty, self.quality_extra_difficulty]
|
||||
|
||||
def set_recipe_name(self, _, app_data, __):
|
||||
self.name = app_data
|
||||
self.set_recipe_stats(0, full_config.get_recipes_dict()[self.name], 0)
|
||||
dpg.set_value(recipe_stats, self.get_recipe_stats())
|
||||
self.refresh_gui()
|
||||
return self.name
|
||||
|
||||
def get_recipe_name(self) -> str:
|
||||
return self.name
|
||||
|
||||
|
||||
with dpg.window(label="Settings", width=500, height=700, no_resize=True, no_title_bar=True):
|
||||
user = User()
|
||||
recipe = Recipe()
|
||||
class Solution:
|
||||
def __init__(self, title, logger):
|
||||
self.loggers = logger
|
||||
self.result = None
|
||||
self.title = title
|
||||
|
||||
full_config = loader.Loader()
|
||||
characters_names = full_config.get_users_names()
|
||||
foods_names = full_config.get_foods_names()
|
||||
pots_names = full_config.get_pots_names()
|
||||
recipe_names = full_config.get_recipes_names()
|
||||
def print_result(self):
|
||||
if self.result:
|
||||
dpg.set_value(results, self.result)
|
||||
else:
|
||||
self.loggers.add_log('No solution to display.')
|
||||
|
||||
dpg.add_text("Character")
|
||||
user_combo = dpg.add_combo(items=characters_names, label="Your character")
|
||||
dpg.set_value(user_combo, "NEW")
|
||||
# TODO: Load 1rst user in users.yaml by default
|
||||
# TODO: Make NEW prompt for a name when saving
|
||||
user_stats = dpg.add_input_intx(size=3, label="Stats", tag="stats_tooltip", callback=user.set_initial_stats)
|
||||
with dpg.tooltip("stats_tooltip"):
|
||||
dpg.add_text("Craftsmanship / Control / CP")
|
||||
dpg.add_button(label="Save!", indent=282)
|
||||
specialist_checkbox = dpg.add_checkbox(label="Specialist", tag="specialist", callback=user.set_specialist)
|
||||
dpg.add_text(" ")
|
||||
user_effective_stats = dpg.add_input_intx(size=3, label="Effective stats", tag="effective_stats_tooltip", readonly=True)
|
||||
with dpg.tooltip("effective_stats_tooltip"):
|
||||
dpg.add_text("Craftsmanship / Control / CP")
|
||||
def print_macro_1(self):
|
||||
if self.result and self.result.macro1:
|
||||
dpg.set_value(results, self.result.macro1)
|
||||
else:
|
||||
self.loggers.add_log('No macro to display.')
|
||||
|
||||
dpg.add_separator()
|
||||
def print_macro_2(self):
|
||||
if self.result and self.result.macro2:
|
||||
dpg.set_value(results, self.result.macro2)
|
||||
else:
|
||||
self.loggers.add_log('No macro to display.')
|
||||
|
||||
dpg.add_text("Consumables")
|
||||
food_combo = dpg.add_combo(items=foods_names, label="Food", callback=user.set_food)
|
||||
pot_combo = dpg.add_combo(items=pots_names, label="Pot", callback=user.set_pot)
|
||||
def print_macro_3(self):
|
||||
if self.result and self.result.macro3:
|
||||
dpg.set_value(results, self.result.macro3)
|
||||
else:
|
||||
self.loggers.add_log('No macro to display.')
|
||||
|
||||
dpg.add_separator()
|
||||
|
||||
dpg.add_text("Recipe")
|
||||
recipe_combo = dpg.add_combo(items=recipe_names, label="Recipe", callback=recipe.set_recipe_name)
|
||||
dpg.set_value(recipe_combo, "NEW")
|
||||
recipe_stats = dpg.add_input_intx(size=3, label="Stats", tag="recipe_tooltip", callback=recipe.set_recipe_stats)
|
||||
with dpg.tooltip("recipe_tooltip"):
|
||||
dpg.add_text("Quality / Difficulty / Durability")
|
||||
# TODO: add a small grey text message if recipe matches a known recipe
|
||||
dpg.add_button(label="Save!", indent=282)
|
||||
def request_solve() -> True:
|
||||
loggers.add_log('Solver initialised. Please stand by.')
|
||||
all_results = solver.Solver(user, recipe, loggers)
|
||||
best_quality.result = all_results.best_quality
|
||||
least_steps.result = all_results.least_steps
|
||||
safe_50.result = all_results.safe_50
|
||||
dpg.set_value(results, best_quality.result)
|
||||
loggers.add_log('Solved!')
|
||||
return True
|
||||
|
||||
dpg.add_button(label="Solve!")
|
||||
dpg.add_collapsing_header(label="Result")
|
||||
|
||||
# TODO: add a log space at the bottom
|
||||
def refresh_log() -> True:
|
||||
dpg.set_value(log_window, loggers.log)
|
||||
return True
|
||||
|
||||
dpg.setup_dearpygui()
|
||||
dpg.show_viewport()
|
||||
while dpg.is_dearpygui_running():
|
||||
jobs = dpg.get_callback_queue() # retrieves and clears queue
|
||||
dpg.run_callbacks(jobs)
|
||||
dpg.render_dearpygui_frame()
|
||||
dpg.start_dearpygui()
|
||||
dpg.destroy_context()
|
||||
|
||||
if __name__ == '__main__':
|
||||
dpg.create_context()
|
||||
dpg.configure_app(manual_callback_management=True)
|
||||
dpg.create_viewport(title='XIV Solver', width=500, height=700, resizable=False)
|
||||
|
||||
with dpg.window(label="Settings", width=500, height=700, no_resize=True, no_title_bar=True, no_move=True, no_collapse=True):
|
||||
# Initialization of all our classes
|
||||
loggers = log.Loggers()
|
||||
|
||||
user = User()
|
||||
recipe = Recipe()
|
||||
best_quality = Solution("Best Quality", loggers)
|
||||
least_steps = Solution("Least Steps", loggers)
|
||||
safe_50 = Solution("Safe Margin", loggers)
|
||||
|
||||
full_config = loader.Loader(loggers)
|
||||
characters_names = full_config.get_users_names()
|
||||
foods_names = full_config.get_foods_names()
|
||||
pots_names = full_config.get_pots_names()
|
||||
recipe_names = full_config.get_recipes_names()
|
||||
|
||||
# Start of GUI drawing
|
||||
# CHARACTER
|
||||
dpg.add_text("Character")
|
||||
user_combo = dpg.add_combo(items=characters_names, label="Your character", callback=user.set_name_combo)
|
||||
dpg.set_value(user_combo, ' ')
|
||||
# TODO: Load 1rst user in users.yaml by default
|
||||
user_stats = dpg.add_input_intx(size=3, label="Stats", tag="stats_tooltip", callback=user.set_initial_stats)
|
||||
with dpg.tooltip("stats_tooltip"):
|
||||
dpg.add_text("Craftsmanship / Control / CP")
|
||||
with dpg.group(horizontal=True):
|
||||
save_user_as = dpg.add_input_text(hint='Save as...')
|
||||
dpg.add_button(label="Save!")
|
||||
# TODO: Can't save if value == ' '
|
||||
|
||||
# EFFECTIVE STATS
|
||||
dpg.add_separator()
|
||||
user_effective_stats = dpg.add_input_intx(size=3, label="Effective stats", tag="effective_stats_tooltip", readonly=True)
|
||||
with dpg.tooltip("effective_stats_tooltip"):
|
||||
dpg.add_text("Craftsmanship / Control / CP")
|
||||
dpg.add_separator()
|
||||
|
||||
# MODIFIERS
|
||||
dpg.add_text("Modifiers")
|
||||
food_combo = dpg.add_combo(items=foods_names, label="Food", callback=user.set_food)
|
||||
pot_combo = dpg.add_combo(items=pots_names, label="Pot", callback=user.set_pot)
|
||||
specialist_checkbox = dpg.add_checkbox(label="Specialist", tag="specialist", callback=user.set_specialist)
|
||||
|
||||
# RECIPE
|
||||
dpg.add_separator()
|
||||
dpg.add_text("Recipe")
|
||||
recipe_combo = dpg.add_combo(items=recipe_names, label="Recipe", callback=recipe.set_recipe_name)
|
||||
dpg.set_value(recipe_combo, " ")
|
||||
recipe_stats = dpg.add_input_intx(size=3, label="Stats", tag="recipe_tooltip", callback=recipe.set_recipe_stats)
|
||||
with dpg.tooltip("recipe_tooltip"):
|
||||
dpg.add_text("Progress / Quality / Durability")
|
||||
advanced_recipe_stats = dpg.add_input_intx(
|
||||
size=4, label="Advanced stats", tag="advanced_recipe_tooltip", callback=recipe.set_recipe_stats
|
||||
)
|
||||
with dpg.tooltip("advanced_recipe_tooltip"):
|
||||
dpg.add_text("Progress / Quality difficulty // Progress / Quality extra difficulty")
|
||||
# TODO: add a log if recipe matches a known recipe
|
||||
with dpg.group(horizontal=True):
|
||||
save_recipe_as = dpg.add_input_text(hint='Save as...')
|
||||
dpg.add_button(label="Save!", callback=request_solve)
|
||||
# TODO: Can't save if value == ' '
|
||||
|
||||
# SOLVE
|
||||
dpg.add_separator()
|
||||
dpg.add_button(label="Solve!", callback=request_solve)
|
||||
dpg.add_text()
|
||||
dpg.add_collapsing_header(label="Results", leaf=True)
|
||||
# TODO: Add feedback when pressed
|
||||
|
||||
with dpg.group(horizontal=True):
|
||||
results = dpg.add_input_text(multiline=True, height=220, readonly=True)
|
||||
with dpg.child_window(autosize_x=True, height=220):
|
||||
dpg.add_button(label="BEST QUALITY", width=136, callback=best_quality.print_result)
|
||||
dpg.add_button(label="Macro 1", width=136, callback=best_quality.print_macro_1)
|
||||
dpg.add_button(label="Macro 2", width=136, callback=best_quality.print_macro_2)
|
||||
dpg.add_button(label="SAFE MARGIN", width=136, callback=safe_50.print_result)
|
||||
dpg.add_button(label="Macro 1", width=136, callback=safe_50.print_macro_1)
|
||||
dpg.add_button(label="Macro 2", width=136, callback=safe_50.print_macro_2)
|
||||
dpg.add_button(label="QUICKEST", width=136, callback=least_steps.print_result)
|
||||
dpg.add_button(label="Macro 1", width=136, callback=least_steps.print_macro_1)
|
||||
dpg.add_button(label="Macro 2", width=136, callback=least_steps.print_macro_2)
|
||||
|
||||
# LOG
|
||||
log_window = dpg.add_input_text(multiline=True, default_value=loggers.log, height=50, width=500,
|
||||
tab_input=True, pos=[0, 642], tracked=False, readonly=True, tag="log_window")
|
||||
|
||||
dpg.setup_dearpygui()
|
||||
dpg.show_viewport()
|
||||
while dpg.is_dearpygui_running():
|
||||
jobs = dpg.get_callback_queue() # retrieves and clears queue
|
||||
dpg.run_callbacks(jobs)
|
||||
dpg.render_dearpygui_frame()
|
||||
dpg.start_dearpygui()
|
||||
dpg.destroy_context()
|
||||
|
|
|
|||
|
|
@ -1,3 +1,8 @@
|
|||
# Name: [Quality, difficulty, durability]
|
||||
Grade 7 Tincture of Strength: [12628, 5060, 70]
|
||||
Grade 5 Strength Alkahest: [6200, 1300, 35]
|
||||
# Name: [Progress, quality, durability, progress difficulty, quality difficulty, extra progress difficulty, extra quality difficulty]
|
||||
# as can be found on other solver websites, such as https://yyyy.games/crafter/index.html#/simulator and checking custom recipe.
|
||||
# The language option is the second menu to the left from the top-right hand corner.
|
||||
# If this seems super convoluted, and you'd rather it was just the three in-game values, know that me too.
|
||||
# Unfortunately that is how Square Enix chose to make crafting work in FFXIV.
|
||||
|
||||
Grade 7 Tincture of Strength: [5060, 12628, 70, 130, 115, 80, 70]
|
||||
Grade 5 Strength Alkahest: [1300, 6200, 40, 123, 107, 100, 100]
|
||||
|
|
@ -7,7 +7,7 @@ rich.inspect(xiv_craft_solver.test_result())
|
|||
rich.inspect(xiv_craft_solver.test_result())
|
||||
|
||||
|
||||
class feedMeDaddy:
|
||||
class FeedMeDaddy:
|
||||
durability = 70
|
||||
progress = 3900
|
||||
quality = 10920
|
||||
|
|
@ -27,6 +27,6 @@ class feedMeDaddy:
|
|||
verbose = 0
|
||||
|
||||
|
||||
el_daddy=feedMeDaddy()
|
||||
el_daddy = FeedMeDaddy()
|
||||
rich.inspect(xiv_craft_solver.solve_from_python(el_daddy))
|
||||
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import rich
|
||||
import yaml
|
||||
import os
|
||||
from ffcraft_solver.modules import log
|
||||
|
||||
|
||||
class DefaultConfig:
|
||||
yaml_user = 'configs/users.yaml'
|
||||
|
|
@ -8,40 +9,43 @@ class DefaultConfig:
|
|||
yaml_recipes = 'configs/recipes.yaml'
|
||||
|
||||
|
||||
|
||||
|
||||
class Loader:
|
||||
# TODO: create folder/file if missing when clicking "save"
|
||||
# TODO: log any missing file(s) or the whole folder
|
||||
def __init__(self):
|
||||
self.user_list = {'NEW': [0, 0, 0]}
|
||||
def __init__(self, loggers: log.Loggers):
|
||||
self.loggers = loggers
|
||||
self.user_list = {' ': [0, 0, 0]}
|
||||
self.foods_list = {' ': [[0, 0], [0, 0], [0, 0]]}
|
||||
self.pots_list = {' ': [[0, 0], [0, 0], [0, 0]]}
|
||||
self.recipes_list = {'NEW': [0, 0, 0]}
|
||||
self.recipes_list = {' ': [0, 0, 0, 0, 0, 0, 0]}
|
||||
self.config = DefaultConfig()
|
||||
|
||||
try:
|
||||
with open(self.relative_import(self.config.yaml_user), 'r') as file:
|
||||
self.user_list.update(yaml.safe_load(file))
|
||||
except FileNotFoundError as e:
|
||||
print(e)
|
||||
self.loggers.add_log(e)
|
||||
|
||||
try:
|
||||
with open(self.relative_import(self.config.yaml_consumable), 'r') as file:
|
||||
loaded_file = yaml.safe_load(file)
|
||||
self.foods_list.update(loaded_file['Foods'])
|
||||
self.pots_list.update(loaded_file['Pots'])
|
||||
except FileNotFoundError as e:
|
||||
print(e)
|
||||
self.loggers.add_log(e)
|
||||
|
||||
try:
|
||||
with open(self.relative_import(self.config.yaml_recipes), 'r') as file:
|
||||
self.recipes_list.update(yaml.safe_load(file))
|
||||
except (FileNotFoundError,IsADirectoryError) as e:
|
||||
print(e)
|
||||
except (FileNotFoundError, IsADirectoryError) as e:
|
||||
self.loggers.add_log(e)
|
||||
|
||||
def relative_import(self, path):
|
||||
return (os.path.normpath(os.path.join(__file__,"../..",path)))
|
||||
@staticmethod
|
||||
def relative_import(path):
|
||||
return os.path.normpath(os.path.join(__file__, "../..", path))
|
||||
|
||||
def get_users_dict(self) -> dict:
|
||||
self.loggers.add_log('Loaded user dictionary from users.yaml')
|
||||
return self.user_list
|
||||
|
||||
def get_users_names(self) -> list:
|
||||
|
|
@ -76,7 +80,3 @@ class Loader:
|
|||
for r in self.recipes_list:
|
||||
recipes_names.append(r)
|
||||
return recipes_names
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
loader = Loader()
|
||||
|
|
|
|||
|
|
@ -0,0 +1,29 @@
|
|||
from datetime import datetime
|
||||
import dearpygui.dearpygui as dpg
|
||||
|
||||
|
||||
class Loggers:
|
||||
def __init__(self, log=None):
|
||||
timestamp = self.get_timestamp()
|
||||
if not log:
|
||||
self.log = f"{timestamp} Log initialised."
|
||||
else:
|
||||
self.log = log
|
||||
|
||||
def add_log(self, other: str) -> str:
|
||||
timestamp = self.get_timestamp()
|
||||
self.log = timestamp + ' ' + other + '\n' + self.log
|
||||
dpg.set_value('log_window', self.log)
|
||||
return self.log
|
||||
|
||||
# noinspection PyMethodMayBeStatic
|
||||
def get_timestamp(self) -> str:
|
||||
now = datetime.now()
|
||||
almost_timestamp = str(now.time())
|
||||
timestamp = almost_timestamp.rsplit('.')
|
||||
return f'[{timestamp[0]}]'
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
loggers = Loggers()
|
||||
print(loggers.log)
|
||||
|
|
@ -0,0 +1,173 @@
|
|||
import rich
|
||||
import xiv_craft_solver as xcs
|
||||
from ffcraft_solver.__main__ import User, Recipe
|
||||
from ffcraft_solver.modules import log, translator
|
||||
|
||||
|
||||
class Result:
|
||||
def __init__(self, result, title: str):
|
||||
self.title = title
|
||||
self.original = result
|
||||
self.quality = result.quality
|
||||
self.actions = result.actions
|
||||
self.steps = result.steps
|
||||
self.remaining_cp = result.cp
|
||||
|
||||
self.all_buffs_list = ['manipulation', 'veneration', 'mastersMend', 'wasteNot', 'wasteNot2', 'greatStrides',
|
||||
'innovation', 'finalAppraisal', 'carefulObservation', 'heartAndSoul']
|
||||
|
||||
self.readable_actions = self.text_wrap(self.actions)
|
||||
|
||||
self.macro1 = ''
|
||||
self.macro2 = ''
|
||||
self.macro3 = ''
|
||||
self.make_macro()
|
||||
|
||||
self.readable = f"""/// {self.title}
|
||||
Rotation:
|
||||
{self.readable_actions}
|
||||
Quality: {self.quality}
|
||||
Steps: {self.steps}
|
||||
Remaining CP: {self.remaining_cp}"""
|
||||
|
||||
def __str__(self) -> str:
|
||||
return self.readable
|
||||
|
||||
@staticmethod # il est con ou quoi?
|
||||
def text_wrap(text: list[str]) -> str:
|
||||
"""Transforms a list of words into a string and wraps them at 34 characters with an indent."""
|
||||
line = ' '
|
||||
saved_lines = []
|
||||
justified_text = ''
|
||||
for w in text:
|
||||
if len(line) < 31:
|
||||
line += w + ' '
|
||||
else:
|
||||
saved_lines.append(line)
|
||||
line = ' ' + w + ' '
|
||||
|
||||
if line != saved_lines[-1]:
|
||||
saved_lines.append(line)
|
||||
|
||||
for line in saved_lines:
|
||||
justified_text += line + '\n'
|
||||
|
||||
return justified_text[:-1]
|
||||
|
||||
def make_macro(self) -> True:
|
||||
saved_lines = ['']
|
||||
translated_actions = translator.translate_list(self.actions, "en")
|
||||
count = 0
|
||||
|
||||
for action in translated_actions:
|
||||
line = f'/ac "{action}" <wait.{"2" if self.actions[count] in self.all_buffs_list else "3"}>'
|
||||
saved_lines.append(line)
|
||||
count += 1
|
||||
saved_lines = saved_lines[1:]
|
||||
|
||||
if self.steps != 15 and self.steps != 29 and self.steps != 44:
|
||||
saved_lines.append('/echo Craft complete ! <se.3>')
|
||||
else:
|
||||
self.loggers.log(f'No completion message in macro because rotation is exactly {self.steps} steps.')
|
||||
|
||||
if self.steps > 15:
|
||||
saved_lines.insert(14, '/echo Macro 1 complete <se.2>')
|
||||
|
||||
if self.steps > 30:
|
||||
saved_lines.insert(30, '/echo Macro 2 complete <se.2>')
|
||||
# TODO : test index
|
||||
|
||||
count = 0
|
||||
for line in saved_lines:
|
||||
count += 1
|
||||
if count < 16:
|
||||
self.macro1 += line + '\n'
|
||||
elif 15 < count < 31:
|
||||
self.macro2 += line + '\n'
|
||||
elif 30 < count < 46:
|
||||
self.macro3 += line + '\n'
|
||||
|
||||
self.macro1 = self.macro1[:-1]
|
||||
self.macro2 = self.macro2[:-1]
|
||||
self.macro3 = self.macro3[:-1]
|
||||
return True
|
||||
|
||||
|
||||
class Solver:
|
||||
def __init__(self, user: User, recipe: Recipe, loggers: log.Loggers):
|
||||
self.durability = recipe.durability
|
||||
self.progress = recipe.progress
|
||||
self.quality = recipe.quality
|
||||
self.progress_divider = recipe.progress_difficulty
|
||||
self.quality_divider = recipe.quality_difficulty
|
||||
self.progress_modifier = recipe.progress_extra_difficulty
|
||||
self.quality_modifier = recipe.quality_extra_difficulty
|
||||
|
||||
self.craftsmanship = user.craftsmanship
|
||||
self.control = user.control
|
||||
self.max_cp = user.cp
|
||||
|
||||
self.depth = 10
|
||||
self.byregot_step = 10
|
||||
self.desperate = False
|
||||
self.threads = 8
|
||||
self.verbose = 0
|
||||
|
||||
self.loggers = loggers
|
||||
|
||||
self.solutions = []
|
||||
self.best_quality = None
|
||||
self.least_steps = None
|
||||
self.safe_50 = None
|
||||
|
||||
self.solve()
|
||||
self.compute_all()
|
||||
|
||||
def solve(self) -> str:
|
||||
self.solutions = xcs.solve_from_python(self)
|
||||
return xcs.solve_from_python(self)
|
||||
|
||||
def compute_all(self) -> True:
|
||||
if self.solutions:
|
||||
self.sort_quality()
|
||||
self.compute_best_quality()
|
||||
self.compute_least_steps()
|
||||
self.compute_50percent_quality()
|
||||
|
||||
def sort_quality(self) -> True:
|
||||
self.solutions.sort(key=lambda x: x.quality)
|
||||
return True
|
||||
|
||||
def compute_best_quality(self) -> Result:
|
||||
self.best_quality = Result(self.solutions[-1], 'Best quality')
|
||||
return self.best_quality
|
||||
|
||||
def compute_50percent_quality(self) -> Result:
|
||||
done = False
|
||||
threshold = self.quality * 1.5
|
||||
for s in reversed(self.solutions):
|
||||
if s.quality > threshold:
|
||||
self.safe_50 = Result(s, 'Safe 50')
|
||||
done = True
|
||||
|
||||
if not done:
|
||||
self.loggers.add_log('Could not find a rotation for a 50% Safe Margin.\n'
|
||||
' Defaulting to Best Quality.')
|
||||
self.safe_50 = self.best_quality
|
||||
|
||||
# self.safe_50 = Result(self.solutions[round(len(self.solutions)/2)+1], 'Safe 50') # old version
|
||||
return self.safe_50
|
||||
|
||||
def compute_least_steps(self) -> Result:
|
||||
least_steps = 100
|
||||
output = None
|
||||
if self.solutions:
|
||||
for e in self.solutions:
|
||||
if e.steps < least_steps:
|
||||
least_steps = e.steps
|
||||
output = e
|
||||
self.least_steps = Result(output, 'Least steps')
|
||||
|
||||
return self.least_steps
|
||||
|
||||
|
||||
|
|
@ -0,0 +1,58 @@
|
|||
from ffcraft_solver.modules import log
|
||||
|
||||
loggers = log.Loggers
|
||||
|
||||
supported_languages = {
|
||||
"en": {
|
||||
'basicSynth': 'Basic Synthesis',
|
||||
'basicSynth2': 'Basic Synthesis',
|
||||
'basicTouch': 'Basic Touch',
|
||||
'observe': 'Observe',
|
||||
'mastersMend': "Master's mend",
|
||||
'hastyTouch': 'Hasty Touch',
|
||||
'rapidSynthesis': 'Rapid Synthesis',
|
||||
'wasteNot': 'Waste Not',
|
||||
'veneration': 'Veneration',
|
||||
'standardTouch': 'Standard Touch',
|
||||
'greatStrides': 'Great Strides',
|
||||
'innovation': 'Innovation',
|
||||
'finalAppraisal': 'Final Appraisal',
|
||||
'wasteNot2': 'Waste Not II',
|
||||
'byregotsBlessing': "Byregot's Blessing",
|
||||
'preciseTouch': 'Precise Touch',
|
||||
'muscleMemory': 'Muscle Memory',
|
||||
'carefulSynthesis': 'Careful Synthesis',
|
||||
'manipulation': 'Manipulation',
|
||||
'prudentTouch': 'Prudent Touch',
|
||||
'focusedSynthesis': 'Focused Synthesis',
|
||||
'focusedTouch': 'Focused Touch',
|
||||
'reflect': 'Reflect',
|
||||
'preparatoryTouch': 'Preparatory Touch',
|
||||
'groundwork': 'Groundwork',
|
||||
'delicateSynthesis': 'Delicate Synthesis',
|
||||
'intensiveSynthesis': 'Intensive Synthesis',
|
||||
'trainedEye': 'Trained Eye',
|
||||
'advancedTouch': 'Advanced Touch',
|
||||
'prudentSynthesis': 'Prudent Synthesis',
|
||||
'trainedFinesse': 'Trained Finesse'
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
def translate_list(actions: list, lang: str):
|
||||
output = []
|
||||
if lang in supported_languages:
|
||||
dictionary = supported_languages[lang]
|
||||
for action in actions:
|
||||
try:
|
||||
output.append(dictionary[action])
|
||||
except KeyError:
|
||||
output.append(supported_languages["en"][action])
|
||||
loggers.log('Translation not found. Defaulting to English.\n'
|
||||
' Macros will probably be broken because of this.')
|
||||
|
||||
else:
|
||||
loggers.add_log(f'Language code "{lang}" not recognised.')
|
||||
|
||||
return output
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 248 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 352 KiB |
151
src/action.rs
151
src/action.rs
|
|
@ -1,9 +1,8 @@
|
|||
#[allow(dead_code)]
|
||||
|
||||
use std::fmt::Debug;
|
||||
use lazy_static::lazy_static;
|
||||
use crate::craft::Craft;
|
||||
use crate::specs::{Buff, Success};
|
||||
use lazy_static::lazy_static;
|
||||
#[allow(dead_code)]
|
||||
use std::fmt::Debug;
|
||||
|
||||
pub struct Action {
|
||||
pub name: String,
|
||||
|
|
@ -25,9 +24,15 @@ impl ActionBuilder {
|
|||
short_name = short_name.replace("II", "2");
|
||||
short_name.retain(|c| !c.is_whitespace() && c != '\'');
|
||||
short_name[0..1].make_ascii_lowercase();
|
||||
if name == "Basic Synthesis" { short_name = "basicSynth".to_string(); }
|
||||
if name == "Groundwork" { short_name = "groundwork".to_string(); }
|
||||
if name == "Careful Synthesis" { short_name = "carefulSynthesis".to_string(); }
|
||||
if name == "Basic Synthesis" {
|
||||
short_name = "basicSynth2".to_string();
|
||||
}
|
||||
if name == "Groundwork" {
|
||||
short_name = "groundwork".to_string();
|
||||
}
|
||||
if name == "Careful Synthesis" {
|
||||
short_name = "carefulSynthesis".to_string();
|
||||
}
|
||||
|
||||
Self {
|
||||
action: Action {
|
||||
|
|
@ -38,7 +43,7 @@ impl ActionBuilder {
|
|||
quality: 0,
|
||||
buff: None,
|
||||
short_name,
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
pub fn dur(mut self, dur: u32) -> Self {
|
||||
|
|
@ -68,7 +73,10 @@ impl ActionBuilder {
|
|||
|
||||
impl PartialEq for Action {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.cp == other.cp && self.dur == other.dur && self.progress == other.progress && self.quality == other.quality
|
||||
self.cp == other.cp
|
||||
&& self.dur == other.dur
|
||||
&& self.progress == other.progress
|
||||
&& self.quality == other.quality
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -77,12 +85,18 @@ impl Action {
|
|||
self.name.clone()
|
||||
}
|
||||
pub fn get_cp_cost(&self, _craft: &Craft) -> u32 {
|
||||
if self == &ACTIONS.standard_touch && _craft.buffs.basic_touch > 0 { return 18; };
|
||||
if self == &ACTIONS.advanced_touch && _craft.buffs.standard_touch > 0 { return 18; };
|
||||
if self == &ACTIONS.standard_touch && _craft.buffs.basic_touch > 0 {
|
||||
return 18;
|
||||
};
|
||||
if self == &ACTIONS.advanced_touch && _craft.buffs.standard_touch > 0 {
|
||||
return 18;
|
||||
};
|
||||
self.cp
|
||||
}
|
||||
pub fn get_durability_cost(&self, _craft: &Craft) -> u32 {
|
||||
if self == &ACTIONS.masters_mend { return 30; }
|
||||
if self == &ACTIONS.masters_mend {
|
||||
return 30;
|
||||
}
|
||||
if self.dur == 0 || self.progress == 0 && self.quality == 0 {
|
||||
return 0;
|
||||
}
|
||||
|
|
@ -156,7 +170,6 @@ impl Debug for Action {
|
|||
}
|
||||
}
|
||||
|
||||
|
||||
pub struct ActionList {
|
||||
pub muscle_memory: Action,
|
||||
pub reflect: Action,
|
||||
|
|
@ -186,31 +199,99 @@ pub struct ActionList {
|
|||
impl Default for ActionList {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
muscle_memory: ActionBuilder::new("Muscle Memory").cp(6).progress(300).buff(Some((Buff::MuscleMemory, 5))).build(),
|
||||
reflect: ActionBuilder::new("Reflect").cp(6).quality(100).buff(Some((Buff::InnerQuiet, 1))).build(),
|
||||
muscle_memory: ActionBuilder::new("Muscle Memory")
|
||||
.cp(6)
|
||||
.progress(300)
|
||||
.buff(Some((Buff::MuscleMemory, 5)))
|
||||
.build(),
|
||||
reflect: ActionBuilder::new("Reflect")
|
||||
.cp(6)
|
||||
.quality(100)
|
||||
.buff(Some((Buff::InnerQuiet, 1)))
|
||||
.build(),
|
||||
|
||||
basic_synthesis: ActionBuilder::new("Basic Synthesis").progress(120).build(),
|
||||
careful_synthesis: ActionBuilder::new("Careful Synthesis").cp(7).progress(180).build(),
|
||||
groundwork: ActionBuilder::new("Groundwork").cp(18).dur(20).progress(360).build(),
|
||||
prudent_synthesis: ActionBuilder::new("Prudent Synthesis").cp(18).dur(5).progress(180).build(),
|
||||
delicate_synthesis: ActionBuilder::new("Delicate Synthesis").cp(32).progress(100).quality(100).build(),
|
||||
careful_synthesis: ActionBuilder::new("Careful Synthesis")
|
||||
.cp(7)
|
||||
.progress(180)
|
||||
.build(),
|
||||
groundwork: ActionBuilder::new("Groundwork")
|
||||
.cp(18)
|
||||
.dur(20)
|
||||
.progress(360)
|
||||
.build(),
|
||||
prudent_synthesis: ActionBuilder::new("Prudent Synthesis")
|
||||
.cp(18)
|
||||
.dur(5)
|
||||
.progress(180)
|
||||
.build(),
|
||||
delicate_synthesis: ActionBuilder::new("Delicate Synthesis")
|
||||
.cp(32)
|
||||
.progress(100)
|
||||
.quality(100)
|
||||
.build(),
|
||||
|
||||
basic_touch: ActionBuilder::new("Basic Touch").cp(18).quality(100).buff(Some((Buff::BasicTouch, 1))).build(),
|
||||
standard_touch: ActionBuilder::new("Standard Touch").quality(125).cp(32).buff(Some((Buff::StandardTouch, 1))).build(),
|
||||
byregot_blessing: ActionBuilder::new("Byregot's Blessing").cp(24).quality(100).buff(Some((Buff::InnerQuiet, 0))).build(),
|
||||
prudent_touch: ActionBuilder::new("Prudent Touch").cp(25).dur(5).quality(100).build(),
|
||||
preparatory_touch: ActionBuilder::new("Preparatory Touch").cp(40).dur(20).quality(200).buff(Some((Buff::InnerQuiet, 1))).build(),
|
||||
advanced_touch: ActionBuilder::new("Advanced Touch").quality(150).cp(46).build(),
|
||||
trained_finesse: ActionBuilder::new("Trained Finesse").cp(32).quality(100).dur(0).build(),
|
||||
basic_touch: ActionBuilder::new("Basic Touch")
|
||||
.cp(18)
|
||||
.quality(100)
|
||||
.buff(Some((Buff::BasicTouch, 1)))
|
||||
.build(),
|
||||
standard_touch: ActionBuilder::new("Standard Touch")
|
||||
.quality(125)
|
||||
.cp(32)
|
||||
.buff(Some((Buff::StandardTouch, 1)))
|
||||
.build(),
|
||||
byregot_blessing: ActionBuilder::new("Byregot's Blessing")
|
||||
.cp(24)
|
||||
.quality(100)
|
||||
.buff(Some((Buff::InnerQuiet, 0)))
|
||||
.build(),
|
||||
prudent_touch: ActionBuilder::new("Prudent Touch")
|
||||
.cp(25)
|
||||
.dur(5)
|
||||
.quality(100)
|
||||
.build(),
|
||||
preparatory_touch: ActionBuilder::new("Preparatory Touch")
|
||||
.cp(40)
|
||||
.dur(20)
|
||||
.quality(200)
|
||||
.buff(Some((Buff::InnerQuiet, 1)))
|
||||
.build(),
|
||||
advanced_touch: ActionBuilder::new("Advanced Touch")
|
||||
.quality(150)
|
||||
.cp(46)
|
||||
.build(),
|
||||
trained_finesse: ActionBuilder::new("Trained Finesse")
|
||||
.cp(32)
|
||||
.quality(100)
|
||||
.dur(0)
|
||||
.build(),
|
||||
|
||||
masters_mend: ActionBuilder::new("Master's Mend").cp(88).build(),
|
||||
waste_not: ActionBuilder::new("Waste Not").cp(56).buff(Some((Buff::WasteNot, 4))).build(),
|
||||
waste_not_ii: ActionBuilder::new("Waste Not II").cp(98).buff(Some((Buff::WasteNot, 8))).build(),
|
||||
manipulation: ActionBuilder::new("Manipulation").cp(96).buff(Some((Buff::Manipulation, 8))).build(),
|
||||
veneration: ActionBuilder::new("Veneration").cp(18).buff(Some((Buff::Veneration, 4))).build(),
|
||||
great_strides: ActionBuilder::new("Great Strides").cp(32).buff(Some((Buff::GreatStrides, 3))).build(),
|
||||
innovation: ActionBuilder::new("Innovation").cp(18).buff(Some((Buff::Innovation, 4))).build(),
|
||||
|
||||
waste_not: ActionBuilder::new("Waste Not")
|
||||
.cp(56)
|
||||
.buff(Some((Buff::WasteNot, 4)))
|
||||
.build(),
|
||||
waste_not_ii: ActionBuilder::new("Waste Not II")
|
||||
.cp(98)
|
||||
.buff(Some((Buff::WasteNot, 8)))
|
||||
.build(),
|
||||
manipulation: ActionBuilder::new("Manipulation")
|
||||
.cp(96)
|
||||
.buff(Some((Buff::Manipulation, 8)))
|
||||
.build(),
|
||||
veneration: ActionBuilder::new("Veneration")
|
||||
.cp(18)
|
||||
.buff(Some((Buff::Veneration, 4)))
|
||||
.build(),
|
||||
great_strides: ActionBuilder::new("Great Strides")
|
||||
.cp(32)
|
||||
.buff(Some((Buff::GreatStrides, 3)))
|
||||
.build(),
|
||||
innovation: ActionBuilder::new("Innovation")
|
||||
.cp(18)
|
||||
.buff(Some((Buff::Innovation, 4)))
|
||||
.build(),
|
||||
// Todo: Add back
|
||||
//observe: ActionBuilder::new("observe").cp(18).buff(Some((Buff::Observe, 1))).build(),
|
||||
//focused_synthesis: ActionBuilder::new("focused_synthesis").cp(18).quality(100).build(),
|
||||
|
|
@ -219,5 +300,5 @@ impl Default for ActionList {
|
|||
}
|
||||
|
||||
lazy_static! {
|
||||
pub static ref ACTIONS: ActionList = ActionList::default();
|
||||
}
|
||||
pub static ref ACTIONS: ActionList = ActionList::default();
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
// #![warn(missing_docs,unsafe_code,unstable_features,)]
|
||||
use std::time::{Instant};
|
||||
use clap::Parser;
|
||||
use std::time::Instant;
|
||||
use xiv_craft_solver;
|
||||
|
||||
#[derive(Debug)]
|
||||
|
|
@ -15,37 +15,48 @@ fn main() {
|
|||
println!("Solving...");
|
||||
|
||||
// Solve from config
|
||||
let (recipe,stats) = xiv_craft_solver::load_from_config(&args.recipe_name, &args.file_name, &args.character_name);
|
||||
let results = xiv_craft_solver::solve_craft(recipe,stats,params);
|
||||
|
||||
let (recipe, stats) = xiv_craft_solver::load_from_config(
|
||||
&args.recipe_name,
|
||||
&args.file_name,
|
||||
&args.character_name,
|
||||
);
|
||||
let results = xiv_craft_solver::solve_craft(recipe, stats, params);
|
||||
|
||||
// Stop timer
|
||||
let t_final = now.elapsed().as_millis();
|
||||
|
||||
|
||||
|
||||
// Show best result depending on selected value
|
||||
match results{
|
||||
match results {
|
||||
None => {
|
||||
println!("[Error] No solutions found for craft '{}' with crafter '{}' (ms)", args.recipe_name, args.character_name);
|
||||
return
|
||||
println!(
|
||||
"[Error] No solutions found for craft '{}' with crafter '{}' (ms)",
|
||||
args.recipe_name, args.character_name
|
||||
);
|
||||
return;
|
||||
}
|
||||
Some(ref res)=>{
|
||||
Some(ref res) => {
|
||||
// Show best results
|
||||
if args.verbose>0{
|
||||
println!("[Final] {} results were found:",res.len());
|
||||
if args.verbose > 0 {
|
||||
println!("[Final] {} results were found:", res.len());
|
||||
#[cfg(feature = "verbose")]
|
||||
if args.verbose>1{
|
||||
if args.verbose > 1 {
|
||||
xiv_craft_solver::print_routes(&results);
|
||||
}
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
println!("\n > SOLUTION [Least steps] <");
|
||||
xiv_craft_solver::find_fast_route(&results).unwrap().pretty_print();
|
||||
xiv_craft_solver::find_fast_route(&results)
|
||||
.unwrap()
|
||||
.pretty_print();
|
||||
println!("\n > SOLUTION [Most durability] <");
|
||||
xiv_craft_solver::find_safe_route(&results).unwrap().pretty_print();
|
||||
xiv_craft_solver::find_safe_route(&results)
|
||||
.unwrap()
|
||||
.pretty_print();
|
||||
println!("\n > SOLUTION [Most quality] < ");
|
||||
xiv_craft_solver::find_quality_route(&results).unwrap().pretty_print();
|
||||
xiv_craft_solver::find_quality_route(&results)
|
||||
.unwrap()
|
||||
.pretty_print();
|
||||
|
||||
// #[cfg(feature = "verbose")]
|
||||
// if params.verbose>2{
|
||||
|
|
@ -53,7 +64,11 @@ fn main() {
|
|||
// }
|
||||
|
||||
// Wait for user input
|
||||
println!("\nProgram finished successfully in {}ms\nPress enter to exit...", t_final);
|
||||
let mut input = String::new(); std::io::stdin().read_line(&mut input).unwrap();
|
||||
println!(
|
||||
"\nProgram finished successfully in {}ms\nPress enter to exit...",
|
||||
t_final
|
||||
);
|
||||
let mut input = String::new();
|
||||
std::io::stdin().read_line(&mut input).unwrap();
|
||||
()
|
||||
}
|
||||
}
|
||||
|
|
|
|||
81
src/craft.rs
81
src/craft.rs
|
|
@ -1,12 +1,12 @@
|
|||
use std::fmt::{Debug, Formatter,Display};
|
||||
use crate::action::Action;
|
||||
use crate::specs::{Buff, BuffState, Recipe, Stats, Success};
|
||||
use crate::Parameters;
|
||||
use std::fmt::{Debug, Display, Formatter};
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Craft<'a> {
|
||||
pub recipe: Recipe,
|
||||
pub stats: Stats,
|
||||
pub recipe: Recipe,
|
||||
pub stats: Stats,
|
||||
pub buffs: BuffState,
|
||||
pub step_count: u32,
|
||||
pub durability: i32,
|
||||
|
|
@ -19,7 +19,7 @@ pub struct Craft<'a> {
|
|||
}
|
||||
|
||||
impl<'a> Craft<'a> {
|
||||
pub fn new(recipe: Recipe, stats: Stats, params: Parameters) -> Craft<'a> {
|
||||
pub fn new(recipe: Recipe, stats: Stats, params: Parameters) -> Craft<'a> {
|
||||
Self {
|
||||
recipe,
|
||||
stats,
|
||||
|
|
@ -36,12 +36,16 @@ impl<'a> Craft<'a> {
|
|||
}
|
||||
|
||||
pub fn get_base_progression(&self) -> u32 {
|
||||
let base_value = (self.stats.craftsmanship as f64 / 10.0) / (self.recipe.progress_divider as f64 / 100.0) + 2.0;
|
||||
let base_value = (self.stats.craftsmanship as f64 / 10.0)
|
||||
/ (self.recipe.progress_divider as f64 / 100.0)
|
||||
+ 2.0;
|
||||
(base_value * (self.recipe.progress_modifier as f64 / 100.0) as f64).floor() as u32
|
||||
}
|
||||
|
||||
pub fn get_base_quality(&self) -> u32 {
|
||||
let base_value = (self.stats.control as f64 / 10.0) / (self.recipe.quality_divider as f64 / 100.0) + 35.0;
|
||||
let base_value = (self.stats.control as f64 / 10.0)
|
||||
/ (self.recipe.quality_divider as f64 / 100.0)
|
||||
+ 35.0;
|
||||
(base_value * (self.recipe.quality_modifier as f64 / 100.0) as f64).floor() as u32
|
||||
}
|
||||
|
||||
|
|
@ -53,18 +57,39 @@ impl<'a> Craft<'a> {
|
|||
self.step_count += 1;
|
||||
self.cp -= action.get_cp_cost(self) as i32;
|
||||
self.durability -= action.get_durability_cost(self) as i32;
|
||||
self.progression += (action.get_progress(self) as f64 * (self.get_base_progression() as f64 / 100.0)).floor() as u32;
|
||||
self.quality += (action.get_quality(self) as f64 * (self.get_base_quality() as f64 / 100.0)).floor() as u32;
|
||||
if self.progression >= self.recipe.progress { self.success = Success::Success; }
|
||||
if self.durability <= 0 { self.success = Success::Failure; }
|
||||
if self.buffs.manipulation > 0 { self.durability += 5; }
|
||||
if action.quality > 0 { self.buffs.inner_quiet += 1; }
|
||||
self.progression += (action.get_progress(self) as f64
|
||||
* (self.get_base_progression() as f64 / 100.0))
|
||||
.floor() as u32;
|
||||
self.quality += (action.get_quality(self) as f64 * (self.get_base_quality() as f64 / 100.0))
|
||||
.floor() as u32;
|
||||
if self.progression >= self.recipe.progress {
|
||||
self.success = Success::Success;
|
||||
}
|
||||
if self.durability <= 0 {
|
||||
self.success = Success::Failure;
|
||||
}
|
||||
if self.buffs.manipulation > 0 {
|
||||
self.durability += 5;
|
||||
}
|
||||
if action.quality > 0 {
|
||||
self.buffs.inner_quiet += 1;
|
||||
}
|
||||
self.buffs.tick();
|
||||
if action.progress > 0 { self.buffs.remove(Buff::MuscleMemory); }
|
||||
if action.quality > 0 { self.buffs.remove(Buff::GreatStrides); }
|
||||
if let Some((buff, duration)) = action.get_buff() { self.buffs.apply(buff, duration); }
|
||||
if self.durability > self.recipe.durability as i32 { self.durability = self.recipe.durability as i32; }
|
||||
if self.buffs.inner_quiet > 10 { self.buffs.inner_quiet = 10; }
|
||||
if action.progress > 0 {
|
||||
self.buffs.remove(Buff::MuscleMemory);
|
||||
}
|
||||
if action.quality > 0 {
|
||||
self.buffs.remove(Buff::GreatStrides);
|
||||
}
|
||||
if let Some((buff, duration)) = action.get_buff() {
|
||||
self.buffs.apply(buff, duration);
|
||||
}
|
||||
if self.durability > self.recipe.durability as i32 {
|
||||
self.durability = self.recipe.durability as i32;
|
||||
}
|
||||
if self.buffs.inner_quiet > 10 {
|
||||
self.buffs.inner_quiet = 10;
|
||||
}
|
||||
|
||||
self.actions.push(action);
|
||||
return self;
|
||||
|
|
@ -95,20 +120,28 @@ impl<'a> Debug for Craft<'a> {
|
|||
.field("durability", &format!("{:?}/{:?}", &self.durability, &self.recipe.durability))
|
||||
// .field("cp", &format!("{:?}/{:?}", &self.cp, &self.stats.max_cp))
|
||||
;
|
||||
binding.field("actions",&self.actions);
|
||||
binding.field("actions", &self.actions);
|
||||
binding.finish()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
impl<'a> Display for Craft<'a> {
|
||||
fn fmt(&self, f: &mut Formatter)-> std::fmt::Result {
|
||||
fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
|
||||
f.debug_struct("Craft")
|
||||
.field("step_count", &self.step_count)
|
||||
.field("progression", &format!("{:?}/{:?}", &self.progression, &self.recipe.progress))
|
||||
.field("quality", &format!("{:?}/{:?}", &self.quality, &self.recipe.quality))
|
||||
.field("durability", &format!("{:?}/{:?}", &self.durability, &self.recipe.durability))
|
||||
.field(
|
||||
"progression",
|
||||
&format!("{:?}/{:?}", &self.progression, &self.recipe.progress),
|
||||
)
|
||||
.field(
|
||||
"quality",
|
||||
&format!("{:?}/{:?}", &self.quality, &self.recipe.quality),
|
||||
)
|
||||
.field(
|
||||
"durability",
|
||||
&format!("{:?}/{:?}", &self.durability, &self.recipe.durability),
|
||||
)
|
||||
.field("cp", &format!("{:?}/{:?}", &self.cp, &self.stats.max_cp))
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
163
src/io.rs
163
src/io.rs
|
|
@ -1,8 +1,8 @@
|
|||
use crate::Craft;
|
||||
use core::fmt::Display;
|
||||
use clap::Parser;
|
||||
use core::fmt::Display;
|
||||
|
||||
#[cfg(not(feature="no_python"))]
|
||||
#[cfg(not(feature = "no_python"))]
|
||||
use pyo3::prelude::*;
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
|
|
@ -10,7 +10,7 @@ pub struct Parameters {
|
|||
pub threads: usize,
|
||||
pub verbose: u8,
|
||||
pub depth: u32,
|
||||
pub desperate:bool,
|
||||
pub desperate: bool,
|
||||
pub byregot_step: u8,
|
||||
}
|
||||
|
||||
|
|
@ -28,7 +28,7 @@ pub struct Args {
|
|||
/// The ml file name
|
||||
#[arg(short, long, default_value_t = String::from("craft.toml"))]
|
||||
pub file_name: String,
|
||||
|
||||
|
||||
/// The verbose flag
|
||||
#[arg(short, long, action = clap::ArgAction::Count)]
|
||||
pub verbose: u8,
|
||||
|
|
@ -42,20 +42,19 @@ pub struct Args {
|
|||
pub threads: usize,
|
||||
|
||||
/// Desperate mode, will try to finish the craft above all
|
||||
#[arg(short='D', long, default_value_t = false)]
|
||||
#[arg(short = 'D', long, default_value_t = false)]
|
||||
pub desperate: bool,
|
||||
|
||||
/// Long mode, will try to find more solutions, at the expense of time
|
||||
#[arg(short='l', long, default_value_t = false)]
|
||||
#[arg(short = 'l', long, default_value_t = false)]
|
||||
pub long: bool,
|
||||
}
|
||||
|
||||
|
||||
/// A final stripped down version of a craft
|
||||
/// used for final print and talking with python
|
||||
#[derive(Debug)]
|
||||
#[pyclass]
|
||||
pub struct SolverResult{
|
||||
pub struct SolverResult {
|
||||
#[pyo3(get)]
|
||||
pub steps: u32,
|
||||
#[pyo3(get)]
|
||||
|
|
@ -65,15 +64,15 @@ pub struct SolverResult{
|
|||
#[pyo3(get)]
|
||||
pub durability: i32,
|
||||
#[pyo3(get)]
|
||||
pub cp:i32,
|
||||
pub cp: i32,
|
||||
#[pyo3(get)]
|
||||
pub total_cp:u32,
|
||||
pub total_cp: u32,
|
||||
#[pyo3(get)]
|
||||
pub total_progression:u32,
|
||||
pub total_progression: u32,
|
||||
#[pyo3(get)]
|
||||
pub total_quality:u32,
|
||||
pub total_quality: u32,
|
||||
#[pyo3(get)]
|
||||
pub total_durability:u32,
|
||||
pub total_durability: u32,
|
||||
#[pyo3(get)]
|
||||
pub actions: Vec<String>,
|
||||
#[pyo3(get)]
|
||||
|
|
@ -85,92 +84,108 @@ pub struct SolverResult{
|
|||
}
|
||||
|
||||
/// Pretty display for SolverResult
|
||||
impl Display for SolverResult{
|
||||
fn fmt(&self, _f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
|
||||
println!("{:?}",self.actions);
|
||||
impl Display for SolverResult {
|
||||
fn fmt(&self, _f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
|
||||
println!("{:?}", self.actions);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
//#[pymethods]
|
||||
impl SolverResult{
|
||||
pub fn from_craft(craft: & Craft,step1_solutions : usize,step2_solutions : usize, found_100_percent: bool)->SolverResult{
|
||||
// Todo: recreate actions
|
||||
// Where steps ?
|
||||
let mut actions = craft.actions.iter().map(|action|
|
||||
format!("{}",action.short_name)
|
||||
).collect::<Vec<String>>();
|
||||
let arg = (craft.recipe.progress as f32 - craft.progression as f32) / craft.get_base_progression() as f32;
|
||||
if 0.0 < arg && arg < 1.2 { actions.push("basicSynth2".to_string()); }
|
||||
if 1.2 <= arg && arg < 1.8 { actions.push("carefulSynthesis".to_string()); }
|
||||
impl SolverResult {
|
||||
pub fn from_craft(
|
||||
craft: &Craft,
|
||||
step1_solutions: usize,
|
||||
step2_solutions: usize,
|
||||
found_100_percent: bool,
|
||||
) -> SolverResult {
|
||||
let mut actions = craft
|
||||
.actions
|
||||
.iter()
|
||||
.map(|action| format!("{}", action.short_name))
|
||||
.collect::<Vec<String>>();
|
||||
let arg = (craft.recipe.progress as f32 - craft.progression as f32)
|
||||
/ craft.get_base_progression() as f32;
|
||||
if 0.0 < arg && arg < 1.2 {
|
||||
actions.push("basicSynth2".to_string());
|
||||
}
|
||||
if 1.2 <= arg && arg < 1.8 {
|
||||
actions.push("carefulSynthesis".to_string());
|
||||
}
|
||||
if 1.8 <= arg && arg < 2.0 {
|
||||
actions.push("observe".to_string());
|
||||
actions.push("focusedSynthesis".to_string());
|
||||
}
|
||||
SolverResult{
|
||||
steps:craft.step_count,
|
||||
SolverResult {
|
||||
steps: craft.step_count,
|
||||
progression: craft.progression,
|
||||
quality:craft.quality,
|
||||
durability:craft.durability,
|
||||
actions:actions,
|
||||
quality: craft.quality,
|
||||
durability: craft.durability,
|
||||
actions: actions,
|
||||
step1_solutions,
|
||||
step2_solutions,
|
||||
found_100_percent,
|
||||
total_progression:craft.recipe.progress,
|
||||
total_quality:craft.recipe.quality,
|
||||
total_durability:craft.recipe.durability,
|
||||
total_progression: craft.recipe.progress,
|
||||
total_quality: craft.recipe.quality,
|
||||
total_durability: craft.recipe.durability,
|
||||
cp: craft.cp,
|
||||
total_cp : craft.stats.max_cp,
|
||||
total_cp: craft.stats.max_cp,
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
#[pymethods]
|
||||
impl SolverResult{
|
||||
impl SolverResult {
|
||||
#[staticmethod]
|
||||
pub fn default()->Self{
|
||||
Self{
|
||||
steps:0,
|
||||
pub fn default() -> Self {
|
||||
Self {
|
||||
steps: 0,
|
||||
progression: 0,
|
||||
quality:0,
|
||||
durability:0,
|
||||
total_progression:0,
|
||||
total_quality:0,
|
||||
total_durability:0,
|
||||
actions:vec!["Act1".to_string(),"Act2".to_string()],
|
||||
step1_solutions:0,
|
||||
step2_solutions:0,
|
||||
found_100_percent:false,
|
||||
cp:0,
|
||||
total_cp:0,
|
||||
quality: 0,
|
||||
durability: 0,
|
||||
total_progression: 0,
|
||||
total_quality: 0,
|
||||
total_durability: 0,
|
||||
actions: vec!["Act1".to_string(), "Act2".to_string()],
|
||||
step1_solutions: 0,
|
||||
step2_solutions: 0,
|
||||
found_100_percent: false,
|
||||
cp: 0,
|
||||
total_cp: 0,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn pretty_print(&self){
|
||||
println!("Quality: [{}/{}] | Durability: [{}/{}] | Cp : [{}/{}] | Steps : {}",
|
||||
self.quality, self.total_quality, self.durability, self.total_durability, self.cp, self.total_cp, self.steps);
|
||||
pub fn pretty_print(&self) {
|
||||
println!(
|
||||
"Quality: [{}/{}] | Durability: [{}/{}] | Cp : [{}/{}] | Steps : {}",
|
||||
self.quality,
|
||||
self.total_quality,
|
||||
self.durability,
|
||||
self.total_durability,
|
||||
self.cp,
|
||||
self.total_cp,
|
||||
self.steps
|
||||
);
|
||||
println!("{:?}", self.actions);
|
||||
}
|
||||
}
|
||||
|
||||
impl Parameters{
|
||||
pub fn from_args(args:& Args) -> Self{
|
||||
Self{
|
||||
depth: if args.desperate{11}else{8},
|
||||
impl Parameters {
|
||||
pub fn from_args(args: &Args) -> Self {
|
||||
Self {
|
||||
depth: if args.desperate { 11 } else { 8 },
|
||||
threads: args.threads,
|
||||
verbose: args.verbose,
|
||||
desperate: args.desperate,
|
||||
byregot_step: if args.long{6}else{8}
|
||||
byregot_step: if args.long { 6 } else { 8 },
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
////// Python Bindings //////
|
||||
|
||||
/// A Python module implemented in Rust.
|
||||
#[cfg(not(feature="no_python"))]
|
||||
#[cfg(not(feature = "no_python"))]
|
||||
#[pymodule]
|
||||
fn xiv_craft_solver(_py: Python, m: &PyModule) -> PyResult<()> {
|
||||
m.add_function(wrap_pyfunction!(test_result, m)?)?;
|
||||
|
|
@ -179,39 +194,39 @@ fn xiv_craft_solver(_py: Python, m: &PyModule) -> PyResult<()> {
|
|||
}
|
||||
|
||||
///
|
||||
#[cfg(not(feature="no_python"))]
|
||||
#[cfg(not(feature = "no_python"))]
|
||||
#[pyfunction]
|
||||
pub fn test_result()-> SolverResult {
|
||||
pub fn test_result() -> SolverResult {
|
||||
SolverResult::default()
|
||||
}
|
||||
|
||||
/// Create a stat struct stats with the base values
|
||||
#[cfg(not(feature="no_python"))]
|
||||
use crate::{Recipe,Stats,solve_craft};
|
||||
#[cfg(not(feature = "no_python"))]
|
||||
use crate::{solve_craft, Recipe, Stats};
|
||||
|
||||
#[cfg(not(feature="no_python"))]
|
||||
#[cfg(not(feature = "no_python"))]
|
||||
#[pyfunction]
|
||||
pub fn solve_from_python(values : &PyAny)->PyResult<Option<Vec<SolverResult>>>{
|
||||
pub fn solve_from_python(values: &PyAny) -> PyResult<Option<Vec<SolverResult>>> {
|
||||
// // Create Recipe
|
||||
let recipe = Recipe{
|
||||
let recipe = Recipe {
|
||||
durability: values.getattr("durability")?.extract()?,
|
||||
progress: values.getattr("progress")?.extract()?,
|
||||
progress: values.getattr("progress")?.extract()?,
|
||||
progress_divider: values.getattr("progress_divider")?.extract()?,
|
||||
progress_modifier: values.getattr("progress_modifier")?.extract()?,
|
||||
quality: values.getattr("quality")?.extract()?,
|
||||
quality_divider:values.getattr("quality_divider")?.extract()?,
|
||||
quality_modifier:values.getattr("quality_modifier")?.extract()?,
|
||||
quality_divider: values.getattr("quality_divider")?.extract()?,
|
||||
quality_modifier: values.getattr("quality_modifier")?.extract()?,
|
||||
};
|
||||
|
||||
// Create Stats
|
||||
let stats = Stats{
|
||||
let stats = Stats {
|
||||
craftsmanship: values.getattr("craftsmanship")?.extract()?,
|
||||
control: values.getattr("control")?.extract()?,
|
||||
max_cp: values.getattr("max_cp")?.extract()?,
|
||||
};
|
||||
|
||||
// Create parameters
|
||||
let param = Parameters{
|
||||
let param = Parameters {
|
||||
depth: values.getattr("depth")?.extract()?,
|
||||
byregot_step: values.getattr("byregot_step")?.extract()?,
|
||||
desperate: values.getattr("desperate")?.extract()?,
|
||||
|
|
@ -222,4 +237,4 @@ pub fn solve_from_python(values : &PyAny)->PyResult<Option<Vec<SolverResult>>>{
|
|||
// println!("{:?} len: {:?} ",values,values.getattr("len()"));
|
||||
let res = solve_craft(recipe, stats, param);
|
||||
Ok(res)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
246
src/lib.rs
246
src/lib.rs
|
|
@ -1,28 +1,32 @@
|
|||
use crate::io::SolverResult;
|
||||
use crate::{
|
||||
craft::Craft,
|
||||
specs::{Recipe,Stats},
|
||||
io::Parameters,
|
||||
specs::{Recipe, Stats},
|
||||
};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use threadpool::ThreadPool;
|
||||
use std::sync::{Arc,Mutex};
|
||||
|
||||
mod solver;
|
||||
mod specs;
|
||||
pub mod action;
|
||||
pub mod craft;
|
||||
pub mod io;
|
||||
mod solver;
|
||||
mod specs;
|
||||
|
||||
/// Solve the craft with given arguments, this functions calls threads and must own it's values
|
||||
pub fn solve_craft<'a>(recipe: Recipe, stats: Stats, params: Parameters) -> Option<Vec<SolverResult>>{
|
||||
pub fn solve_craft<'a>(
|
||||
recipe: Recipe,
|
||||
stats: Stats,
|
||||
params: Parameters,
|
||||
) -> Option<Vec<SolverResult>> {
|
||||
// Load the craft with given arguments
|
||||
let craft = Craft::new(recipe,stats,params);
|
||||
let craft = Craft::new(recipe, stats, params);
|
||||
|
||||
// Start a threadpool
|
||||
let pool = ThreadPool::new(params.threads);
|
||||
|
||||
#[cfg(feature = "verbose")]
|
||||
if params.verbose>0{
|
||||
if params.verbose > 0 {
|
||||
println!("[P1] Starting phase 1...");
|
||||
}
|
||||
|
||||
|
|
@ -30,11 +34,23 @@ pub fn solve_craft<'a>(recipe: Recipe, stats: Stats, params: Parameters) -> Opti
|
|||
let nb_p1 = phase1_routes.len();
|
||||
|
||||
#[cfg(feature = "verbose")]
|
||||
if params.verbose>0{
|
||||
println!("[P1] Found {} routes, testing them all...",phase1_routes.len());
|
||||
if params.verbose>1{ for r in &phase1_routes{
|
||||
println!("[P1] {:?} p:{}% q:{}% c:{} d:{}",r.actions,r.progression,r.quality * 100 / r.recipe.quality,r.cp,r.durability);
|
||||
}}
|
||||
if params.verbose > 0 {
|
||||
println!(
|
||||
"[P1] Found {} routes, testing them all...",
|
||||
phase1_routes.len()
|
||||
);
|
||||
if params.verbose > 1 {
|
||||
for r in &phase1_routes {
|
||||
println!(
|
||||
"[P1] {:?} p:{}% q:{}% c:{} d:{}",
|
||||
r.actions,
|
||||
r.progression,
|
||||
r.quality * 100 / r.recipe.quality,
|
||||
r.cp,
|
||||
r.durability
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Core algorithm, fill all found routes with the best route (doesn't branch, just replace)
|
||||
|
|
@ -44,7 +60,7 @@ pub fn solve_craft<'a>(recipe: Recipe, stats: Stats, params: Parameters) -> Opti
|
|||
let _phase2_routes = Arc::clone(&arc_phase2_routes);
|
||||
|
||||
pool.execute(move || {
|
||||
if let Some(mut _route) = solver::generate_routes_phase2(route){
|
||||
if let Some(mut _route) = solver::generate_routes_phase2(route) {
|
||||
let mut shared = _phase2_routes.lock().unwrap();
|
||||
shared.append(&mut _route);
|
||||
};
|
||||
|
|
@ -56,145 +72,207 @@ pub fn solve_craft<'a>(recipe: Recipe, stats: Stats, params: Parameters) -> Opti
|
|||
let nb_p2 = phase2_routes.len();
|
||||
|
||||
// Drop on empty results
|
||||
if phase2_routes.len()==0{
|
||||
return None
|
||||
if phase2_routes.len() == 0 {
|
||||
return None;
|
||||
}
|
||||
|
||||
// Print the results if verbose
|
||||
#[cfg(feature = "verbose")]
|
||||
if params.verbose>0{
|
||||
println!("[P2] Found {} solutions, sorting",phase2_routes.len());
|
||||
if params.verbose>1{ for r in phase2_routes.iter(){
|
||||
println!("[P2] {:?} p:{}% q:{}% d:{}", r.actions, r.progression * 100 / r.recipe.progress, r.quality * 100 / r.recipe.quality, r.durability);
|
||||
}}
|
||||
if params.verbose > 0 {
|
||||
println!("[P2] Found {} solutions, sorting", phase2_routes.len());
|
||||
if params.verbose > 1 {
|
||||
for r in phase2_routes.iter() {
|
||||
println!(
|
||||
"[P2] {:?} p:{}% q:{}% d:{}",
|
||||
r.actions,
|
||||
r.progression * 100 / r.recipe.progress,
|
||||
r.quality * 100 / r.recipe.quality,
|
||||
r.durability
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Prune the results for analysis
|
||||
// let mut valid_routes : Vec<Craft> = vec![];
|
||||
let mut valid_solutions: Vec<SolverResult> = vec![];
|
||||
for route in phase2_routes.iter(){
|
||||
if route.quality>=route.recipe.quality{
|
||||
for route in phase2_routes.iter() {
|
||||
if route.quality >= route.recipe.quality {
|
||||
// valid_routes.push(route.clone());
|
||||
valid_solutions.push(SolverResult::from_craft(route,nb_p1,nb_p2,true));
|
||||
valid_solutions.push(SolverResult::from_craft(route, nb_p1, nb_p2, true));
|
||||
}
|
||||
}
|
||||
// If no craft can make it to 100% HQ, fallback to base results
|
||||
if valid_solutions.len()==0{
|
||||
for route in phase2_routes.iter(){valid_solutions.push(SolverResult::from_craft(route,nb_p1,nb_p2,false));}
|
||||
if valid_solutions.len() == 0 {
|
||||
for route in phase2_routes.iter() {
|
||||
valid_solutions.push(SolverResult::from_craft(route, nb_p1, nb_p2, false));
|
||||
}
|
||||
}
|
||||
|
||||
Some(valid_solutions)
|
||||
}
|
||||
|
||||
/// Load the config from args and make a craft from it
|
||||
pub fn load_from_config<'a>(recipe_name: &str, file_name: &str, character_name: &str) -> (Recipe,Stats) {
|
||||
pub fn load_from_config<'a>(
|
||||
recipe_name: &str,
|
||||
file_name: &str,
|
||||
character_name: &str,
|
||||
) -> (Recipe, Stats) {
|
||||
//read craft.toml
|
||||
let config: toml::Value = toml::from_str(
|
||||
&std::fs::read_to_string(file_name)
|
||||
.expect(&format!("Can't open {}",file_name))
|
||||
).unwrap();
|
||||
&std::fs::read_to_string(file_name).expect(&format!("Can't open {}", file_name)),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let recp = match config.get(recipe_name){
|
||||
let recp = match config.get(recipe_name) {
|
||||
Some(r) => r,
|
||||
None => panic!("Can't find value '{}' in '{}'",recipe_name, file_name)
|
||||
None => panic!("Can't find value '{}' in '{}'", recipe_name, file_name),
|
||||
};
|
||||
|
||||
// Load receipe values
|
||||
let recipe = Recipe {
|
||||
durability: recp
|
||||
.get("durability").expect(&format!("Can't find 'durability' in recipe '{}' on file '{}'",
|
||||
recipe_name,file_name))
|
||||
.as_integer().expect("Can't convert durability as an integer") as u32,
|
||||
.get("durability")
|
||||
.expect(&format!(
|
||||
"Can't find 'durability' in recipe '{}' on file '{}'",
|
||||
recipe_name, file_name
|
||||
))
|
||||
.as_integer()
|
||||
.expect("Can't convert durability as an integer") as u32,
|
||||
progress: recp
|
||||
.get("progress").expect(&format!("Can't find 'progress' in recipe '{}' on '{}'",
|
||||
recipe_name,file_name))
|
||||
.as_integer().expect("Can't convert progress as an integer") as u32,
|
||||
.get("progress")
|
||||
.expect(&format!(
|
||||
"Can't find 'progress' in recipe '{}' on '{}'",
|
||||
recipe_name, file_name
|
||||
))
|
||||
.as_integer()
|
||||
.expect("Can't convert progress as an integer") as u32,
|
||||
quality: recp
|
||||
.get("quality").expect(&format!("Can't find 'quality' in recipe '{}' on '{}'",
|
||||
recipe_name,file_name))
|
||||
.as_integer().expect("Can't convert quality as an integer") as u32,
|
||||
.get("quality")
|
||||
.expect(&format!(
|
||||
"Can't find 'quality' in recipe '{}' on '{}'",
|
||||
recipe_name, file_name
|
||||
))
|
||||
.as_integer()
|
||||
.expect("Can't convert quality as an integer") as u32,
|
||||
progress_divider: recp
|
||||
.get("progress_divider").expect(&format!("Can't find 'progress_divider' in recipe '{}' on '{}'",
|
||||
recipe_name,file_name))
|
||||
.as_integer().expect("Can't convert progress_divider as an integer") as u32,
|
||||
.get("progress_divider")
|
||||
.expect(&format!(
|
||||
"Can't find 'progress_divider' in recipe '{}' on '{}'",
|
||||
recipe_name, file_name
|
||||
))
|
||||
.as_integer()
|
||||
.expect("Can't convert progress_divider as an integer")
|
||||
as u32,
|
||||
quality_divider: recp
|
||||
.get("quality_divider").expect(&format!("Can't find 'quality_divider' in recipe '{}' on '{}'",
|
||||
recipe_name,file_name))
|
||||
.as_integer().expect("Can't convert quality_divider as an integer") as u32,
|
||||
.get("quality_divider")
|
||||
.expect(&format!(
|
||||
"Can't find 'quality_divider' in recipe '{}' on '{}'",
|
||||
recipe_name, file_name
|
||||
))
|
||||
.as_integer()
|
||||
.expect("Can't convert quality_divider as an integer") as u32,
|
||||
progress_modifier: recp
|
||||
.get("progress_modifier").expect(&format!("Can't find 'progress_modifier' in recipe '{}' on '{}'",
|
||||
recipe_name,file_name))
|
||||
.as_integer().expect("Can't convert progress_modifier as an integer") as u32,
|
||||
.get("progress_modifier")
|
||||
.expect(&format!(
|
||||
"Can't find 'progress_modifier' in recipe '{}' on '{}'",
|
||||
recipe_name, file_name
|
||||
))
|
||||
.as_integer()
|
||||
.expect("Can't convert progress_modifier as an integer")
|
||||
as u32,
|
||||
quality_modifier: recp
|
||||
.get("quality_modifier").expect(&format!("Can't find 'quality_modifier' in recipe '{}' on '{}'",
|
||||
recipe_name,file_name))
|
||||
.as_integer().expect("Can't convert quality_modifier as an integer") as u32,
|
||||
.get("quality_modifier")
|
||||
.expect(&format!(
|
||||
"Can't find 'quality_modifier' in recipe '{}' on '{}'",
|
||||
recipe_name, file_name
|
||||
))
|
||||
.as_integer()
|
||||
.expect("Can't convert quality_modifier as an integer")
|
||||
as u32,
|
||||
};
|
||||
|
||||
let cfg = match config.get(character_name){
|
||||
let cfg = match config.get(character_name) {
|
||||
Some(c) => c,
|
||||
None => panic!("Can't find '{}' in file '{}'",character_name,file_name),
|
||||
None => panic!("Can't find '{}' in file '{}'", character_name, file_name),
|
||||
};
|
||||
let stats = Stats {
|
||||
craftsmanship: cfg
|
||||
.get("craftsmanship").expect(&format!("Can't find 'craftsmanship' in character '{}' on file '{}'",
|
||||
character_name,file_name))
|
||||
.as_integer().expect("Can't convert craftsmanship as an integer") as u32,
|
||||
.get("craftsmanship")
|
||||
.expect(&format!(
|
||||
"Can't find 'craftsmanship' in character '{}' on file '{}'",
|
||||
character_name, file_name
|
||||
))
|
||||
.as_integer()
|
||||
.expect("Can't convert craftsmanship as an integer") as u32,
|
||||
control: cfg
|
||||
.get("control").expect(&format!("Can't find 'control' in character '{}' on file '{}'",
|
||||
character_name,file_name))
|
||||
.as_integer().expect("Can't convert control as an integer") as u32,
|
||||
.get("control")
|
||||
.expect(&format!(
|
||||
"Can't find 'control' in character '{}' on file '{}'",
|
||||
character_name, file_name
|
||||
))
|
||||
.as_integer()
|
||||
.expect("Can't convert control as an integer") as u32,
|
||||
max_cp: cfg
|
||||
.get("max_cp").expect(&format!("Can't find 'max_cp' in character '{}' on file '{}'",
|
||||
character_name,file_name))
|
||||
.as_integer().expect("Can't convert max_cp as an integer") as u32,
|
||||
.get("max_cp")
|
||||
.expect(&format!(
|
||||
"Can't find 'max_cp' in character '{}' on file '{}'",
|
||||
character_name, file_name
|
||||
))
|
||||
.as_integer()
|
||||
.expect("Can't convert max_cp as an integer") as u32,
|
||||
};
|
||||
(recipe,stats)
|
||||
(recipe, stats)
|
||||
}
|
||||
|
||||
/// Print all routes in the vect, verbose
|
||||
pub fn print_routes<'a>(routes: & Option<Vec<SolverResult>>){
|
||||
match routes{
|
||||
pub fn print_routes<'a>(routes: &Option<Vec<SolverResult>>) {
|
||||
match routes {
|
||||
Some(r) => {
|
||||
println!("Showing {} routes",r.len());
|
||||
for c in r.iter(){
|
||||
println!("\n[{}¤][{}@][{}#] {:?} ",c.quality,c.durability,c.steps,c.actions)
|
||||
println!("Showing {} routes", r.len());
|
||||
for c in r.iter() {
|
||||
println!(
|
||||
"\n[{}¤][{}@][{}#] {:?} ",
|
||||
c.quality, c.durability, c.steps, c.actions
|
||||
)
|
||||
}
|
||||
},
|
||||
None => println!("No routes to print")
|
||||
}
|
||||
None => println!("No routes to print"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Find the route with the least amount of steps
|
||||
pub fn find_fast_route(routes: &Option<Vec<SolverResult>>) -> Option<&SolverResult>{
|
||||
pub fn find_fast_route(routes: &Option<Vec<SolverResult>>) -> Option<&SolverResult> {
|
||||
match routes {
|
||||
Some(_routes) => {
|
||||
if _routes.len()>0{
|
||||
if _routes.len() > 0 {
|
||||
_routes.iter().min_by_key(|key| key.steps)
|
||||
} else { None }
|
||||
},
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
None => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Find the route with the maximum amount of quality
|
||||
pub fn find_quality_route(routes: &Option<Vec<SolverResult>>) -> Option<&SolverResult>{
|
||||
pub fn find_quality_route(routes: &Option<Vec<SolverResult>>) -> Option<&SolverResult> {
|
||||
match routes {
|
||||
Some(_routes) => _routes.iter().max_by_key(|key| key.quality),
|
||||
None => None,
|
||||
Some(_routes) => _routes.iter().max_by_key(|key| key.quality),
|
||||
None => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Find the route with the maximum of durability left
|
||||
pub fn find_safe_route(routes: &Option<Vec<SolverResult>>) -> Option<&SolverResult>{
|
||||
pub fn find_safe_route(routes: &Option<Vec<SolverResult>>) -> Option<&SolverResult> {
|
||||
match routes {
|
||||
Some(_routes) => {
|
||||
if _routes.len()>0{
|
||||
Some(_routes) => {
|
||||
if _routes.len() > 0 {
|
||||
_routes.iter().max_by_key(|key| key.durability)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
None => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
146
src/solver.rs
146
src/solver.rs
|
|
@ -1,47 +1,83 @@
|
|||
use std::collections::VecDeque;
|
||||
use std::ops::Not;
|
||||
use crate::action::{Action, ACTIONS};
|
||||
use crate::craft::Craft;
|
||||
use crate::specs::Success;
|
||||
use std::collections::VecDeque;
|
||||
use std::ops::Not;
|
||||
|
||||
macro_rules! action_vec {
|
||||
($($tt:expr),*) => { vec![ $(Some(&$tt),)*]};
|
||||
}
|
||||
|
||||
/// Find the next authorised action for this step of the craft
|
||||
pub fn next_action_picker_1<'a>(craft: & Craft<'a>) -> Vec<Option<&'a Action>> {
|
||||
if craft.success != Success::Pending { return vec![None]; }
|
||||
pub fn next_action_picker_1<'a>(craft: &Craft<'a>) -> Vec<Option<&'a Action>> {
|
||||
if craft.success != Success::Pending {
|
||||
return vec![None];
|
||||
}
|
||||
let mut available_actions = Vec::<Option<&'a Action>>::new();
|
||||
let mut forbidden_actions = Vec::<Option<&'a Action>>::new();
|
||||
|
||||
// Optimize the first three steps for massive time save
|
||||
if craft.step_count == 0 { return action_vec![ACTIONS.muscle_memory]; }
|
||||
if craft.step_count == 1 { return action_vec![ACTIONS.manipulation]; }
|
||||
if craft.step_count == 0 {
|
||||
return action_vec![ACTIONS.muscle_memory];
|
||||
}
|
||||
if craft.step_count == 1 {
|
||||
return action_vec![ACTIONS.manipulation];
|
||||
}
|
||||
|
||||
// Prune some actions if not requested by --long
|
||||
if craft.step_count == 2 { return action_vec![/*ACTIONS.waste_not, ACTIONS.waste_not_ii, */ACTIONS.veneration]; }
|
||||
if craft.step_count == 3 { available_actions.append(&mut action_vec![ACTIONS.waste_not_ii/*,ACTIONS.waste_not*/]) }
|
||||
if craft.step_count == 2 {
|
||||
return action_vec![/*ACTIONS.waste_not, ACTIONS.waste_not_ii, */ ACTIONS.veneration];
|
||||
}
|
||||
if craft.step_count == 3 {
|
||||
available_actions.append(&mut action_vec![
|
||||
ACTIONS.waste_not_ii /*,ACTIONS.waste_not*/
|
||||
])
|
||||
}
|
||||
|
||||
// Groundwork mostly for wn / mm
|
||||
if craft.buffs.waste_not > 0 || craft.buffs.muscle_memory > 0 { available_actions.append(&mut action_vec![ACTIONS.groundwork]) }
|
||||
|
||||
if craft.buffs.waste_not > 0 || craft.buffs.muscle_memory > 0 {
|
||||
available_actions.append(&mut action_vec![ACTIONS.groundwork])
|
||||
}
|
||||
|
||||
// Forbidding actions depending on buffs
|
||||
if craft.buffs.muscle_memory > 0 { forbidden_actions.append(&mut action_vec![ACTIONS.basic_synthesis,ACTIONS.careful_synthesis,ACTIONS.prudent_synthesis,ACTIONS.delicate_synthesis]) }
|
||||
if craft.buffs.waste_not > 0 { forbidden_actions.append(&mut action_vec![ACTIONS.prudent_synthesis]) }
|
||||
available_actions.append(&mut action_vec![ACTIONS.basic_synthesis,ACTIONS.careful_synthesis,ACTIONS.prudent_synthesis,ACTIONS.delicate_synthesis]);
|
||||
|
||||
if craft.buffs.muscle_memory > 0 {
|
||||
forbidden_actions.append(&mut action_vec![
|
||||
ACTIONS.basic_synthesis,
|
||||
ACTIONS.careful_synthesis,
|
||||
ACTIONS.prudent_synthesis,
|
||||
ACTIONS.delicate_synthesis
|
||||
])
|
||||
}
|
||||
if craft.buffs.waste_not > 0 {
|
||||
forbidden_actions.append(&mut action_vec![ACTIONS.prudent_synthesis])
|
||||
}
|
||||
available_actions.append(&mut action_vec![
|
||||
ACTIONS.basic_synthesis,
|
||||
ACTIONS.careful_synthesis,
|
||||
ACTIONS.prudent_synthesis,
|
||||
ACTIONS.delicate_synthesis
|
||||
]);
|
||||
|
||||
// ACTIONS.groundwork for the --pls
|
||||
if craft.args.desperate{
|
||||
if craft.args.desperate {
|
||||
available_actions.append(&mut action_vec![ACTIONS.groundwork]);
|
||||
}
|
||||
|
||||
// For long first run
|
||||
if craft.step_count > 8 {available_actions.append(&mut action_vec![ACTIONS.waste_not_ii, ACTIONS.waste_not])};
|
||||
if craft.step_count > 8 {
|
||||
available_actions.append(&mut action_vec![ACTIONS.waste_not_ii, ACTIONS.waste_not])
|
||||
};
|
||||
|
||||
// Pruning the actions with the forbidden ones
|
||||
let mut result_actions = Vec::<Option<&'a Action>>::new();
|
||||
for action in available_actions {
|
||||
if !forbidden_actions.contains(&action) && action.unwrap().can_use(&craft) && result_actions.iter().any(|x| x.unwrap() == action.unwrap()).not() {
|
||||
if !forbidden_actions.contains(&action)
|
||||
&& action.unwrap().can_use(&craft)
|
||||
&& result_actions
|
||||
.iter()
|
||||
.any(|x| x.unwrap() == action.unwrap())
|
||||
.not()
|
||||
{
|
||||
result_actions.push(action);
|
||||
}
|
||||
}
|
||||
|
|
@ -49,7 +85,6 @@ pub fn next_action_picker_1<'a>(craft: & Craft<'a>) -> Vec<Option<&'a Action>> {
|
|||
result_actions
|
||||
}
|
||||
|
||||
|
||||
/// Find all routes that can finish in one more action
|
||||
pub fn generate_routes_phase1<'a>(craft: Craft<'a>) -> Vec<Craft<'a>> {
|
||||
let mut queue = Vec::new();
|
||||
|
|
@ -57,15 +92,16 @@ pub fn generate_routes_phase1<'a>(craft: Craft<'a>) -> Vec<Craft<'a>> {
|
|||
let mut routes = Vec::new();
|
||||
while !queue.is_empty() {
|
||||
let craft = queue.pop().unwrap();
|
||||
for action in next_action_picker_1(& craft) {
|
||||
for action in next_action_picker_1(&craft) {
|
||||
let mut craft = craft.clone();
|
||||
|
||||
match action{
|
||||
match action {
|
||||
Some(a) => craft.run_action(a),
|
||||
None => break,
|
||||
};
|
||||
|
||||
let remaining_prog = (craft.recipe.progress as f32 - craft.progression as f32) / craft.get_base_progression() as f32;
|
||||
let remaining_prog = (craft.recipe.progress as f32 - craft.progression as f32)
|
||||
/ craft.get_base_progression() as f32;
|
||||
if remaining_prog <= 2.0 {
|
||||
if remaining_prog <= 0.0 {
|
||||
continue;
|
||||
|
|
@ -85,33 +121,46 @@ pub fn generate_routes_phase1<'a>(craft: Craft<'a>) -> Vec<Craft<'a>> {
|
|||
// 8 Seemed to be a good initial guess with enouth to use a good amount of WN / WNII to get close
|
||||
// A higher value will yield more initial guesses with minimal benefits
|
||||
// A lover value will yield less initial guesses and might spent too much CP to get to the required progression
|
||||
if craft.step_count < craft.args.depth { queue.push(craft); }
|
||||
if craft.step_count < craft.args.depth {
|
||||
queue.push(craft);
|
||||
}
|
||||
}
|
||||
}
|
||||
routes
|
||||
}
|
||||
|
||||
|
||||
/// Find the list of authorised actions for this step
|
||||
pub fn next_action_phase_2<'a>(craft: & Craft<'a>) -> Vec<Option<&'a Action>> {
|
||||
let mut available_actions = vec![&ACTIONS.basic_touch, &ACTIONS.prudent_touch, &ACTIONS.preparatory_touch];
|
||||
pub fn next_action_phase_2<'a>(craft: &Craft<'a>) -> Vec<Option<&'a Action>> {
|
||||
let mut available_actions = vec![
|
||||
&ACTIONS.basic_touch,
|
||||
&ACTIONS.prudent_touch,
|
||||
&ACTIONS.preparatory_touch,
|
||||
];
|
||||
let mut forbidden_actions = Vec::new();
|
||||
if craft.success != Success::Pending { return vec![None]; }
|
||||
if craft.success != Success::Pending {
|
||||
return vec![None];
|
||||
}
|
||||
if craft.buffs.innovation > 0 {
|
||||
forbidden_actions.push(&ACTIONS.innovation);
|
||||
} else {
|
||||
if craft.buffs.inner_quiet >= 2 {
|
||||
forbidden_actions.append(&mut vec![&ACTIONS.basic_touch,
|
||||
&ACTIONS.standard_touch,
|
||||
&ACTIONS.advanced_touch,
|
||||
&ACTIONS.trained_finesse,
|
||||
&ACTIONS.prudent_touch,
|
||||
&ACTIONS.preparatory_touch,
|
||||
&ACTIONS.byregot_blessing]);
|
||||
forbidden_actions.append(&mut vec![
|
||||
&ACTIONS.basic_touch,
|
||||
&ACTIONS.standard_touch,
|
||||
&ACTIONS.advanced_touch,
|
||||
&ACTIONS.trained_finesse,
|
||||
&ACTIONS.prudent_touch,
|
||||
&ACTIONS.preparatory_touch,
|
||||
&ACTIONS.byregot_blessing,
|
||||
]);
|
||||
}
|
||||
available_actions.push(&ACTIONS.innovation);
|
||||
}
|
||||
if craft.buffs.manipulation == 0 && craft.buffs.basic_touch == 0 && craft.buffs.standard_touch == 0 && craft.buffs.inner_quiet < 8 {
|
||||
if craft.buffs.manipulation == 0
|
||||
&& craft.buffs.basic_touch == 0
|
||||
&& craft.buffs.standard_touch == 0
|
||||
&& craft.buffs.inner_quiet < 8
|
||||
{
|
||||
available_actions.push(&ACTIONS.manipulation);
|
||||
}
|
||||
if craft.buffs.waste_not > 0 {
|
||||
|
|
@ -129,8 +178,9 @@ pub fn next_action_phase_2<'a>(craft: & Craft<'a>) -> Vec<Option<&'a Action>> {
|
|||
available_actions.push(&ACTIONS.advanced_touch);
|
||||
forbidden_actions.push(&ACTIONS.basic_touch);
|
||||
}
|
||||
// Todo, allow earlier byregot if the craft can be finished all the same (useless with always optimize on)
|
||||
if craft.buffs.inner_quiet >= craft.args.byregot_step { // 10
|
||||
|
||||
if craft.buffs.inner_quiet >= craft.args.byregot_step {
|
||||
// 10
|
||||
available_actions.push(&ACTIONS.trained_finesse);
|
||||
available_actions.push(&ACTIONS.great_strides);
|
||||
}
|
||||
|
|
@ -142,9 +192,11 @@ pub fn next_action_phase_2<'a>(craft: & Craft<'a>) -> Vec<Option<&'a Action>> {
|
|||
}
|
||||
}
|
||||
let mut final_actions: Vec<Option<&Action>> = Vec::new();
|
||||
|
||||
|
||||
for action in available_actions {
|
||||
if !forbidden_actions.contains(&action) && !final_actions.iter().any(|a| a.unwrap() == action) {
|
||||
if !forbidden_actions.contains(&action)
|
||||
&& !final_actions.iter().any(|a| a.unwrap() == action)
|
||||
{
|
||||
final_actions.push(Some(action));
|
||||
}
|
||||
}
|
||||
|
|
@ -154,8 +206,7 @@ pub fn next_action_phase_2<'a>(craft: & Craft<'a>) -> Vec<Option<&'a Action>> {
|
|||
/// Apply all actions to the current route
|
||||
pub fn generate_routes_phase2<'a>(craft: Craft<'a>) -> Option<Vec<Craft<'a>>> {
|
||||
let mut queue = VecDeque::new();
|
||||
|
||||
// Todo: Return a vec of relevant functions, instead of the most quality one
|
||||
|
||||
let mut top_route: Craft<'a> = craft.clone(); // Default route, no hq on that one
|
||||
let mut top_routes: Vec<Craft<'a>> = vec![];
|
||||
|
||||
|
|
@ -164,18 +215,21 @@ pub fn generate_routes_phase2<'a>(craft: Craft<'a>) -> Option<Vec<Craft<'a>>> {
|
|||
while !queue.is_empty() {
|
||||
let _craft = queue.pop_front().unwrap();
|
||||
for action in next_action_phase_2(&_craft) {
|
||||
if _craft.success != Success::Pending || action.is_none() || !action.unwrap().can_use(&_craft) {
|
||||
if _craft.success != Success::Pending
|
||||
|| action.is_none()
|
||||
|| !action.unwrap().can_use(&_craft)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let mut craft = _craft.clone();
|
||||
craft.run_action(action.unwrap());
|
||||
if action.unwrap() == &ACTIONS.byregot_blessing {
|
||||
#[cfg(not(feature="fast"))]
|
||||
if top_route.quality>=craft.recipe.quality{
|
||||
top_routes.push(craft.clone()); // Me memory
|
||||
#[cfg(not(feature = "fast"))]
|
||||
if top_route.quality >= craft.recipe.quality {
|
||||
top_routes.push(craft.clone()); // Me memory
|
||||
}
|
||||
if top_route.quality < craft.quality {
|
||||
#[cfg(feature="fast")]
|
||||
#[cfg(feature = "fast")]
|
||||
top_routes.push(craft.clone());
|
||||
top_route = craft;
|
||||
}
|
||||
|
|
@ -187,4 +241,4 @@ pub fn generate_routes_phase2<'a>(craft: Craft<'a>) -> Option<Vec<Craft<'a>>> {
|
|||
// Let's not forget the best result
|
||||
top_routes.push(top_route);
|
||||
Some(top_routes)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
36
src/specs.rs
36
src/specs.rs
|
|
@ -1,7 +1,6 @@
|
|||
use std::fmt::{Debug};
|
||||
use std::fmt::Debug;
|
||||
use strum_macros::EnumIter;
|
||||
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct Recipe {
|
||||
pub durability: u32,
|
||||
|
|
@ -13,7 +12,6 @@ pub struct Recipe {
|
|||
pub quality_modifier: u32,
|
||||
}
|
||||
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct Stats {
|
||||
pub craftsmanship: u32,
|
||||
|
|
@ -103,14 +101,30 @@ impl BuffState {
|
|||
}
|
||||
|
||||
pub fn tick(&mut self) {
|
||||
if self.waste_not > 0 { self.waste_not -= 1; }
|
||||
if self.great_strides > 0 { self.great_strides -= 1; }
|
||||
if self.innovation > 0 { self.innovation -= 1; }
|
||||
if self.veneration > 0 { self.veneration -= 1; }
|
||||
if self.manipulation > 0 { self.manipulation -= 1; }
|
||||
if self.muscle_memory > 0 { self.muscle_memory -= 1; }
|
||||
if self.basic_touch > 0 { self.basic_touch -= 1; }
|
||||
if self.standard_touch > 0 { self.standard_touch -= 1; }
|
||||
if self.waste_not > 0 {
|
||||
self.waste_not -= 1;
|
||||
}
|
||||
if self.great_strides > 0 {
|
||||
self.great_strides -= 1;
|
||||
}
|
||||
if self.innovation > 0 {
|
||||
self.innovation -= 1;
|
||||
}
|
||||
if self.veneration > 0 {
|
||||
self.veneration -= 1;
|
||||
}
|
||||
if self.manipulation > 0 {
|
||||
self.manipulation -= 1;
|
||||
}
|
||||
if self.muscle_memory > 0 {
|
||||
self.muscle_memory -= 1;
|
||||
}
|
||||
if self.basic_touch > 0 {
|
||||
self.basic_touch -= 1;
|
||||
}
|
||||
if self.standard_touch > 0 {
|
||||
self.standard_touch -= 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
Reference in New Issue