1
use crate::Craft;
2
use clap::Parser;
3
use core::fmt::Display;
4

            
5
// #[cfg(not(feature = "no_python"))]
6
use pyo3::prelude::*;
7

            
8
12
#[derive(Debug, Clone, Copy)]
9
pub struct Parameters {
10
    pub threads: usize,
11
    pub verbose: u8,
12
    pub depth: u32,
13
    pub desperate: bool,
14
    pub byregot_step: u8,
15
}
16

            
17
32
#[derive(Parser, Debug, Clone)]
18
#[command(author, version, about, long_about = None)]
19
pub struct Args {
20
    /// Name of the receipe
21
6
    #[arg(short, long, default_value_t = String::from("default_recipe"))]
22
    pub recipe_name: String,
23

            
24
    /// Name of the character
25
6
    #[arg(short, long, default_value_t = String::from("default_character"))]
26
    pub character_name: String,
27

            
28
    /// The ml file name
29
6
    #[arg(short, long, default_value_t = String::from("craft.toml"))]
30
    pub file_name: String,
31

            
32
    /// The verbose flag
33
    #[arg(short, long, action = clap::ArgAction::Count)]
34
    pub verbose: u8,
35

            
36
    /// The depth of the first pass
37
6
    #[arg(short, long, default_value_t = 8)]
38
    pub depth: u32,
39

            
40
    /// Thread counts, default is 4
41
6
    #[arg(short, long, default_value_t = 4)]
42
    pub threads: usize,
43

            
44
    /// Desperate mode, will try to finish the craft above all
45
6
    #[arg(short = 'D', long, default_value_t = false)]
46
    pub desperate: bool,
47

            
48
    /// Long mode, will try to find more solutions, at the expense of time
49
6
    #[arg(short = 'l', long, default_value_t = false)]
50
    pub long: bool,
51
}
52

            
53
/// A final stripped down version of a craft
54
/// used for final print and talking with python
55
10
#[derive(Debug)]
56
#[pyclass]
57
pub struct SolverResult {
58
    #[pyo3(get)]
59
    pub steps: u32,
60
    #[pyo3(get)]
61
    pub quality: u32,
62
    #[pyo3(get)]
63
    pub progression: u32,
64
    #[pyo3(get)]
65
    pub durability: i32,
66
    #[pyo3(get)]
67
    pub cp: i32,
68
    #[pyo3(get)]
69
    pub total_cp: u32,
70
    #[pyo3(get)]
71
    pub total_progression: u32,
72
    #[pyo3(get)]
73
    pub total_quality: u32,
74
    #[pyo3(get)]
75
    pub total_durability: u32,
76
    #[pyo3(get)]
77
    pub actions: Vec<String>,
78
    #[pyo3(get)]
79
    pub step1_solutions: usize,
80
    #[pyo3(get)]
81
    pub step2_solutions: usize,
82
    #[pyo3(get)]
83
    pub found_100_percent: bool,
84
}
85

            
86
/// Pretty display for SolverResult
87
impl Display for SolverResult {
88
26
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
89
26
        write!(f, "{:?}", self.actions)
90
26
    }
91
}
92

            
93
//#[pymethods]
94
impl SolverResult {
95
    pub fn from_craft(
96
        craft: &Craft,
97
        step1_solutions: usize,
98
        step2_solutions: usize,
99
        found_100_percent: bool,
100
    ) -> SolverResult {
101
        let mut actions = craft
102
            .actions
103
            .iter()
104
            .map(|action| format!("{}", action.short_name))
105
            .collect::<Vec<String>>();
106
        let arg = (craft.recipe.progress as f32 - craft.progression as f32)
107
            / craft.get_base_progression() as f32;
108
        if 0.0 < arg && arg < 1.2 {
109
            actions.push("basicSynth2".to_string());
110
        }
111
        if 1.2 <= arg && arg < 1.8 {
112
            actions.push("carefulSynthesis".to_string());
113
        }
114
        if 1.8 <= arg && arg < 2.0 {
115
            actions.push("observe".to_string());
116
            actions.push("focusedSynthesis".to_string());
117
        }
118
        SolverResult {
119
            steps: craft.step_count,
120
            progression: craft.progression,
121
            quality: craft.quality,
122
            durability: craft.durability,
123
            actions: actions,
124
            step1_solutions,
125
            step2_solutions,
126
            found_100_percent,
127
            total_progression: craft.recipe.progress,
128
            total_quality: craft.recipe.quality,
129
            total_durability: craft.recipe.durability,
130
            cp: craft.cp,
131
            total_cp: craft.stats.max_cp,
132
        }
133
    }
134
}
135

            
136
#[pymethods]
137
impl SolverResult {
138
    #[staticmethod]
139
23
    pub fn default() -> Self {
140
23
        Self {
141
23
            steps: 0,
142
23
            progression: 0,
143
23
            quality: 0,
144
23
            durability: 0,
145
23
            total_progression: 0,
146
23
            total_quality: 0,
147
23
            total_durability: 0,
148
23
            actions: vec!["Act1".to_string(), "Act2".to_string()],
149
23
            step1_solutions: 0,
150
23
            step2_solutions: 0,
151
23
            found_100_percent: false,
152
23
            cp: 0,
153
23
            total_cp: 0,
154
23
        }
155
23
    }
156

            
157
8
    pub fn pretty_print(&self) {
158
8
        println!(
159
8
            "Quality: [{}/{}] | Durability: [{}/{}] | Cp : [{}/{}] | Steps : {}",
160
8
            self.quality,
161
8
            self.total_quality,
162
8
            self.durability,
163
8
            self.total_durability,
164
8
            self.cp,
165
8
            self.total_cp,
166
8
            self.steps
167
8
        );
168
8
        println!("{:?}", self.actions);
169
8
    }
170
}
171

            
172
impl Parameters {
173
    pub fn from_args(args: &Args) -> Self {
174
        Self {
175
            depth: if args.desperate { 11 } else { 8 },
176
            threads: args.threads,
177
            verbose: args.verbose,
178
            desperate: args.desperate,
179
            byregot_step: if args.long { 6 } else { 8 },
180
        }
181
    }
182
}
183

            
184
////// Python Bindings //////
185

            
186
/// A Python module implemented in Rust.
187
#[cfg(not(feature = "no_python"))]
188
#[pymodule]
189
fn xiv_csolver_lib(_py: Python, m: &PyModule) -> PyResult<()> {
190
    m.add_function(wrap_pyfunction!(test_result, m)?)?;
191
    m.add_function(wrap_pyfunction!(solve_from_python, m)?)?;
192
    Ok(())
193
}
194

            
195
///
196
#[cfg(not(feature = "no_python"))]
197
#[pyfunction]
198
pub fn test_result() -> SolverResult {
199
    SolverResult::default()
200
}
201

            
202
/// Create a stat struct stats with the base values
203
#[cfg(not(feature = "no_python"))]
204
use crate::{solve_craft, Recipe, Stats};
205

            
206
#[cfg(not(feature = "no_python"))]
207
#[pyfunction]
208
pub fn solve_from_python(values: &PyAny) -> PyResult<Option<Vec<SolverResult>>> {
209
    // // Create Recipe
210
    let recipe = Recipe {
211
        durability: values.getattr("durability")?.extract()?,
212
        progress: values.getattr("progress")?.extract()?,
213
        progress_divider: values.getattr("progress_divider")?.extract()?,
214
        progress_modifier: values.getattr("progress_modifier")?.extract()?,
215
        quality: values.getattr("quality")?.extract()?,
216
        quality_divider: values.getattr("quality_divider")?.extract()?,
217
        quality_modifier: values.getattr("quality_modifier")?.extract()?,
218
    };
219

            
220
    // Create Stats
221
    let stats = Stats {
222
        craftsmanship: values.getattr("craftsmanship")?.extract()?,
223
        control: values.getattr("control")?.extract()?,
224
        max_cp: values.getattr("max_cp")?.extract()?,
225
    };
226

            
227
    // Create parameters
228
    let param = Parameters {
229
        depth: values.getattr("depth")?.extract()?,
230
        byregot_step: values.getattr("byregot_step")?.extract()?,
231
        desperate: values.getattr("desperate")?.extract()?,
232
        threads: values.getattr("threads")?.extract()?,
233
        verbose: values.getattr("verbose")?.extract()?,
234
    };
235

            
236
    // println!("{:?} len: {:?} ",values,values.getattr("len()"));
237
    let res = solve_craft(recipe, stats, param);
238
    Ok(res)
239
}
240

            
241
#[cfg(test)]
242
mod tests {
243
    use crate::io::Args;
244
    use crate::{Parameters, SolverResult};
245
    use pretty_assertions::{assert_eq, assert_ne};
246
    use clap::Parser;
247

            
248
    impl PartialEq for Parameters {
249
6
        fn eq(&self, rhs: &Parameters) -> bool {
250
6
            (self.byregot_step == rhs.byregot_step)
251
6
                & (self.depth == rhs.depth)
252
6
                & (self.desperate == rhs.desperate)
253
6
                & (self.threads == rhs.threads)
254
6
        }
255
    }
256

            
257
6
    #[test]
258
6
    pub fn test_parameters_derived_attributes() {
259
6
        let def = Parameters {
260
6
            byregot_step: 0,
261
6
            depth: 0,
262
6
            desperate: false,
263
6
            threads: 42,
264
6
            verbose: 1,
265
6
        };
266
6
        let def2 = def;
267
6
        let def3 = def2.clone();
268
6

            
269
6
        assert_eq!(def2, def3);
270
6
    }
271

            
272
6
    #[test]
273
6
    pub fn test_display() {
274
6
        let def = SolverResult::default();
275
6
        assert_ne!(def.to_string(), "");
276
6
        assert_eq!(def.to_string(), "[\"Act1\", \"Act2\"]");
277
6
        def.pretty_print();
278
6
    }
279

            
280
6
    #[test]
281
6
    pub fn test_debug() {
282
6
        let def = SolverResult::default();
283
6
        assert_eq!(format!("{:?}", def),"SolverResult { steps: 0, quality: 0, progression: 0, durability: 0, cp: 0, total_cp: 0, total_progression: 0, total_quality: 0, total_durability: 0, actions: [\"Act1\", \"Act2\"], step1_solutions: 0, step2_solutions: 0, found_100_percent: false }");
284
6
    }
285

            
286
3
    #[test]
287
3
    pub fn test_arguments() {
288
3
        // Create false argument parameter
289
3
        let a = Args {
290
3
            character_name: "Bob GZ".to_string(),
291
3
            depth: 77,
292
3
            desperate: false,
293
3
            file_name: "test.toml".to_string(),
294
3
            long: false,
295
3
            recipe_name: "Belladone".to_string(),
296
3
            threads: 11,
297
3
            verbose: 1,
298
3
        };
299
3
        let a2 = a.clone();
300
3
        println!("{:?}",a2);
301
3
        // Test Custom recipe
302
3
        let a3 = Args::parse_from(["ultraman","-r", "recipe","-c","dan","-f","bigfile.toml","-d","45","-t","4","-D","-l","-vvv"]);
303
3
        let _ = Args::parse_from(["-V"]);
304
3
        let _ = Args::parse_from(["-H"]);
305
3
        assert_eq!(a3.recipe_name,"recipe");
306
3
        assert_eq!(a3.character_name,"dan");
307
3
        assert_eq!(a3.file_name,"bigfile.toml");
308
3
        assert_eq!(a3.verbose,3);
309
3
        assert_eq!(a3.depth,45);
310
3
        assert_eq!(a3.threads,4);
311
3
        assert_eq!(a3.desperate,true);
312
3
        assert_eq!(a3.long,true);
313

            
314
        // Test default parameters
315
3
        let a4 = Args::parse_from(["bobGZ"]); 
316
3
        assert_eq!(a4.recipe_name,"default_recipe");
317
3
        assert_eq!(a4.character_name,"default_character");
318
3
        assert_eq!(a4.file_name,"craft.toml");
319
3
        assert_eq!(a4.verbose,0);
320
3
        assert_eq!(a4.depth,8);
321
3
        assert_eq!(a4.threads,4);
322
3
        assert_eq!(a4.desperate,false);
323
3
        assert_eq!(a4.long,false);
324
3
    }
325

            
326
3
    #[test]
327
3
    pub fn test_parameters() {}
328
}