• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

APN-Pucky / tyrant_optimize / 41361472244

01 Nov 2026 11:18PM UTC coverage: 70.592% (+0.08%) from 70.512%
41361472244

push

github

web-flow
Fix parallel db access (#118)

* document changes

* Fix db corruption/crash with concurrent tuo processes

load_db crashed with std::out_of_range when it read database.yml
mid-write by another process, since a truncated line left substr()
calling with pos > size. There was also no synchronization around
database.yml, so concurrent writers could corrupt the file, and each
writer only ever held its own subset of evaluated matchups, so the
last process to finish silently discarded everyone else's results.

- Bounds-check every substr in the db parser and skip malformed/
  truncated lines instead of crashing.
- Serialize write_db across processes with an interprocess file lock.
- Merge with whatever is currently on disk (keeping the higher-count
  result per matchup) instead of overwriting, so parallel runs
  accumulate into the shared db rather than clobbering each other.
- Publish via a temp file + atomic rename so a concurrent reader can
  never observe a half-written file.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* add changelog update

* check for file error codes

---------

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>

76 of 86 new or added lines in 1 file covered. (88.37%)

4844 of 6862 relevant lines covered (70.59%)

10529229.61 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

55.01
/tyrant_optimize.cpp
1
// This program is free software: you can redistribute it and/or modify
2
// it under the terms of the GNU General Public License as published by
3
// the Free Software Foundation, either version 3 of the License, or
4
// (at your option) any later version.
5

6
// This program is distributed in the hope that it will be useful,
7
// but WITHOUT ANY WARRANTY; without even the implied warranty of
8
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
9
// GNU General Public License for more details.
10

11
// You should have received a copy of the GNU General Public License
12
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
13
//------------------------------------------------------------------------------
14
// #define NDEBUG
15
#define BOOST_THREAD_USE_LIB
16

17
#ifndef _WIN32
18
#include <unistd.h>
19
#else
20
#include <io.h>
21
#define F_OK 0
22
#define access(f, m) _access((f), (m))
23
#endif
24
#include <array>
25
#include <cassert>
26
#include <chrono>
27
#include <cstring>
28
#include <ctime>
29
#include <functional>
30
#include <iostream>
31
#include <map>
32
#include <unordered_map>
33
#include <set>
34
#include <stack>
35
#include <fstream>
36
#include <string>
37
#include <iomanip>
38
#include <tuple>
39
#include <vector>
40
#include <math.h>
41
#include <boost/algorithm/string.hpp>
42
#include <boost/filesystem.hpp>
43
#include <boost/interprocess/sync/file_lock.hpp>
44
#include <boost/interprocess/sync/scoped_lock.hpp>
45
#include <boost/lexical_cast.hpp>
46
#include <boost/math/distributions/binomial.hpp>
47
#include <boost/optional.hpp>
48
#include <boost/range/join.hpp>
49
#include <boost/thread/barrier.hpp>
50
#include <boost/thread/mutex.hpp>
51
#include <boost/thread/thread.hpp>
52
#include <boost/timer/timer.hpp>
53
#include <boost/tokenizer.hpp>
54
#include "card.h"
55
#include "cards.h"
56
#include "deck.h"
57
#include "read.h"
58
#include "sim.h"
59
#include "tyrant.h"
60
#include "xml.h"
61

62
#include "hPMML.h"
63

64
#define DEFINE_GLOBALS
65
#include "algorithms.h"
66

67
// OpenMP Header
68
#ifdef _OPENMP
69
#include <omp.h>
70
#endif
71

72
// Android Headers
73
#if defined(ANDROID) || defined(__ANDROID__)
74
#include <jni.h>
75
#include <android/log.h>
76
#endif
77

78
using namespace tuo;
79
using namespace proc;
80

81
// Confidence bounds are computed in double precision. Boost promotes double to long double by default, which is
82
// slow where long double is a software-emulated 128-bit type (e.g. WebAssembly), and its root finding fails there
83
// near 100% wins ("gamma_p_inv<long double>: Root finding evaluation exceeded 200 iterations").
84
typedef boost::math::binomial_distribution<double, boost::math::policies::policy<boost::math::policies::promote_double<false>>> binomial_distribution;
85

86
// init
87
/*
88
namespace tuo {
89
  unsigned opt_num_threads=4;
90
    gamemode_t gamemode{fight};
91
    OptimizationMode optimization_mode{OptimizationMode::notset};
92
    std::unordered_map<unsigned, unsigned> owned_cards;
93
    const Card* owned_alpha_dominion{nullptr};
94
    bool use_owned_cards{true};
95
    bool opt_skip_unclaimed_decks{false};
96
    //bool opt_trim_unclaimed_decks{false};
97
    unsigned min_deck_len{1};
98
    unsigned max_deck_len{10};
99
    unsigned opt_freezed_cards{0};
100
    unsigned freezed_cards{0};
101
    unsigned fund{0};
102
    long double target_score{100};
103
    long double min_increment_of_score{0};
104
    long double confidence_level{0.99};
105
    bool use_top_level_card{true};
106
    bool use_top_level_commander{true};
107
    bool mode_open_the_deck{false};
108
    bool use_owned_dominions{true};
109
    bool use_maxed_dominions{false};
110
    unsigned use_fused_card_level{0};
111
    unsigned use_fused_commander_level{0};
112
    bool print_upgraded{false};
113
    bool print_values{false};
114
    bool simplify_output{false};
115
    bool show_ci{false};
116
    bool use_harmonic_mean{false};
117
    unsigned iterations_multiplier{10};
118
    unsigned sim_seed{0};
119
    unsigned flexible_iter{20};
120
    unsigned flexible_turn{10};
121
    Requirement requirement;
122
#ifndef NQUEST
123
    Quest quest;
124
#endif
125
    std::unordered_set<unsigned> allowed_candidates;
126
    std::unordered_set<unsigned> disallowed_candidates;
127
    std::chrono::time_point<std::chrono::system_clock> start_time;
128
    long double maximum_time{0};
129
    //anneal
130
    long double temperature = 1000;
131
    long double coolingRate = 0.001;
132
    //genetic
133
    unsigned generations = 50;
134
    unsigned pool_size = 0;
135
    unsigned min_pool_size = 20;
136
    double opt_pool_keep = 1;
137
    double opt_pool_mutate = 1;
138
    double opt_pool_cross = 1;
139
    //fort_climb
140
    unsigned yfpool{0};
141
    unsigned efpool{0};
142
    std::vector<Faction> factions;
143
    bool invert_factions{false};
144
    bool only_recent{false};
145
    bool prefered_recent{false};
146
    unsigned recent_percent{5};
147
    std::vector<Skill::Skill> skills;
148
    bool invert_skills{false};
149
    std::vector<Skill::Skill> prefered_skills;
150
    unsigned prefered_factor{3};
151

152
#if defined(ANDROID) || defined(__ANDROID__)
153
    JNIEnv *envv;
154
    jobject objv;
155
#endif
156
}
157
*/
158

159
static const unsigned int crc32_table[] =
160
    {
161
        0x00000000, 0x04c11db7, 0x09823b6e, 0x0d4326d9,
162
        0x130476dc, 0x17c56b6b, 0x1a864db2, 0x1e475005,
163
        0x2608edb8, 0x22c9f00f, 0x2f8ad6d6, 0x2b4bcb61,
164
        0x350c9b64, 0x31cd86d3, 0x3c8ea00a, 0x384fbdbd,
165
        0x4c11db70, 0x48d0c6c7, 0x4593e01e, 0x4152fda9,
166
        0x5f15adac, 0x5bd4b01b, 0x569796c2, 0x52568b75,
167
        0x6a1936c8, 0x6ed82b7f, 0x639b0da6, 0x675a1011,
168
        0x791d4014, 0x7ddc5da3, 0x709f7b7a, 0x745e66cd,
169
        0x9823b6e0, 0x9ce2ab57, 0x91a18d8e, 0x95609039,
170
        0x8b27c03c, 0x8fe6dd8b, 0x82a5fb52, 0x8664e6e5,
171
        0xbe2b5b58, 0xbaea46ef, 0xb7a96036, 0xb3687d81,
172
        0xad2f2d84, 0xa9ee3033, 0xa4ad16ea, 0xa06c0b5d,
173
        0xd4326d90, 0xd0f37027, 0xddb056fe, 0xd9714b49,
174
        0xc7361b4c, 0xc3f706fb, 0xceb42022, 0xca753d95,
175
        0xf23a8028, 0xf6fb9d9f, 0xfbb8bb46, 0xff79a6f1,
176
        0xe13ef6f4, 0xe5ffeb43, 0xe8bccd9a, 0xec7dd02d,
177
        0x34867077, 0x30476dc0, 0x3d044b19, 0x39c556ae,
178
        0x278206ab, 0x23431b1c, 0x2e003dc5, 0x2ac12072,
179
        0x128e9dcf, 0x164f8078, 0x1b0ca6a1, 0x1fcdbb16,
180
        0x018aeb13, 0x054bf6a4, 0x0808d07d, 0x0cc9cdca,
181
        0x7897ab07, 0x7c56b6b0, 0x71159069, 0x75d48dde,
182
        0x6b93dddb, 0x6f52c06c, 0x6211e6b5, 0x66d0fb02,
183
        0x5e9f46bf, 0x5a5e5b08, 0x571d7dd1, 0x53dc6066,
184
        0x4d9b3063, 0x495a2dd4, 0x44190b0d, 0x40d816ba,
185
        0xaca5c697, 0xa864db20, 0xa527fdf9, 0xa1e6e04e,
186
        0xbfa1b04b, 0xbb60adfc, 0xb6238b25, 0xb2e29692,
187
        0x8aad2b2f, 0x8e6c3698, 0x832f1041, 0x87ee0df6,
188
        0x99a95df3, 0x9d684044, 0x902b669d, 0x94ea7b2a,
189
        0xe0b41de7, 0xe4750050, 0xe9362689, 0xedf73b3e,
190
        0xf3b06b3b, 0xf771768c, 0xfa325055, 0xfef34de2,
191
        0xc6bcf05f, 0xc27dede8, 0xcf3ecb31, 0xcbffd686,
192
        0xd5b88683, 0xd1799b34, 0xdc3abded, 0xd8fba05a,
193
        0x690ce0ee, 0x6dcdfd59, 0x608edb80, 0x644fc637,
194
        0x7a089632, 0x7ec98b85, 0x738aad5c, 0x774bb0eb,
195
        0x4f040d56, 0x4bc510e1, 0x46863638, 0x42472b8f,
196
        0x5c007b8a, 0x58c1663d, 0x558240e4, 0x51435d53,
197
        0x251d3b9e, 0x21dc2629, 0x2c9f00f0, 0x285e1d47,
198
        0x36194d42, 0x32d850f5, 0x3f9b762c, 0x3b5a6b9b,
199
        0x0315d626, 0x07d4cb91, 0x0a97ed48, 0x0e56f0ff,
200
        0x1011a0fa, 0x14d0bd4d, 0x19939b94, 0x1d528623,
201
        0xf12f560e, 0xf5ee4bb9, 0xf8ad6d60, 0xfc6c70d7,
202
        0xe22b20d2, 0xe6ea3d65, 0xeba91bbc, 0xef68060b,
203
        0xd727bbb6, 0xd3e6a601, 0xdea580d8, 0xda649d6f,
204
        0xc423cd6a, 0xc0e2d0dd, 0xcda1f604, 0xc960ebb3,
205
        0xbd3e8d7e, 0xb9ff90c9, 0xb4bcb610, 0xb07daba7,
206
        0xae3afba2, 0xaafbe615, 0xa7b8c0cc, 0xa379dd7b,
207
        0x9b3660c6, 0x9ff77d71, 0x92b45ba8, 0x9675461f,
208
        0x8832161a, 0x8cf30bad, 0x81b02d74, 0x857130c3,
209
        0x5d8a9099, 0x594b8d2e, 0x5408abf7, 0x50c9b640,
210
        0x4e8ee645, 0x4a4ffbf2, 0x470cdd2b, 0x43cdc09c,
211
        0x7b827d21, 0x7f436096, 0x7200464f, 0x76c15bf8,
212
        0x68860bfd, 0x6c47164a, 0x61043093, 0x65c52d24,
213
        0x119b4be9, 0x155a565e, 0x18197087, 0x1cd86d30,
214
        0x029f3d35, 0x065e2082, 0x0b1d065b, 0x0fdc1bec,
215
        0x3793a651, 0x3352bbe6, 0x3e119d3f, 0x3ad08088,
216
        0x2497d08d, 0x2056cd3a, 0x2d15ebe3, 0x29d4f654,
217
        0xc5a92679, 0xc1683bce, 0xcc2b1d17, 0xc8ea00a0,
218
        0xd6ad50a5, 0xd26c4d12, 0xdf2f6bcb, 0xdbee767c,
219
        0xe3a1cbc1, 0xe760d676, 0xea23f0af, 0xeee2ed18,
220
        0xf0a5bd1d, 0xf464a0aa, 0xf9278673, 0xfde69bc4,
221
        0x89b8fd09, 0x8d79e0be, 0x803ac667, 0x84fbdbd0,
222
        0x9abc8bd5, 0x9e7d9662, 0x933eb0bb, 0x97ffad0c,
223
        0xafb010b1, 0xab710d06, 0xa6322bdf, 0xa2f33668,
224
        0xbcb4666d, 0xb8757bda, 0xb5365d03, 0xb1f740b4};
225

226
unsigned int
227
xcrc32(const unsigned char *buf, int len, unsigned int init)
97,280,390 ✔
228
{
229
    unsigned int crc = init;
97,280,390 ✔
230
    while (len--)
2,147,483,647 ✔
231
    {
232
        crc = (crc << 8) ^ crc32_table[((crc >> 24) ^ *buf) & 255];
2,147,483,647 ✔
233
        buf++;
2,147,483,647 ✔
234
    }
235
    return crc;
×
236
}
237

238
unsigned int file_xrcrc32(std::string filename, unsigned int init)
4,580 ✔
239
{
240
    std::ifstream file;
4,580 ✔
241
    file.open(filename);
4,580 ✔
242
    std::string line;
4,580 ✔
243
    unsigned int crc = init;
4,580 ✔
244
    while (getline(file, line))
97,289,550 ✔
245
    {
246
        crc = xcrc32((const unsigned char *)line.c_str(), line.length(), crc);
194,565,360 ✔
247
    }
248
    return crc;
9,160 ✔
249
}
4,580 ✔
250

251
unsigned int checksumcards(std::string prefix)
200 ✔
252
{
253
    unsigned int crc = 0;
200 ✔
254
    // loop cardsections
255
    unsigned int ii = 1;
200 ✔
256

257
    crc = file_xrcrc32(prefix + "data/raids.xml", crc);
200 ✔
258
    crc = file_xrcrc32(prefix + "data/missions.xml", crc);
200 ✔
259
    std::string fname = prefix + "data/cards_section_1.xml";
200 ✔
260
    while (access(fname.c_str(), F_OK) == 0)
4,380 ✔
261
    {
262
        crc = file_xrcrc32(fname, crc);
8,360 ✔
263
        ii += 1;
4,180 ✔
264
        fname = prefix + "data/cards_section_" + std::to_string(ii) + ".xml";
8,360 ✔
265
    }
266
    return crc;
200 ✔
267
}
200 ✔
268

269
void load_ml(std::string prefix)
85 ✔
270
{
271
    if (use_ml)
85 ✔
272
    {
273
        win_model = hpmml::Model(prefix + "data/win.pmml");
2 ✔
274
        stall_model = hpmml::Model(prefix + "data/stall.pmml");
2 ✔
275
        loss_model = hpmml::Model(prefix + "data/loss.pmml");
2 ✔
276
        points_model = hpmml::Model(prefix + "data/points.pmml");
2 ✔
277
    }
278
}
85 ✔
279

280
using Database = std::map<std::string, std::map<std::string, std::map<std::string, Results<uint64_t>>>>;
281

282
// reads the "version: ..." / "xml_check_sum: ..." header lines of a database.yml stream
283
void parse_db_header(std::istream &file, std::string &version, std::string &check)
132 ✔
284
{
285
    std::string line;
132 ✔
286
    // another process may still be in the middle of (re)writing the db file;
287
    // guard every substr so a half-written/truncated line can't throw/crash us
288
    getline(file, line);
132 ✔
289
    {
132 ✔
290
        auto colon = line.find(":");
132 ✔
291
        if (colon != std::string::npos && colon + 2 <= line.size())
132 ✔
292
            version = line.substr(colon + 2);
131 ✔
293
    }
294
    getline(file, line);
132 ✔
295
    {
132 ✔
296
        auto colon = line.find(":");
132 ✔
297
        if (colon != std::string::npos && colon + 2 <= line.size())
132 ✔
298
            check = line.substr(colon + 2);
131 ✔
299
    }
300
}
132 ✔
301

302
// parses the records that follow the header of a database.yml stream into out
303
void parse_db_body(std::istream &file, Database &out)
131 ✔
304
{
305
    std::string line, hfield, hydeck, hedeck;
131 ✔
306
    uint64_t wins, draws, losses, points, count;
131 ✔
307
    while (getline(file, line))
111,203 ✔
308
    {
309
        auto colon = line.find(":");
110,941 ✔
310
        if (line.rfind("\t\t", 0) == 0 && colon != std::string::npos)
110,941 ✔
311
        {
312
            // a concurrent writer may have left this (the last) line truncated
313
            // right after the colon; skip it instead of reading out of bounds
314
            if (colon + 2 > line.size())
95,811 ✔
NEW
315
                continue;
×
316
            hedeck = line.substr(2, colon - 2);
95,811 ✔
317
            std::istringstream reader(line.substr(colon + 2));
95,811 ✔
318
            reader >> wins >> draws >> losses >> points >> count;
95,811 ✔
319
            if (reader.fail())
95,811 ✔
NEW
320
                continue;
×
321
            out[hfield][hydeck][hedeck] = {wins, draws, losses, points, count};
95,811 ✔
322
            // std::cout << "load db: " << hfield << " " << hydeck << " " << hedeck << " " <<wins<< " "<< draws<< " "<< losses<< " " <<points<< " " <<count << std::endl;
323
        }
95,811 ✔
324
        else if (line.rfind("\t", 0) == 0 && colon != std::string::npos)
15,130 ✔
325
        {
326
            hydeck = line.substr(1, colon - 1);
13,643 ✔
327
        }
328
        else if (colon != std::string::npos)
1,487 ✔
329
        {
330
            hfield = line.substr(0, colon);
1,487 ✔
331
        }
332
        else
333
        {
334
            std::cout << "unknown db line: " << line;
111,072 ✔
335
        }
336
    }
337
}
131 ✔
338

339
// load database map from file
340
void load_db(std::string prefix)
85 ✔
341
{
342
    if (use_db_load)
85 ✔
343
    {
344
        _DEBUG_MSG(1, "start loading db\n");
66 ✔
345
        // open file to read from
346
        std::ifstream file;
66 ✔
347
        file.open(prefix + "data/database.yml");
66 ✔
348
        std::string version, check;
66 ✔
349
        parse_db_header(file, version, check);
66 ✔
350
        std::cout << "DB version " << version << std::endl;
66 ✔
351
        std::cout << "DB checksum " << check << std::endl;
66 ✔
352

353
        if (use_strict_db)
66 ✔
354
        {
355
            if (version.compare(TYRANT_OPTIMIZER_VERSION) != 0)
66 ✔
356
            {
357
                std::cout << "DB TUO version outdated" << std::endl;
1 ✔
358
                std::cout << "DB TUO version " << version << " != " << TYRANT_OPTIMIZER_VERSION << std::endl;
1 ✔
359
                std::cout << "DB ignoring database.yml" << std::endl;
1 ✔
360
                use_db_load = false;
1 ✔
361
                return;
1 ✔
362
            }
363
            if (check.compare(std::to_string(checksumcards(prefix))) != 0)
130 ✔
364
            {
365
                std::cout << "DB cards_sections mismatch to db" << std::endl;
×
366
                std::cout << "DB cards_sections checksum " << checksumcards(prefix) << " != " << check << std::endl;
×
367
                std::cout << "DB ignoring database.yml" << std::endl;
×
368
                use_db_load = false;
×
369
                return;
×
370
            }
371
        }
372

373
        parse_db_body(file, database);
65 ✔
374
        // close file
375
        file.close();
65 ✔
376
        _DEBUG_MSG(1, "done loading db\n");
65 ✔
377
    }
66 ✔
378
}
379

380
// write database map to file
381
void write_db(std::string prefix)
85 ✔
382
{
383
    if (use_db_write)
85 ✔
384
    {
385
        _DEBUG_MSG(1, "start writing to db\n");
69 ✔
386
        const std::string db_path = prefix + "data/database.yml";
69 ✔
387

388
        // serialize concurrent writers with an interprocess lock, and merge
389
        // our in-memory results into whatever is currently on disk instead of
390
        // overwriting it outright: each tuo process only ever holds the
391
        // subset of matchups it looked at, so a plain overwrite would make
392
        // the last process to finish the only one whose results survive.
393
        const std::string lock_path = db_path + ".lock";
69 ✔
394
        { std::ofstream ensure_lock(lock_path, std::ios::app); } // file_lock requires the path to already exist
69 ✔
395
        try
69 ✔
396
        {
397
            boost::interprocess::file_lock flock(lock_path.c_str());
69 ✔
398
            boost::interprocess::scoped_lock<boost::interprocess::file_lock> guard(flock);
69 ✔
399

400
            std::ifstream in(db_path);
69 ✔
401
            if (in.is_open())
69 ✔
402
            {
403
                std::string disk_version, disk_check;
66 ✔
404
                parse_db_header(in, disk_version, disk_check);
66 ✔
405
                bool compatible = !use_strict_db || (disk_version == std::string(TYRANT_OPTIMIZER_VERSION) &&
132 ✔
406
                                                      disk_check == std::to_string(checksumcards(prefix)));
198 ✔
407
                if (compatible)
66 ✔
408
                {
409
                    Database on_disk;
66 ✔
410
                    parse_db_body(in, on_disk);
66 ✔
411
                    for (auto &f : on_disk)
810 ✔
412
                        for (auto &d : f.second)
7,566 ✔
413
                            for (auto &e : d.second)
54,728 ✔
414
                            {
415
                                auto &slot = database[f.first][d.first][e.first];
47,906 ✔
416
                                // keep whichever result was computed from more samples
417
                                if (e.second.count > slot.count)
47,906 ✔
418
                                    slot = e.second;
1 ✔
419
                            }
420
                }
66 ✔
421
            }
66 ✔
422
            in.close();
69 ✔
423

424
            // write to a uniquely-named temp file first, then atomically rename it
425
            // onto database.yml, so a concurrent reader never observes a
426
            // half-written (truncated) file
427
            boost::filesystem::path tmp_path = boost::filesystem::unique_path(db_path + ".tmp-%%%%-%%%%");
138 ✔
428
            // open file to write to
429
            std::ofstream file;
69 ✔
430
            file.open(tmp_path.string());
69 ✔
431
            file << "version: " << TYRANT_OPTIMIZER_VERSION << std::endl;
69 ✔
432

433
            file << "xml_check_sum: " << checksumcards(prefix) << std::endl;
138 ✔
434
            auto lines_to_write = db_limit;
69 ✔
435
            // write map to file
436
            for (auto it1 = database.begin(); lines_to_write != 0 && it1 != database.end(); ++it1)
847 ✔
437
            {
438
                file << it1->first << ":" << std::endl;
778 ✔
439
                for (auto it2 = it1->second.begin(); lines_to_write != 0 && it2 != it1->second.end(); ++it2)
7,907 ✔
440
                {
441
                    file << "\t" << it2->first << ":" << std::endl;
7,129 ✔
442
                    for (auto it3 = it2->second.begin(); lines_to_write != 0 && it3 != it2->second.end(); ++it3)
56,995 ✔
443
                    {
444
                        file << "\t\t" << it3->first << ": " << it3->second.wins << " " << it3->second.draws << " " << it3->second.losses << " " << it3->second.points << " " << it3->second.count << std::endl;
49,866 ✔
445
                        if (lines_to_write > 0)
49,866 ✔
NEW
446
                            lines_to_write--;
×
447
                    }
448
                }
449
            }
450
            // close file
451
            file.close();
69 ✔
452
            boost::system::error_code ec;
69 ✔
453
            if (!file)
69 ✔
454
            {
455
                // ofstream doesn't throw on write failures by default (disk full,
456
                // quota, etc.); without this check a partially-written temp file
457
                // would still get renamed over the good database.yml
NEW
458
                std::cout << "DB failed to write temporary database file, preserving database.yml" << std::endl;
×
NEW
459
                boost::filesystem::remove(tmp_path, ec);
×
460
            }
461
            else
462
            {
463
                boost::filesystem::rename(tmp_path, db_path, ec);
138 ✔
464
                if (ec)
69 ✔
465
                {
NEW
466
                    std::cout << "DB failed to atomically update database.yml: " << ec.message() << std::endl;
×
NEW
467
                    boost::filesystem::remove(tmp_path, ec);
×
468
                }
469
            }
470
        }
138 ✔
NEW
471
        catch (const boost::interprocess::interprocess_exception &e)
×
472
        {
NEW
473
            std::cout << "DB failed to lock database.yml for writing (" << e.what() << "), skipping write" << std::endl;
×
NEW
474
        }
×
475
        _DEBUG_MSG(1, "done writing to db\n");
69 ✔
476
    }
69 ✔
477
}
85 ✔
478

479
void init()
86 ✔
480
{
481
    debug_str.clear();
86 ✔
482
    database.clear();
86 ✔
483
    thread_num_iterations = 0; // written by threads
86 ✔
484
    thread_results = nullptr;  // written by threads
86 ✔
485
    thread_best_results = nullptr;
86 ✔
486
    thread_compare = false;
86 ✔
487
    thread_compare_stop = false; // written by threads
86 ✔
488
    destroy_threads;
86 ✔
489
    opt_num_threads = 4;
86 ✔
490
    gamemode = fight;
86 ✔
491
    optimization_mode = OptimizationMode::notset;
86 ✔
492
    owned_cards.clear();
86 ✔
493
    owned_alpha_dominion = nullptr;
86 ✔
494
    use_owned_cards = true;
86 ✔
495
    opt_skip_unclaimed_decks = false;
86 ✔
496
    // opt_trim_unclaimed_decks=false;
497
    min_deck_len = 1;
86 ✔
498
    max_deck_len = 10;
86 ✔
499
    opt_freezed_cards = 0;
86 ✔
500
    freezed_cards = 0;
86 ✔
501
    fund = 0;
86 ✔
502
    target_score = 100;
86 ✔
503
    min_increment_of_score = 0;
86 ✔
504
    confidence_level = 0.99;
86 ✔
505
    use_top_level_card = true;
86 ✔
506
    use_top_level_commander = true;
86 ✔
507
    mode_open_the_deck = false;
86 ✔
508
    use_owned_dominions = true;
86 ✔
509
    use_maxed_dominions = false;
86 ✔
510
    use_fused_card_level = 0;
86 ✔
511
    use_fused_commander_level = 0;
86 ✔
512
    print_upgraded = false;
86 ✔
513
    print_values = false;
86 ✔
514
    vc_x = 0;
86 ✔
515
    simplify_output = false;
86 ✔
516
    show_ci = false;
86 ✔
517
    use_harmonic_mean = false;
86 ✔
518
    iterations_multiplier = 10;
86 ✔
519
    sim_seed = 0;
86 ✔
520
    flexible_iter = 20;
86 ✔
521
    flexible_turn = 20;
86 ✔
522
    eval_iter = 8;
86 ✔
523
    eval_turn = 8;
86 ✔
524
    requirement.num_cards.clear();
86 ✔
525
    for (unsigned i(0); i < Skill::num_skills; ++i)
4,902 ✔
526
    {
527
        auto s = static_cast<Skill::Skill>(i);
4,816 ✔
528
        x_skill_scale[s] = 1.0;
4,816 ✔
529
        n_skill_scale[s] = 1.0;
4,816 ✔
530
        c_skill_scale[s] = 1.0;
4,816 ✔
531
    }
532
    hp_scale = 1.0;
86 ✔
533
    atk_scale = 1.0;
86 ✔
534
#ifndef NQUEST
535
    // quest = new Quest(); //TODO Quest bugged in Android now here
536
#endif
537
    allowed_candidates.clear();
86 ✔
538
    disallowed_candidates.clear();
86 ✔
539
    disallowed_recipes.clear();
86 ✔
540

541
    // std::chrono::time_point<std::chrono::system_clock> start_time;
542
    maximum_time = 0;
86 ✔
543
    temperature = 1000;
86 ✔
544
    coolingRate = 0.001;
86 ✔
545

546
    generations = 50;
86 ✔
547
    pool_size = 0;
86 ✔
548
    min_pool_size = 20;
86 ✔
549
    opt_pool_keep = 1;
86 ✔
550
    opt_pool_mutate = 1;
86 ✔
551
    opt_pool_cross = 1;
86 ✔
552

553
    min_beam_size = 5;
86 ✔
554

555
    yfpool = 0;
86 ✔
556
    efpool = 0;
86 ✔
557

558
    factions.clear();
86 ✔
559
    invert_factions = false;
86 ✔
560
    only_recent = false;
86 ✔
561
    prefered_recent = false;
86 ✔
562
    recent_percent = 5;
86 ✔
563
    skills.clear();
86 ✔
564
    invert_skills = false;
86 ✔
565
    prefered_skills.clear();
86 ✔
566
    prefered_factor = 3;
86 ✔
567

568
    all_cards.clear();
86 ✔
569

570
    // fix defaults
571
    for (int i = 0; i < Fix::num_fixes; ++i)
1,204 ✔
572
        fixes[i] = false;
1,118 ✔
573

574
    // recommended/default fixes
575
    fixes[Fix::enhance_early] = true;
86 ✔
576
    fixes[Fix::revenge_on_death] = true;
86 ✔
577
    fixes[Fix::death_from_bge] = true;
86 ✔
578
    fixes[Fix::legion_under_mega] = true;
86 ✔
579
    // Sort of a misnomer, but updated skills are also treated as fixes
580
        fixes[Fix::barrier_each_turn] = true;
86 ✔
581
        fixes[Fix::dont_evade_mimic_selection] = true;
86 ✔
582
        fixes[Fix::leech_increase_max_hp] = true;
86 ✔
583
        fixes[Fix::subdue_before_attack] = true;
86 ✔
584
        fixes[Fix::counter_without_damage] = true;
86 ✔
585
        fixes[Fix::poison_after_attacked] = true;
86 ✔
586

587
        fixes[Fix::corrosive_protect_armor] = true;
86 ✔
588
    fixes[Fix::reduce_delay_summoned_by_tower] = true;
86 ✔
589
  
590
    db_limit = -1;
86 ✔
591
    use_strict_db = true;
86 ✔
592
    use_db_write = true;
86 ✔
593
    use_db_load = true;
86 ✔
594

595
    use_ml = false;
86 ✔
596
    use_only_ml = false;
86 ✔
597
    ml_precision = 0.01;
86 ✔
598
}
86 ✔
599

600
#if defined(ANDROID) || defined(__ANDROID__)
601
extern "C" JNIEXPORT void
602

603
    JNICALL
604
    Java_de_neuwirthinformatik_alexander_mtuo_TUO_callMain(
605
        JNIEnv *env,
606
        jobject obj /* this */, jobjectArray stringArray)
607
{
608
    envv = env;
609
    objv = obj;
610
    // from: https://stackoverflow.com/questions/8870174/is-stdcout-usable-in-android-ndk and https://gist.github.com/dzhioev/6127982
611
    class androidbuf : public std::streambuf
612
    {
613
    public:
614
        enum
615
        {
616
            bufsize = 512
617
        }; // ... or some other suitable buffer size
618
        androidbuf() { this->setp(buffer, buffer + bufsize - 1); }
619

620
    private:
621
        int overflow(int c)
622
        {
623
            if (c == traits_type::eof())
624
            {
625
                *this->pptr() = traits_type::to_char_type(c);
626
                this->sbumpc();
627
            }
628
            sync_me(c);
629
            return traits_type::not_eof(c);
630
        }
631

632
        void sync_me(int overflow=0) {
633
            if (this->pbase() != this->pptr())
634
            {
635
                char writebuf[bufsize+2];
636
                memcpy(writebuf, this->pbase(), this->pptr() - this->pbase() );
637
                writebuf[this->pptr() - this->pbase() ] = overflow;
638
                writebuf[this->pptr() - this->pbase() + 1 ] = '\0';
639
                //auto sss = std::string(writebuf).c_str();
640
                ///*
641
                __android_log_print(ANDROID_LOG_DEBUG,
642
                                    "TUO_TUO",
643
                                    "%s",
644
                                    writebuf);
645
                //*/
646
                jstring jstr = envv->NewStringUTF(writebuf);
647
                jclass clazz = envv->FindClass("de/neuwirthinformatik/alexander/mtuo/TUO");
648
                jmethodID messageMe = envv->GetMethodID(clazz, "output", "(Ljava/lang/String;)V");
649
                envv->CallVoidMethod(objv, messageMe, jstr);
650
                this->setp(buffer, buffer + bufsize - 1);
651
            }
652
        }
653

654
        int sync()
655
        {
656
            sync_me(0);
657
            return 0;
658
        }
659
        char buffer[bufsize];
660
    };
661
    auto ao = new androidbuf();
662
    auto ae = new androidbuf();
663
    std::cout.rdbuf(ao);
664
    std::cerr.rdbuf(ae);
665
    __android_log_write(ANDROID_LOG_DEBUG, "TUO_TUO", "START");
666
    int stringCount = env->GetArrayLength(stringArray);
667
    char **param = new char *[stringCount];
668
    const char **cparam = new const char *[stringCount];
669
    jstring *strs = new jstring[stringCount];
670
    for (int i = 0; i < stringCount; i++)
671
    {
672
        strs[i] = (jstring)(*env).GetObjectArrayElement(stringArray, i);
673
        cparam[i] = ((*env).GetStringUTFChars(strs[i], NULL));
674
        param[i] = const_cast<char *>(cparam[i]);
675
    }
676

677
    main(stringCount, cparam);
678
    std::cout << std::flush;
679
    __android_log_write(ANDROID_LOG_DEBUG, "TUO_TUO", "END");
680

681
    for (int i = 0; i < stringCount; i++)
682
    {
683
        env->ReleaseStringUTFChars(strs[i], cparam[i]);
684
    }
685
    // std::string text = "return";
686
    // return env->NewStringUTF(text.c_str());
687
    delete[] param;
688
    delete[] cparam;
689
    delete[] strs;
690
    delete ao;
691
    delete ae;
692
}
693

694
extern "C" JNIEXPORT jstring
695

696
    JNICALL
697
    Java_de_neuwirthinformatik_alexander_mtuo_TUO_stringFromJNI(JNIEnv *env,
698
                                                                jobject thiz, jstring s)
699
{
700
    std::string str = env->GetStringUTFChars(s, NULL);
701
    str += "hello.txt";
702
    __android_log_write(ANDROID_LOG_DEBUG, "TUO_TUO", str.c_str());
703
    FILE *file = fopen(str.c_str(), "w+");
704

705
    if (file != NULL)
706
    {
707
        fputs("HELLO WORLD!\n", file);
708
        fflush(file);
709
        fclose(file);
710
    }
711

712
    return env->NewStringUTF("Hello from JNI (with file io)!");
713
}
714
#endif
715
using namespace std::placeholders;
716

717
//------------------------------------------------------------------------------
718

719
//------------------------------------------------------------------------------
720
Deck *find_deck(Decks &decks, const Cards &all_cards, std::string deck_name)
626 ✔
721
{
722
    Deck *deck = decks.find_deck_by_name(deck_name);
626 ✔
723
    if (deck != nullptr)
626 ✔
724
    {
725
        deck->resolve();
566 ✔
726
        return (deck);
566 ✔
727
    }
728
    decks.decks.emplace_back(Deck{all_cards});
120 ✔
729
    deck = &decks.decks.back();
60 ✔
730
    deck->set(deck_name);
60 ✔
731
    deck->resolve();
60 ✔
732
    return (deck);
60 ✔
733
}
734
//---------------------- $80 deck optimization ---------------------------------
735

736
unsigned get_required_cards_before_upgrade(std::unordered_map<unsigned, unsigned> &owned_cards,
94,280 ✔
737
                                           const std::vector<const Card *> &card_list, std::map<const Card *, unsigned> &num_cards)
738
{
739
    unsigned deck_cost = 0;
94,280 ✔
740
    std::set<const Card *> unresolved_cards;
94,280 ✔
741
    for (const Card *card : card_list)
423,539 ✔
742
    {
743
        ++num_cards[card];
329,259 ✔
744
        unresolved_cards.insert(card);
329,259 ✔
745
    }
746
    // un-upgrade according to type/category
747
    // * use fund for normal cards
748
    // * use only top-level cards for initial (basic) dominion (Alpha Dominion) and dominion material (Dominion Shard)
749
    while (!unresolved_cards.empty())
414,601 ✔
750
    {
751
        // pop next unresolved card
752
        auto card_it = unresolved_cards.end();
320,321 ✔
753
        auto card = *(--card_it);
320,321 ✔
754
        unresolved_cards.erase(card_it);
320,321 ✔
755

756
        // assume unlimited common/rare level-1 cards (standard set)
757
        if ((card->m_set == 1000) && (card->m_rarity <= 2) && (card->is_low_level_card()))
320,321 ✔
758
        {
759
            continue;
×
760
        }
761

762
        // keep un-defused (top-level) basic dominion & its material
763
        if ((card->m_id == 50002) || (card->m_category == CardCategory::dominion_material))
320,321 ✔
764
        {
765
            continue;
×
766
        }
767

768
        // defuse if inventory lacks required cards and recipe is not empty
769
        if ((fund || (card->m_category != CardCategory::normal)) && (owned_cards[card->m_id] < num_cards[card]) && !card->m_recipe_cards.empty())
320,321 ✔
770
        {
771
            unsigned num_under = num_cards[card] - owned_cards[card->m_id];
×
772
            num_cards[card] = owned_cards[card->m_id];
×
773

774
            // do count cost (in SP) only for normal cards
775
            if (card->m_category == CardCategory::normal)
×
776
            {
777
                deck_cost += num_under * card->m_recipe_cost;
×
778
            }
779

780
            // enqueue recipe cards as unresolved
781
            for (auto recipe_it : card->m_recipe_cards)
×
782
            {
783
                num_cards[recipe_it.first] += num_under * recipe_it.second;
×
784
                unresolved_cards.insert(recipe_it.first);
×
785
            }
786
        }
787
    }
788
    return deck_cost;
94,280 ✔
789
}
94,280 ✔
790

791
inline unsigned get_required_cards_before_upgrade(const std::vector<const Card *> &card_list, std::map<const Card *, unsigned> &num_cards)
94,280 ✔
792
{
793
    return get_required_cards_before_upgrade(owned_cards, card_list, num_cards);
29,114 ✔
794
}
795

796
unsigned get_deck_cost(const Deck *deck)
32,345 ✔
797
{
798
    if (!use_owned_cards)
32,345 ✔
799
    {
800
        return 0;
801
    }
802
    std::map<const Card *, unsigned> num_in_deck;
32,345 ✔
803
    unsigned deck_cost = 0;
32,345 ✔
804
    if (deck->commander)
32,345 ✔
805
    {
806
        deck_cost += get_required_cards_before_upgrade({deck->commander}, num_in_deck);
58,228 ✔
807
    }
808
    deck_cost += get_required_cards_before_upgrade(deck->cards, num_in_deck);
32,345 ✔
809
    for (auto it : num_in_deck)
215,773 ✔
810
    {
811
        unsigned card_id = it.first->m_id;
184,703 ✔
812
        if (it.second > owned_cards[card_id])
184,703 ✔
813
        {
814
            return UINT_MAX;
1,275 ✔
815
        }
816
    }
817
    return deck_cost;
818
}
32,345 ✔
819

820
bool is_in_recipe(const Card *card, const Card *material)
×
821
{
822
    // is it already material?
823
    if (card == material)
×
824
    {
825
        return true;
826
    }
827

828
    // no recipes
829
    if (card->m_recipe_cards.empty())
×
830
    {
831
        return false;
832
    }
833

834
    // avoid illegal
835
    if (card->m_category == CardCategory::dominion_material)
×
836
    {
837
        return false;
838
    }
839

840
    // check recursively
841
    for (auto recipe_it : card->m_recipe_cards)
×
842
    {
843
        // is material found?
844
        if (recipe_it.first == material)
×
845
        {
846
            return true;
×
847
        }
848

849
        // go deeper ...
850
        if (is_in_recipe(recipe_it.first, material))
×
851
        {
852
            return true;
853
        }
854
    }
855

856
    // found nothing
857
    return false;
858
}
859

860
bool is_owned_or_can_be_fused(const Card *card)
49,441 ✔
861
{
862
    if (owned_cards[card->m_id])
49,441 ✔
863
    {
864
        return true;
865
    }
866
    if (!fund && (card->m_category == CardCategory::normal))
49,217 ✔
867
    {
868
        return false;
869
    }
870
    std::map<const Card *, unsigned> num_in_deck;
×
871
    unsigned deck_cost = get_required_cards_before_upgrade({card}, num_in_deck);
×
872
    if ((card->m_category == CardCategory::normal) && (deck_cost > fund))
×
873
    {
874
        while (!card->is_low_level_card() && (deck_cost > fund))
×
875
        {
876
            card = card->downgraded();
×
877
            num_in_deck.clear();
×
878
            deck_cost = get_required_cards_before_upgrade({card}, num_in_deck);
×
879
        }
880
        if (deck_cost > fund)
×
881
        {
882
            return false;
883
        }
884
    }
885
    std::map<unsigned, unsigned> num_under;
×
886
    for (auto it : num_in_deck)
×
887
    {
888
        if (it.second > owned_cards[it.first->m_id])
×
889
        {
890
            if ((card->m_category == CardCategory::dominion_alpha) && use_maxed_dominions && !is_in_recipe(card, owned_alpha_dominion))
×
891
            {
892
                if (it.first->m_id != 50002)
×
893
                {
894
                    num_under[it.first->m_id] += it.second - owned_cards[it.first->m_id];
×
895
                }
896
                continue;
×
897
            }
898
            return false;
×
899
        }
900
    }
901
    if (!num_under.empty())
×
902
    {
903
        std::map<const Card *, unsigned> &refund = dominion_refund[owned_alpha_dominion->m_fusion_level][owned_alpha_dominion->m_level];
×
904
        for (auto &refund_it : refund)
×
905
        {
906
            unsigned refund_id = refund_it.first->m_id;
×
907
            if (!num_under.count(refund_id))
×
908
            {
909
                continue;
×
910
            }
911
            num_under[refund_id] = safe_minus(num_under[refund_id], refund_it.second);
×
912
            if (!num_under[refund_id])
×
913
            {
914
                num_under.erase(refund_id);
×
915
            }
916
        }
917
    }
918
    return num_under.empty();
×
919
}
×
920

921
std::string alpha_dominion_cost(const Card *dom_card)
×
922
{
923
    assert(dom_card->m_category == CardCategory::dominion_alpha);
×
924
    if (!owned_alpha_dominion)
×
925
    {
926
        return "(no owned alpha dominion)";
×
927
    }
928
    std::unordered_map<unsigned, unsigned> _owned_cards;
×
929
    std::unordered_map<unsigned, unsigned> refund_owned_cards;
×
930
    std::map<const Card *, unsigned> num_cards;
×
931
    std::map<const Card *, unsigned> &refund = dominion_refund[owned_alpha_dominion->m_fusion_level][owned_alpha_dominion->m_level];
×
932
    unsigned own_dom_id = 50002;
×
933
    if (is_in_recipe(dom_card, owned_alpha_dominion))
×
934
    {
935
        own_dom_id = owned_alpha_dominion->m_id;
×
936
    }
937
    else if (owned_alpha_dominion->m_id != 50002)
×
938
    {
939
        for (auto &it : refund)
×
940
        {
941
            if (it.first->m_category != CardCategory::dominion_material)
×
942
            {
943
                continue;
×
944
            }
945
            refund_owned_cards[it.first->m_id] += it.second;
×
946
        }
947
    }
948
    _owned_cards[own_dom_id] = 1;
×
949
    get_required_cards_before_upgrade(_owned_cards, {dom_card}, num_cards);
×
950
    std::string value("");
×
951
    for (auto &it : num_cards)
×
952
    {
953
        if (it.first->m_category != CardCategory::dominion_material)
×
954
        {
955
            continue;
×
956
        }
957
        value += it.first->m_name + " x " + std::to_string(it.second) + ", ";
×
958
    }
959
    if (!is_in_recipe(dom_card, owned_alpha_dominion))
×
960
    {
961
        num_cards.clear();
×
962
        get_required_cards_before_upgrade(_owned_cards, {owned_alpha_dominion}, num_cards);
×
963
        value += "using refund: ";
×
964
        for (auto &it : refund)
×
965
        {
966
            signed num_under(it.second - (signed)num_cards[it.first]);
×
967
            value += it.first->m_name + " x " + std::to_string(it.second) + "/" + std::to_string(num_under) + ", ";
×
968
        }
969
    }
970
    // remove trailing ', ' for non-empty string / replace empty by '(none)'
971
    if (!value.empty())
×
972
    {
973
        value.erase(value.end() - 2, value.end());
×
974
    }
975
    else
976
    {
977
        value += "(none)";
×
978
    }
979
    return value;
×
980
}
×
981

982
// check if claim_cards is necessary => i.e. can the deck be build from the ownedcards
983
bool claim_cards_needed(const std::vector<const Card *> &card_list)
32,807 ✔
984
{
985
    std::map<const Card *, unsigned> num_cards;
32,807 ✔
986
    get_required_cards_before_upgrade(card_list, num_cards);
32,807 ✔
987
    for (const auto &it : num_cards)
142,980 ✔
988
    {
989
        const Card *card = it.first;
114,825 ✔
990
        if (card->m_category == CardCategory::dominion_material && use_maxed_dominions)
114,825 ✔
991
            continue;
×
992
        if (card->m_category == CardCategory::dominion_alpha && use_maxed_dominions)
114,825 ✔
993
            continue;
×
994
        unsigned num_to_claim = safe_minus(it.second, owned_cards[card->m_id]);
114,825 ✔
995
        if (num_to_claim > 0)
996
        {
997
            return true;
32,807 ✔
998
        }
999
    }
1000
    return false;
1001
}
32,807 ✔
1002

1003
void claim_cards(const std::vector<const Card *> &card_list)
14 ✔
1004
{
1005
    std::map<const Card *, unsigned> num_cards;
14 ✔
1006
    get_required_cards_before_upgrade(card_list, num_cards);
14 ✔
1007
    for (const auto &it : num_cards)
91 ✔
1008
    {
1009
        const Card *card = it.first;
77 ✔
1010
        if (card->m_category == CardCategory::dominion_material)
77 ✔
1011
            continue;
×
1012
        if (card->m_category == CardCategory::dominion_alpha)
77 ✔
1013
            continue;
×
1014
        unsigned num_to_claim = safe_minus(it.second, owned_cards[card->m_id]);
154 ✔
1015
        if (num_to_claim > 0)
77 ✔
1016
        {
1017
            owned_cards[card->m_id] += num_to_claim;
77 ✔
1018
            if (debug_print >= 0)
77 ✔
1019
            {
1020
                std::cerr << "WARNING: Need extra " << num_to_claim << " " << card->m_name << " to build your initial deck: adding to owned card list.\n";
77 ✔
1021
            }
1022
        }
1023
    }
1024
}
14 ✔
1025

1026
bool valid_deck(Deck *your_deck)
12,489 ✔
1027
{
1028
    if (claim_cards_needed({your_deck->commander}))
12,489 ✔
1029
        return false;
1030
    if (claim_cards_needed(your_deck->cards))
12,489 ✔
1031
        return false;
1032
    if (your_deck->alpha_dominion && claim_cards_needed({your_deck->alpha_dominion}))
7,837 ✔
1033
        return false;
1034
    return true; // valid
1035
}
1036
//------------------------------------------------------------------------------
1037
FinalResults<long double> compute_score(const EvaluatedResults &results, std::vector<long double> &factors)
3,886 ✔
1038
{
1039
    FinalResults<long double> final{0, 0, 0, 0, 0, 0, results.second};
3,886 ✔
1040
    long double max_possible = max_possible_score[(size_t)optimization_mode];
3,886 ✔
1041
    for (unsigned index(0); index < results.first.size(); ++index)
11,724 ✔
1042
    {
1043
        // std::cout << results.second << " " << results.first[index].points << " " << results.first[index].count << std::endl;
1044
        final.wins += results.first[index].wins * factors[index] * results.second / results.first[index].count;
7,838 ✔
1045
        final.draws += results.first[index].draws * factors[index] * results.second / results.first[index].count;
7,838 ✔
1046
        final.losses += results.first[index].losses * factors[index] * results.second / results.first[index].count;
7,838 ✔
1047
        // APN
1048
        auto trials = results.second;
7,838 ✔
1049
        auto prob = 1 - confidence_level;
7,838 ✔
1050
        auto successes = results.first[index].points * results.second / results.first[index].count / max_possible;
7,838 ✔
1051
        if (successes > trials)
7,838 ✔
1052
        {
1053
            successes = trials;
×
1054
            // printf("WARNING: biominal successes > trials");
1055
            _DEBUG_MSG(2, "WARNING: biominal successes > trials");
×
1056
        }
1057

1058
        auto lower_bound = binomial_distribution::find_lower_bound_on_p(trials, successes, prob) * max_possible;
7,838 ✔
1059
        auto upper_bound = binomial_distribution::find_upper_bound_on_p(trials, successes, prob) * max_possible;
7,838 ✔
1060
        if (use_harmonic_mean)
7,838 ✔
1061
        {
1062
            final.points += factors[index] / (results.first[index].points * results.second / results.first[index].count);
×
1063
            final.points_lower_bound += factors[index] / lower_bound;
×
1064
            final.points_upper_bound += factors[index] / upper_bound;
×
1065
        }
1066
        else
1067
        {
1068
            final.points += results.first[index].points * factors[index] * results.second / results.first[index].count;
7,838 ✔
1069
            final.points_lower_bound += lower_bound * factors[index];
7,838 ✔
1070
            final.points_upper_bound += upper_bound * factors[index];
7,838 ✔
1071
        }
1072
    }
1073
    long double factor_sum = std::accumulate(factors.begin(), factors.end(), 0.);
3,886 ✔
1074
    final.wins /= factor_sum * (long double)results.second;
3,886 ✔
1075
    final.draws /= factor_sum * (long double)results.second;
3,886 ✔
1076
    final.losses /= factor_sum * (long double)results.second;
3,886 ✔
1077
    if (use_harmonic_mean)
3,886 ✔
1078
    {
1079
        final.points = factor_sum / ((long double)results.second * final.points);
×
1080
        final.points_lower_bound = factor_sum / final.points_lower_bound;
×
1081
        final.points_upper_bound = factor_sum / final.points_upper_bound;
×
1082
    }
1083
    else
1084
    {
1085
        final.points /= factor_sum * (long double)results.second;
3,886 ✔
1086
        final.points_lower_bound /= factor_sum;
3,886 ✔
1087
        final.points_upper_bound /= factor_sum;
3,886 ✔
1088
    }
1089
    return final;
3,886 ✔
1090
}
1091
//------------------------------------------------------------------------------
1092
//------------------------------------------------------------------------------
1093
// Per thread data.
1094
// seed should be unique for each thread.
1095
// d1 and d2 are intended to point to read-only process-wide data.
1096

1097
void SimulationData::set_decks(std::vector<Deck *> const your_decks_, std::vector<Deck *> const &enemy_decks_)
3,343 ✔
1098
{
1099
    for (unsigned i(0); i < your_decks_.size(); ++i)
7,127 ✔
1100
    {
1101
        your_decks[i].reset(your_decks_[i]->clone());
3,784 ✔
1102
        your_hands[i]->deck = your_decks[i].get();
3,784 ✔
1103
    }
1104
    for (unsigned i(0); i < enemy_decks_.size(); ++i)
7,127 ✔
1105
    {
1106
        enemy_decks[i].reset(enemy_decks_[i]->clone());
3,784 ✔
1107
        enemy_hands[i]->deck = enemy_decks[i].get();
3,784 ✔
1108
    }
1109
}
3,343 ✔
1110

1111
std::vector<std::unordered_map<std::string, std::string>> Process::samples()
1 ✔
1112
{
1113
    std::vector<std::unordered_map<std::string, std::string>> samples;
1 ✔
1114

1115
    int i = 0;
1 ✔
1116
    // loop over partial ids and prefix with f add to fmap
1117
    auto ids = partial_ids();
1 ✔
1118
    for (auto const &ydeck : your_decks)
2 ✔
1119
    {
1120
        auto yids = ydeck->sorted_ids();
1 ✔
1121
        for (auto const &edeck : enemy_decks)
2 ✔
1122
        {
1123
            auto eids = edeck->sorted_ids();
1 ✔
1124
            std::unordered_map<std::string, std::string> fmap;
1 ✔
1125
            i = 0;
1 ✔
1126
            for (auto const &id : ids)
92 ✔
1127
            {
1128
                fmap.emplace("f" + std::to_string(i), std::to_string(id));
182 ✔
1129
                i++;
91 ✔
1130
            }
1131
            i = 0;
1 ✔
1132
            for (auto const &id : yids)
13 ✔
1133
            {
1134
                fmap.emplace("y" + std::to_string(i), std::to_string(id->m_id));
24 ✔
1135
                i++;
12 ✔
1136
            }
1137
            // fill up with zeros up to id 12
1138
            while (i < 12)
1 ✔
1139
            {
1140
                fmap.emplace("y" + std::to_string(i), std::to_string(0));
×
1141
                i++;
×
1142
            }
1143
            i = 0;
1 ✔
1144
            for (auto const &id : eids)
13 ✔
1145
            {
1146
                fmap.emplace("e" + std::to_string(i), std::to_string(id->m_id));
24 ✔
1147
                i++;
12 ✔
1148
            }
1149
            // fill up with zeros up to id 12
1150
            while (i < 12)
1 ✔
1151
            {
1152
                fmap.emplace("e" + std::to_string(i), std::to_string(0));
×
1153
                i++;
×
1154
            }
1155
            samples.emplace_back(fmap);
1 ✔
1156
        }
1 ✔
1157
    }
1 ✔
1158
    /*
1159
    auto myMap = samples.at(0);
1160
    for(auto it = myMap.begin(); it != myMap.end(); ++it)
1161
    {
1162
        std::cout << it->first << " " << it->second  <<"\n";
1163
    }
1164
    */
1165

1166
    return samples;
1 ✔
1167
}
1 ✔
1168

1169
std::vector<std::array<std::string, 3>> Process::hashes()
3,264 ✔
1170
{
1171
    std::vector<std::array<std::string, 3>> hashes;
3,264 ✔
1172
    hashes.reserve(your_decks.size() * enemy_decks.size());
3,264 ✔
1173
    std::string hash = partial_hash();
3,264 ✔
1174
    for (auto const &ydeck : your_decks)
6,756 ✔
1175
    {
1176
        for (auto const &edeck : enemy_decks)
8,732 ✔
1177
        {
1178
            hashes.emplace_back(std::array<std::string, 3>{hash, ydeck->hash(), edeck->hash()});
15,720 ✔
1179
        }
1180
    }
1181
    return hashes;
3,264 ✔
1182
}
3,264 ✔
1183

1184
std::vector<unsigned int> Process::partial_ids()
3,265 ✔
1185
{
1186
    std::vector<unsigned int> ids;
3,265 ✔
1187
    ids.emplace_back(gamemode);
3,265 ✔
1188
    ids.emplace_back(optimization_mode);
3,265 ✔
1189
    for (int i = 0; i < Fix::num_fixes; ++i)
45,710 ✔
1190
    {
1191
        ids.emplace_back(fixes[i]);
42,445 ✔
1192
    }
1193
    ids.emplace_back(flexible_iter);
3,265 ✔
1194
    ids.emplace_back(flexible_turn);
3,265 ✔
1195
    ids.emplace_back(eval_iter);
3,265 ✔
1196
    ids.emplace_back(eval_turn);
3,265 ✔
1197
    for (int i = 0; i < PassiveBGE::num_passive_bges; ++i)
91,420 ✔
1198
        ids.emplace_back(your_bg_effects[i]);
88,155 ✔
1199
    for (int i = 0; i < PassiveBGE::num_passive_bges; ++i)
91,420 ✔
1200
        ids.emplace_back(enemy_bg_effects[i]);
88,155 ✔
1201
    if (your_bg_skills.size() > 0)
3,265 ✔
1202
    {
1203
        auto bge = your_bg_skills[0];
1 ✔
1204
        ids.emplace_back(bge.id);
1 ✔
1205
        ids.emplace_back(bge.x);
1 ✔
1206
        ids.emplace_back(bge.y);
1 ✔
1207
        ids.emplace_back(bge.n);
1 ✔
1208
        ids.emplace_back(bge.c);
1 ✔
1209
        ids.emplace_back(bge.s);
1 ✔
1210
        ids.emplace_back(bge.s2);
1 ✔
1211
        ids.emplace_back(bge.all);
1 ✔
1212
        ids.emplace_back(bge.card_id);
1 ✔
1213
    }
1214
    else
1215
    {
1216
        // emplace back 9 zeros
1217
        for (int i = 0; i < 9; ++i)
32,640 ✔
1218
            ids.emplace_back(0);
29,376 ✔
1219
    }
1220
    if (enemy_bg_skills.size() > 0)
3,265 ✔
1221
    {
1222
        auto bge = enemy_bg_skills[0];
1 ✔
1223
        ids.emplace_back(bge.id);
1 ✔
1224
        ids.emplace_back(bge.x);
1 ✔
1225
        ids.emplace_back(bge.y);
1 ✔
1226
        ids.emplace_back(bge.n);
1 ✔
1227
        ids.emplace_back(bge.c);
1 ✔
1228
        ids.emplace_back(bge.s);
1 ✔
1229
        ids.emplace_back(bge.s2);
1 ✔
1230
        ids.emplace_back(bge.all);
1 ✔
1231
        ids.emplace_back(bge.card_id);
1 ✔
1232
    }
1233
    else
1234
    {
1235
        // emplace back 9 zeros
1236
        for (int i = 0; i < 9; ++i)
32,640 ✔
1237
            ids.emplace_back(0);
29,376 ✔
1238
    }
1239

1240
    return ids;
3,265 ✔
1241
}
×
1242

1243
// Compute field hash from two decks
1244
std::string Process::partial_hash()
3,264 ✔
1245
{
1246
    // TODO fail if quest enabled since, db caching is incompatible with quest mode
1247
    std::stringstream ios;
3,264 ✔
1248
    for (auto id : partial_ids())
300,288 ✔
1249
        encode_id_ext_b64(ios, id);
300,288 ✔
1250

1251
    return ios.str();
6,528 ✔
1252
}
3,264 ✔
1253

1254
inline std::vector<Results<uint64_t>> SimulationData::evaluate(const std::vector<bool> &deck_mask)
1,313,441 ✔
1255
{
1256
    std::vector<Results<uint64_t>> res;
1,313,441 ✔
1257
    res.reserve(enemy_hands.size() * your_hands.size());
1,313,441 ✔
1258
    assert(deck_mask.size() == your_hands.size() * enemy_hands.size());
1,313,441 ✔
1259
    int i = 0;
1260
    for (Hand *your_hand : your_hands)
2,648,182 ✔
1261
    {
1262
        for (Hand *enemy_hand : enemy_hands)
2,834,682 ✔
1263
        {
1264
            // TUO5 added mask to already computed decks from db
1265
            if (deck_mask[i] != 0)
1,499,941 ✔
1266
            {
1267
                your_hand->reset(re);
1,499,941 ✔
1268
                enemy_hand->reset(re);
1,499,941 ✔
1269
                Field fd(re, cards, *your_hand, *enemy_hand, gamemode, optimization_mode,
1,499,941 ✔
1270
#ifndef NQUEST
1271
                         quest,
1272
#endif
1273
                         your_bg_effects, enemy_bg_effects, your_bg_skills, enemy_bg_skills, fixes, flexible_iter, flexible_turn, eval_iter, eval_turn);
1,499,941 ✔
1274
                Results<uint64_t> result(play(&fd));
1,499,941 ✔
1275
                if (__builtin_expect(mode_open_the_deck, false))
1,499,941 ✔
1276
                {
1277
                    // are there remaining (unopened) cards?
1278
                    if (fd.players[1]->deck->shuffled_cards.size())
×
1279
                    {
1280
                        // apply min score (there are unopened cards, so mission failed)
1281
                        result.points = min_possible_score[(size_t)optimization_mode];
×
1282
                    }
1283
                }
1284
                res.emplace_back(result);
1,499,941 ✔
1285
            }
1,499,941 ✔
1286
            else
1287
            {
1288
                res.emplace_back(Results<uint64_t>()); // no change since masked
×
1289
            }
1290
            i++;
1,499,941 ✔
1291
        }
1292
    }
1293
    // std::cout << std::endl<<  "Deck hash: " << your_hand.deck->hash() << "#"<< std::endl;
1294
    return (res);
1,313,441 ✔
1295
}
×
1296

1297
inline std::vector<Results<uint64_t>> SimulationData::evaluate()
1298
{
1299
    return evaluate(std::vector<bool>(your_hands.size() * enemy_hands.size(), true));
1300
}
1301
//------------------------------------------------------------------------------
1302

1303
//------------------------------------------------------------------------------
1304
// Process
1305
#ifdef _OPENMP
1306
void Process::openmp_evaluate_reduction(EvaluatedResults &evaluated_results)
1307
{
1308

1309
    std::vector<Results<uint64_t>> save_results(evaluated_results.first);
1310
    std::vector<Results<uint64_t>> results(evaluated_results.first);
1311
#pragma omp declare reduction(VecPlus                            \
1312
                              : std::vector <Results <uint64_t>> \
1313
                              : omp_out = merge(omp_out, omp_in))
1314
#pragma omp parallel default(none) shared(evaluated_results, thread_num_iterations, results)
1315
    {
1316
        SimulationData *sim = threads_data.at(omp_get_thread_num());
1317
        sim->set_decks(this->your_decks, this->enemy_decks);
1318
#pragma omp for reduction(VecPlus \
1319
                          : results) schedule(runtime)
1320
        for (unsigned i = 0; i < thread_num_iterations; ++i)
1321
        {
1322
            if (results.size() == 0)
1323
                results = sim->evaluate(mask); // calculate single sim
1324
            else
1325
            {
1326
                results = merge(results, sim->evaluate(mask)); // calculate single sim
1327
            }
1328
        }
1329
#pragma omp for schedule(runtime)
1330
        for (unsigned i = 0; i < results.size(); ++i)
1331
            evaluated_results.first[i] = results[i]; //+?
1332
    }
1333
    evaluated_results.second += thread_num_iterations;
1334
}
1335

1336
void Process::openmp_compare_reduction(EvaluatedResults &evaluated_results)
1337
{
1338

1339
    const unsigned c_num_threads = opt_num_threads;
1340
    std::vector<Results<uint64_t>> save_results(evaluated_results.first);
1341
    std::vector<Results<uint64_t>> results(evaluated_results.first);
1342
    bool compare_stop{false};
1343
    unsigned trials[c_num_threads] = {0};
1344
    long double successes[c_num_threads] = {.0};
1345
    const long double max_possible = max_possible_score[(size_t)optimization_mode];
1346
    const long double prob = 1 - confidence_level;
1347
    omp_lock_t locks[c_num_threads];
1348
    for (unsigned i = 0; i < c_num_threads; ++i)
1349
        omp_init_lock(&locks[i]);
1350
#pragma omp declare reduction(VecPlus                            \
1351
                              : std::vector <Results <uint64_t>> \
1352
                              : omp_out = merge(omp_out, omp_in))
1353
#pragma omp parallel default(none) shared(evaluated_results, trials, successes, locks, compare_stop, thread_num_iterations, results, \
1354
                                          thread_best_results, min_increment_of_score)
1355
    {
1356
        SimulationData *sim = threads_data.at(omp_get_thread_num());
1357
        sim->set_decks(this->your_decks, this->enemy_decks);
1358
        const long double sim_accum = std::accumulate(sim->factors.begin(), sim->factors.end(), .0);
1359
#pragma omp for reduction(VecPlus \
1360
                          : results) schedule(runtime)
1361
        for (unsigned i = 0; i < thread_num_iterations; ++i)
1362
        {
1363
#pragma omp cancellation point for
1364
            if (!compare_stop)
1365
            {
1366
                if (results.size() == 0)
1367
                    results = sim->evaluate(mask); // calculate single sim
1368
                else
1369
                    results = merge(results, sim->evaluate(mask)); // calculate single sim
1370
                long double score_accum_d = 0.0;
1371
                for (unsigned j = 0; j < results.size(); ++j)
1372
                    score_accum_d += results[j].points * sim->factors[j];
1373
                score_accum_d /= sim_accum * max_possible;
1374
                omp_set_lock(&locks[omp_get_thread_num()]);
1375
                trials[omp_get_thread_num()]++;
1376
                successes[omp_get_thread_num()] = score_accum_d;
1377
                omp_unset_lock(&locks[omp_get_thread_num()]);
1378
                // #pragma omp master
1379
                if (omp_get_thread_num() == 0)
1380
                {
1381

1382
                    unsigned ttrials = 0;
1383
                    long double ssuccesses = 0.0;
1384
                    for (unsigned l = 0; l < c_num_threads; ++l)
1385
                    {
1386
                        omp_set_lock(&locks[l]);
1387
                        ttrials += trials[l];
1388
                        ssuccesses += successes[l];
1389
                        omp_unset_lock(&locks[l]);
1390
                    }
1391
                    if (ssuccesses > ttrials)
1392
                    {
1393
                        ssuccesses = ttrials;
1394
                        printf("WARNING: biominal successes {%Le} > trials {%d} in Threads\n", ssuccesses, ttrials);
1395
                        //_DEBUG_MSG(2,"WARNING: biominal successes > trials in Threads");
1396
                    }
1397
                    compare_stop = (binomial_distribution::find_upper_bound_on_p(ttrials, ssuccesses, prob) * max_possible <
1398
                                    thread_best_results->points + min_increment_of_score);
1399
                    if (compare_stop)
1400
                    {
1401
#pragma omp cancel for
1402
                    }
1403
                }
1404
            }
1405
        }
1406
#pragma omp for schedule(runtime)
1407
        for (unsigned i = 0; i < results.size(); ++i)
1408
            evaluated_results.first[i] = results[i]; //+?
1409
    }
1410
    evaluated_results.second += thread_num_iterations;
1411
    for (unsigned i = 0; i < c_num_threads; ++i)
1412
        omp_destroy_lock(&locks[i]);
1413
}
1414

1415
std::vector<Results<uint64_t>> merge(std::vector<Results<uint64_t>> out, std::vector<Results<uint64_t>> in)
1416
{
1417
    // printf("merging out: %d in: %d \n", (int)out[0].wins, (int)in[0].wins);
1418
    // printf("out%p ",(void *)&out );
1419
    for (unsigned i = 0; i < out.size(); ++i)
1420
        out[i] += in[i];
1421
    // printf("merged out: %d \n", (int)out[0].wins);
1422
    return out;
1423
}
1424
#endif
1425

1426
inline bool Process::eval_ml(unsigned num_iterations, EvaluatedResults &evaluated_results)
3,259 ✔
1427
{
1428
    if (!use_ml)
3,259 ✔
1429
        return true;
1430
    bool run = false;
1 ✔
1431
    auto sampls = samples();
1 ✔
1432
    // iterate results from samples()
1433
    for (unsigned i = 0; i < sampls.size(); i++)
2 ✔
1434
    {
1435
        // already found in db?
1436
        if (mask[i])
1 ✔
1437
        {
1438
            auto s = sampls[i];
1 ✔
1439
            auto wins = atof(win_model.predict(s).c_str());
1 ✔
1440
            auto losses = atof(loss_model.predict(s).c_str());
1 ✔
1441
            auto draws = atof(stall_model.predict(s).c_str());
1 ✔
1442
            auto points = atof(points_model.predict(s).c_str());
1 ✔
1443
            if (wins < 0)
1 ✔
1444
                wins = 0;
1445
            if (losses < 0)
1 ✔
1446
                losses = 0;
1447
            if (draws < 0)
1 ✔
1448
                draws = 0;
1449
            if (points < 0)
1 ✔
1450
                points = 0;
1451
            // if((wins + losses + draws) > 1.05 || (wins + losses + draws) < 0.95) {
1452
            //     std::cout << "WARNING: ML model returned invalid sample: " << wins << " "  << draws << " " <<losses << " points " << points << std::endl;
1453
            // }
1454
            if (use_only_ml || ((wins + losses + draws) < 1.00 + ml_precision && (wins + losses + draws) > 1.00 - ml_precision)) // we use the sum of wins, losses and draws to determine if the sample is valid
1 ✔
1455
            {
1456
                // std::cout << "ML model returned: " << wins << " "  << draws << " " <<losses << " points " << points << " " << num_iterations << std::endl;
1457
                mask[i] = false;
1 ✔
1458
                Results<uint64_t> r = {
1 ✔
1459
                    static_cast<uint64_t>(std::round((1.0 * wins * num_iterations / (wins + losses + draws)))),
1 ✔
1460
                    static_cast<uint64_t>(std::round((1.0 * draws * num_iterations / (wins + losses + draws)))),
1 ✔
1461
                    static_cast<uint64_t>(std::round((1.0 * losses * num_iterations / (wins + losses + draws)))),
1 ✔
1462
                    static_cast<uint64_t>(std::round((1.0 * points * num_iterations))),
1 ✔
1463
                    static_cast<uint64_t>(num_iterations)};
1 ✔
1464
                evaluated_results.first[i] = r;
1 ✔
1465
            }
1 ✔
1466
            else
1467
            {
1468
                mask[i] = true;
×
1469
                run = true;
×
1470
            }
1471
        }
1 ✔
1472
    }
1473

1474
    return run;
1 ✔
1475
}
1 ✔
1476

1477
inline bool Process::check_db(std::vector<std::array<std::string, 3>> const &vhashes, unsigned num_iterations, EvaluatedResults &evaluated_results)
3,264 ✔
1478
{
1479
    if (!use_db_load)
3,264 ✔
1480
        return true;
1481
    bool run = false;
1482
    // TODO TUO5 check db for results
1483
    //  TODO TUO5 calculate mask for sim evaluate based on missing results in db
1484
    for (unsigned i = 0; i < vhashes.size(); i++)
2,168 ✔
1485
    {
1486
        bool found = false;
2,072 ✔
1487
        std::string hash = vhashes[i][0];
2,072 ✔
1488
        // TODO TUO5 check db for hash
1489
        auto it1 = database.find(hash);
2,072 ✔
1490
        std::map<std::string, Results<uint64_t>>::iterator it;
2,072 ✔
1491
        if (it1 != database.end())
2,072 ✔
1492
        {
1493
            auto it2 = it1->second.find(vhashes[i][1]);
682 ✔
1494
            if (it2 != it1->second.end())
682 ✔
1495
            {
1496
                auto it3 = it2->second.find(vhashes[i][2]);
117 ✔
1497
                if (it3 != it2->second.end())
117 ✔
1498
                {
1499
                    it = it3;
116 ✔
1500
                    found = true;
116 ✔
1501
                    // std::cout << "hit databse" << std::endl;
1502
                }
1503
            }
1504
        }
1505
        // TODO TUO5 if hash not in db, add to mask
1506
        if (!found)
116 ✔
1507
        {
1508
            mask[i] = true;
1,956 ✔
1509
            run = true;
1,956 ✔
1510
        }
1511
        else
1512
        {
1513
            if (it->second.count >= num_iterations)
116 ✔
1514
            {
1515
                mask[i] = false;
116 ✔
1516
                // TUO5 load results from db
1517
                // renormalized to asked num_iterations
1518
                Results<uint64_t> r = {
116 ✔
1519
                    static_cast<uint64_t>(std::round((1.0 * it->second.wins * num_iterations) / it->second.count)),
116 ✔
1520
                    static_cast<uint64_t>(std::round((1.0 * it->second.draws * num_iterations) / it->second.count)),
116 ✔
1521
                    static_cast<uint64_t>(std::round((1.0 * it->second.losses * num_iterations) / it->second.count)),
116 ✔
1522
                    static_cast<uint64_t>(std::round((1.0 * it->second.points * num_iterations) / it->second.count)),
116 ✔
1523
                    static_cast<uint64_t>(num_iterations)};
116 ✔
1524
                evaluated_results.first[i] = r;
116 ✔
1525
            }
1526
            else
1527
            {
1528
                mask[i] = true;
×
1529
                run = true;
×
1530
            }
1531
        }
1532
    }
2,072 ✔
1533
    return run;
1534
}
1535

1536
inline void Process::save_db(std::vector<std::array<std::string, 3>> const &vhashes, EvaluatedResults &evaluated_results)
3,258 ✔
1537
{
1538
    // TODO TUO5 save results to db
1539
    for (unsigned i = 0; i < vhashes.size(); i++)
8,381 ✔
1540
    {
1541
        if (mask[i])
5,123 ✔
1542
        {
1543
            std::array<std::string, 3> hash = vhashes[i];
5,123 ✔
1544
            // check if map is initialized otherwise initialize
1545
            if (database.find(hash[0]) == database.end())
5,123 ✔
1546
            {
1547
                database[hash[0]] = std::map<std::string, std::map<std::string, Results<uint64_t>>>();
50 ✔
1548
            }
1549
            if (database[hash[0]].find(hash[1]) == database[hash[0]].end())
5,123 ✔
1550
            {
1551
                database[hash[0]][hash[1]] = std::map<std::string, Results<uint64_t>>();
2,809 ✔
1552
            }
1553
            database[hash[0]][hash[1]][hash[2]] = evaluated_results.first[i];
5,123 ✔
1554
        }
5,123 ✔
1555
    }
1556
}
3,258 ✔
1557

1558
EvaluatedResults &Process::evaluate(unsigned num_iterations, EvaluatedResults &evaluated_results)
546 ✔
1559
{
1560
    if (num_iterations <= evaluated_results.second)
546 ✔
1561
    {
1562
        return evaluated_results;
1563
    }
1564
    std::vector<std::array<std::string, 3>> vhashes = hashes();
312 ✔
1565
    // fill mask with true
1566
    mask = std::vector<bool>(vhashes.size(), true);
312 ✔
1567
    if (!check_db(vhashes, num_iterations, evaluated_results))
312 ✔
1568
    {
1569
        // 100% covered by db
1570
        evaluated_results.second = num_iterations;
5 ✔
1571
        return evaluated_results;
5 ✔
1572
    }
1573
    if (!eval_ml(num_iterations, evaluated_results))
307 ✔
1574
    {
1575
        // ml is good
1576
        evaluated_results.second = num_iterations;
1 ✔
1577
        return evaluated_results;
1 ✔
1578
    }
1579

1580
    thread_num_iterations = num_iterations - evaluated_results.second;
306 ✔
1581
    thread_results = &evaluated_results;
306 ✔
1582
    thread_compare = false;
306 ✔
1583
#ifndef _OPENMP
1584
    // unlock all the threads
1585
    main_barrier.wait();
306 ✔
1586
    // wait for the threads
1587
    main_barrier.wait();
306 ✔
1588
#else
1589
    openmp_evaluate_reduction(evaluated_results);
1590
#endif
1591
    save_db(vhashes, evaluated_results);
306 ✔
1592

1593
    return evaluated_results;
1594
}
312 ✔
1595

1596
EvaluatedResults &Process::compare(unsigned num_iterations, EvaluatedResults &evaluated_results, const FinalResults<long double> &best_results)
3,221 ✔
1597
{
1598
    if (num_iterations <= evaluated_results.second)
3,221 ✔
1599
    {
1600
        return evaluated_results;
1601
    }
1602
    std::vector<std::array<std::string, 3>> vhashes = hashes();
2,952 ✔
1603
    // fill mask with true
1604
    mask = std::vector<bool>(vhashes.size(), true);
2,952 ✔
1605
    if (!check_db(vhashes, num_iterations, evaluated_results))
2,952 ✔
1606
    {
1607
        // 100% covered by db
1608
        evaluated_results.second = num_iterations;
×
1609
        return evaluated_results;
×
1610
    }
1611
    if (!eval_ml(num_iterations, evaluated_results))
2,952 ✔
1612
    {
1613
        // ml is good
1614
        evaluated_results.second = num_iterations;
×
1615
        return evaluated_results;
×
1616
    }
1617
    thread_num_iterations = num_iterations - evaluated_results.second;
2,952 ✔
1618
    thread_results = &evaluated_results;
2,952 ✔
1619
    thread_best_results = &best_results;
2,952 ✔
1620
    thread_compare = true;
2,952 ✔
1621
    thread_compare_stop = false;
2,952 ✔
1622
#ifndef _OPENMP
1623
    // unlock all the threads
1624
    main_barrier.wait();
2,952 ✔
1625
    // wait for the threads
1626
    main_barrier.wait();
2,952 ✔
1627
#else
1628
    openmp_compare_reduction(evaluated_results);
1629
#endif
1630
    save_db(vhashes, evaluated_results);
2,952 ✔
1631
    return evaluated_results;
1632
}
2,952 ✔
1633
//------------------------------------------------------------------------------
1634
void thread_evaluate(boost::barrier &main_barrier,
85 ✔
1635
                     boost::mutex &shared_mutex,
1636
                     SimulationData &sim,
1637
                     const Process &p,
1638
                     unsigned thread_id)
1639
{
1640
#ifndef _OPENMP
1641
    while (true)
6,601 ✔
1642
    {
1643
        main_barrier.wait();
3,343 ✔
1644
        sim.set_decks(p.your_decks, p.enemy_decks);
3,343 ✔
1645
        if (destroy_threads)
3,343 ✔
1646
        {
1647
            return;
85 ✔
1648
        }
1649
        while (true)
2,630,140 ✔
1650
        {
1651
            shared_mutex.lock();                                                       //<<<<
1,316,699 ✔
1652
            if (thread_num_iterations == 0 || (thread_compare && thread_compare_stop)) //!
1,316,699 ✔
1653
            {
1654
                shared_mutex.unlock(); //>>>>
3,258 ✔
1655
                main_barrier.wait();
3,258 ✔
1656
                break;
3,258 ✔
1657
            }
1658
            else
1659
            {
1660
                --thread_num_iterations; //!
1,313,441 ✔
1661
                shared_mutex.unlock();   //>>>>
1,313,441 ✔
1662
                std::vector<Results<uint64_t>> result{sim.evaluate(p.mask)};
1,313,441 ✔
1663
                shared_mutex.lock();                                                        //<<<<
1,313,441 ✔
1664
                std::vector<uint64_t> thread_score_local(thread_results->first.size(), 0u); //!
1,313,441 ✔
1665
                unsigned counter = 0;
1,313,441 ✔
1666
                for (unsigned index(0); index < result.size(); ++index)
2,813,382 ✔
1667
                {
1668
                    thread_results->first[index] += result[index]; //!
1,499,941 ✔
1669
                    if (counter == 0 || thread_results->first[index].count < counter)
1,499,941 ✔
1670
                    {
1671
                        counter = thread_results->first[index].count;
1,313,441 ✔
1672
                    }
1673
                }
1674
                for (unsigned index(0); index < result.size(); ++index)
2,813,382 ✔
1675
                {
1676
                    // TUO5 we weight scores by the number of times a deck is used, since the results are no langer same sized in partially cached case
1677
                    thread_score_local[index] = (thread_results->first[index].points * (counter)) / thread_results->first[index].count; //!
1,499,941 ✔
1678
                                                                                                                                        // thread_score_local[index] = static_cast<uint64_t>(std::round((thread_results->first[index].points * (counter))/thread_results->first[index].count)); //!
1679
                }
1680
                ++thread_results->second;                            //!
1,313,441 ✔
1681
                unsigned thread_total_local{thread_results->second}; //!
1,313,441 ✔
1682
                shared_mutex.unlock();                               //>>>>
1,313,441 ✔
1683
                if (thread_compare && thread_id == 0 && thread_total_local > 1)
1,313,441 ✔
1684
                {
1685
                    unsigned score_accum = 0;
869,043 ✔
1686
                    // Multiple defense decks case: scaling by factors and approximation of a "discrete" number of events.
1687
                    if (result.size() > 1)
869,043 ✔
1688
                    {
1689
                        long double score_accum_d = 0.0;
1690
                        for (unsigned i = 0; i < thread_score_local.size(); ++i)
×
1691
                        {
1692
                            score_accum_d += thread_score_local[i] * sim.factors[i];
×
1693
                        }
1694
                        score_accum_d /= std::accumulate(sim.factors.begin(), sim.factors.end(), .0);
×
1695
                        score_accum = score_accum_d;
×
1696
                    }
1697
                    else
1698
                    {
1699
                        score_accum = thread_score_local[0];
869,043 ✔
1700
                    }
1701
                    bool compare_stop(false);
869,043 ✔
1702
                    long double max_possible = max_possible_score[(size_t)optimization_mode];
869,043 ✔
1703

1704
                    // APN
1705
                    auto trials = thread_total_local;
869,043 ✔
1706
                    auto prob = 1 - confidence_level;
869,043 ✔
1707
                    auto successes = score_accum / max_possible;
869,043 ✔
1708
                    if (successes > trials)
869,043 ✔
1709
                    {
1710
                        std::cout << "WARNING: biominal successes > trials in Threads" << successes << " " << trials << " " << counter << std::endl;
×
1711
                        _DEBUG_MSG(2, "WARNING: biominal successes > trials in Threads");
×
1712
                        successes = trials;
1,313,441 ✔
1713
                    }
1714
                    else
1715
                    {
1716

1717
                        // Get a loose (better than no) upper bound. TODO: Improve it.
1718
                        compare_stop = (binomial_distribution::find_upper_bound_on_p(trials, successes, prob) * max_possible <
869,043 ✔
1719
                                        thread_best_results->points + min_increment_of_score);
869,043 ✔
1720
                        if (compare_stop)
869,043 ✔
1721
                        {
1722
                            shared_mutex.lock(); //<<<<
2,436 ✔
1723
                            // std::cout << thread_total_local << "\n";
1724
                            thread_compare_stop = true; //!
2,436 ✔
1725
                            shared_mutex.unlock();      //>>>>
2,436 ✔
1726
                        }
1727
                    }
1728
                }
1729
            }
1,313,441 ✔
1730
        }
1,313,441 ✔
1731
    }
3,258 ✔
1732
#endif
1733
}
1734
//------------------------------------------------------------------------------
1735
void print_score_info(const EvaluatedResults &results, std::vector<long double> &factors)
41 ✔
1736
{
1737
    auto final = compute_score(results, factors);
41 ✔
1738
    std::cout << final.points << " (";
41 ✔
1739
    if (!simplify_output)
41 ✔
1740
    {
1741
        if (show_ci)
41 ✔
1742
        {
1743
            std::cout << final.points_lower_bound << "-" << final.points_upper_bound << ", ";
×
1744
        }
1745
        for (const auto &val : results.first)
82 ✔
1746
        {
1747
            switch (optimization_mode)
41 ✔
1748
            {
1749
            case OptimizationMode::raid:
×
1750
            case OptimizationMode::campaign:
×
1751
            case OptimizationMode::brawl:
×
1752
            case OptimizationMode::brawl_defense:
×
1753
            case OptimizationMode::war:
×
1754
            case OptimizationMode::war_defense:
×
1755
#ifndef NQUEST
1756
            case OptimizationMode::quest:
1757
#endif
1758
                std::cout << val.points << " ";
×
1759
                break;
1760
            default:
41 ✔
1761
                std::cout << val.points / 100 << " ";
41 ✔
1762
                break;
1763
            }
1764
        }
1765
    }
1766
    else
1767
    {
1768
        std::cout << "...";
×
1769
    }
1770
    std::cout << "/ " << results.second << ")" << std::endl;
41 ✔
1771
}
41 ✔
1772
//------------------------------------------------------------------------------
1773
void print_results(const EvaluatedResults &results, std::vector<long double> &factors)
78 ✔
1774
{
1775
    auto final = compute_score(results, factors);
78 ✔
1776
    std::cout << "win%: " << final.wins * 100.0 << " (";
78 ✔
1777
    if (!simplify_output)
78 ✔
1778
    {
1779
        for (const auto &val : results.first)
2,132 ✔
1780
        {
1781
            std::cout << val.wins << " ";
2,054 ✔
1782
        }
1783
    }
1784
    else
1785
    {
1786
        std::cout << "...";
×
1787
    }
1788
    std::cout << "/ " << results.second << ")" << std::endl;
78 ✔
1789

1790
    std::cout << "stall%: " << final.draws * 100.0 << " (";
78 ✔
1791
    if (!simplify_output)
78 ✔
1792
    {
1793
        for (const auto &val : results.first)
2,132 ✔
1794
        {
1795
            std::cout << val.draws << " ";
2,054 ✔
1796
        }
1797
    }
1798
    else
1799
    {
1800
        std::cout << "...";
×
1801
    }
1802
    std::cout << "/ " << results.second << ")" << std::endl;
78 ✔
1803

1804
    std::cout << "loss%: " << final.losses * 100.0 << " (";
78 ✔
1805
    if (!simplify_output)
78 ✔
1806
    {
1807
        for (const auto &val : results.first)
2,132 ✔
1808
        {
1809
            std::cout << val.losses << " ";
2,054 ✔
1810
        }
1811
    }
1812
    else
1813
    {
1814
        std::cout << "...";
×
1815
    }
1816
    std::cout << "/ " << results.second << ")" << std::endl;
78 ✔
1817

1818
#ifndef NQUEST
1819
    if (optimization_mode == OptimizationMode::quest)
1820
    {
1821
        // points = win% * win_score + (must_win ? win% : 100%) * quest% * quest_score
1822
        // quest% = (points - win% * win_score) / (must_win ? win% : 100%) / quest_score
1823
        std::cout << "quest%: " << (final.points - final.wins * tuo::quest.win_score) / (tuo::quest.must_win ? final.wins : 1) / tuo::quest.quest_score * 100 << std::endl;
1824
    }
1825
#endif
1826

1827
    unsigned min_score = min_possible_score[(size_t)optimization_mode];
78 ✔
1828
    unsigned max_score = max_possible_score[(size_t)optimization_mode];
78 ✔
1829
    switch (optimization_mode)
78 ✔
1830
    {
1831
    case OptimizationMode::raid:
×
1832
    case OptimizationMode::campaign:
×
1833
    case OptimizationMode::brawl:
×
1834
    case OptimizationMode::brawl_defense:
×
1835
    case OptimizationMode::war:
×
1836
    case OptimizationMode::war_defense:
×
1837
#ifndef NQUEST
1838
    case OptimizationMode::quest:
1839
#endif
1840
        std::cout << "score: " << final.points;
×
1841
        if (optimization_mode == OptimizationMode::brawl)
×
1842
        {
1843
            auto win_points = final.wins ? ((final.points - min_score * (1.0 - final.wins)) / final.wins) : final.points;
×
1844
            std::cout << " [" << win_points << " per win]";
×
1845
        }
1846
        else if (optimization_mode == OptimizationMode::brawl_defense)
×
1847
        {
1848
            auto opp_win_points = final.losses ? max_score - ((final.points - (max_score - min_score) * (1.0 - final.losses)) / final.losses) : final.points;
×
1849
            std::cout << " [" << opp_win_points << " per opp win]";
×
1850
        }
1851
        else if (optimization_mode == OptimizationMode::war)
×
1852
        {
1853
            auto win_points = final.wins ? ((final.points - min_score * (1.0 - final.wins)) / final.wins) : final.points;
×
1854
            std::cout << " [" << win_points << " per win]";
×
1855
        }
1856
        else if (optimization_mode == OptimizationMode::war_defense)
×
1857
        {
1858
            auto opp_win_points = final.losses ? max_score - ((final.points - (max_score - min_score) * (1.0 - final.losses)) / final.losses) : final.points;
×
1859
            std::cout << " [" << opp_win_points << " per opp win]";
×
1860
        }
1861
        std::cout << " (";
×
1862
        if (!simplify_output)
×
1863
        {
1864
            for (const auto &val : results.first)
×
1865
            {
1866
                std::cout << val.points << " ";
×
1867
            }
1868
        }
1869
        else
1870
        {
1871
            std::cout << "...";
×
1872
        }
1873
        std::cout << "/ " << results.second << ")" << std::endl;
×
1874
        if (show_ci)
×
1875
        {
1876
            std::cout << "ci: " << final.points_lower_bound << " - " << final.points_upper_bound << std::endl;
×
1877
        }
1878
        break;
1879
    default:
1880
        break;
1881
    }
1882
}
78 ✔
1883

1884
//------------------------------------------------------------------------------
1885
// Prints which cards have been upgraded
1886
void print_upgraded_cards(Deck *deck)
7 ✔
1887
{
1888
    if (!print_upgraded)
7 ✔
1889
        return;
7 ✔
1890
    auto owned_cards_c = owned_cards;
×
1891
    std::cout << "Upgraded Cards: ";
×
1892
    auto cards = deck->cards;
×
1893
    cards.insert(cards.begin(), deck->commander);
×
1894
    for (const Card *card : cards)
×
1895
    {
1896

1897
        if ((card->m_set == 1000) && (card->m_rarity <= 2) && (card->is_low_level_card()))
×
1898
        {
1899
            continue;
×
1900
        }
1901

1902
        if ((card->m_id == 50002) || (card->m_category == CardCategory::dominion_material))
×
1903
        {
1904
            continue;
×
1905
        }
1906

1907
        if ((fund || (card->m_category != CardCategory::normal)) && (owned_cards_c[card->m_id] == 0))
×
1908
        {
1909
            // print card
1910
            std::cout << card->m_name << ", ";
×
1911
        }
1912
        if (owned_cards_c[card->m_id] > 0)
×
1913
            owned_cards_c[card->m_id]--;
×
1914
    }
1915
    std::cout << std::endl;
×
1916
}
×
1917
//------------------------------------------------------------------------------
1918
void print_cards_inline(std::vector<const Card *> cards, std::ostream &os, Deck *deck)
1,381 ✔
1919
{
1920
    std::string last_name = "";
1,381 ✔
1921
    unsigned num_repeat(0);
1,381 ✔
1922
    bool first = true;
1,381 ✔
1923

1924
    // for (const Card* card: cards)
1925
    //{
1926
    for (unsigned i = 0; i < cards.size(); ++i)
14,207 ✔
1927
    {
1928
        auto card = cards[i];
12,826 ✔
1929

1930
        if (deck == nullptr && card->m_name == last_name)
12,826 ✔
1931
        {
1932
            ++num_repeat;
×
1933
        }
1934
        else
1935
        {
1936
            if (num_repeat > 1)
12,826 ✔
1937
            {
1938
                os << " #" << num_repeat;
×
1939
            }
1940
            if (deck != nullptr)
12,826 ✔
1941
                os << (first ? "" : ", ") << (deck->card_marks[i] == '!' ? "!" : "") << card->m_name;
1,815 ✔
1942
            else
1943
                os << (first ? "" : ", ") << card->m_name;
23,094 ✔
1944
            first = false;
12,826 ✔
1945
            last_name = card->m_name;
25,652 ✔
1946
            num_repeat = 1;
1947
        }
1948
    }
1949
    if (num_repeat > 1)
1,381 ✔
1950
    {
1951
        os << " #" << num_repeat;
×
1952
    }
1953
    os << "\n";
1,381 ✔
1954
}
1,381 ✔
1955
void print_score_inline(const FinalResults<long double> score)
1,296 ✔
1956
{
1957
    // print optimization result details
1958
    switch (optimization_mode)
1,296 ✔
1959
    {
1960
    case OptimizationMode::raid:
×
1961
    case OptimizationMode::campaign:
×
1962
    case OptimizationMode::brawl:
×
1963
    case OptimizationMode::brawl_defense:
×
1964
    case OptimizationMode::war:
×
1965
    case OptimizationMode::war_defense:
×
1966
#ifndef NQUEST
1967
    case OptimizationMode::quest:
1968
#endif
1969
        std::cout << "(" << score.wins * 100 << "% win";
×
1970
#ifndef NQUEST
1971
        if (optimization_mode == OptimizationMode::quest)
1972
        {
1973
            std::cout << ", " << (score.points - score.wins * tuo::quest.win_score) / (tuo::quest.must_win ? score.wins : 1) / tuo::quest.quest_score * 100 << "% quest";
1974
        }
1975
#endif
1976
        if (show_ci)
×
1977
        {
1978
            std::cout << ", " << score.points_lower_bound << "-" << score.points_upper_bound;
×
1979
        }
1980
        std::cout << ") ";
×
1981
        break;
×
1982
    case OptimizationMode::defense:
×
1983
        std::cout << "(" << score.draws * 100.0 << "% stall) ";
×
1984
        break;
×
1985
    default:
1986
        break;
1987
    }
1988
    std::cout << score.points;
1,296 ✔
1989
    unsigned min_score = min_possible_score[(size_t)optimization_mode];
1,296 ✔
1990
    unsigned max_score = max_possible_score[(size_t)optimization_mode];
1,296 ✔
1991
    if (optimization_mode == OptimizationMode::brawl)
1,296 ✔
1992
    {
1993
        auto win_points = score.wins ? ((score.points - min_score * (1.0 - score.wins)) / score.wins) : score.points;
×
1994
        std::cout << " [" << win_points << " per win]";
×
1995
    }
1996
    else if (optimization_mode == OptimizationMode::brawl_defense)
1,296 ✔
1997
    {
1998
        auto opp_win_points = score.losses ? max_score - ((score.points - (max_score - min_score) * (1.0 - score.losses)) / score.losses) : score.points;
×
1999
        std::cout << " [" << opp_win_points << " per opp win]";
×
2000
    }
2001
    else if (optimization_mode == OptimizationMode::war)
1,296 ✔
2002
    {
2003
        auto win_points = score.wins ? ((score.points - min_score * (1.0 - score.wins)) / score.wins) : score.points;
×
2004
        std::cout << " [" << win_points << " per win]";
×
2005
    }
2006
    else if (optimization_mode == OptimizationMode::war_defense)
1,296 ✔
2007
    {
2008
        auto opp_win_points = score.losses ? max_score - ((score.points - (max_score - min_score) * (1.0 - score.losses)) / score.losses) : score.points;
×
2009
        std::cout << " [" << opp_win_points << " per opp win]";
×
2010
    }
2011
}
1,296 ✔
2012
//------------------------------------------------------------------------------
2013
// Calculates and prints individual card value in this deck
2014
void print_sim_card_values(Deck *original_deck, Process &p, unsigned iter) // run_deck == p.your_decks[0]
85 ✔
2015
{
2016
    if (!print_values && vc_x == 0)
85 ✔
2017
        return;
85 ✔
2018
    if (p.your_decks.size() != 1)
×
2019
        return; // only for single deck
2020
    // auto deck = original_deck;
2021
    if (original_deck->strategy == DeckStrategy::random || original_deck->strategy == DeckStrategy::flexible || original_deck->strategy == DeckStrategy::evaluate || original_deck->strategy == DeckStrategy::evaluate_twice)
×
2022
    {
2023
        std::sort(original_deck->cards.begin(), original_deck->cards.end(), [](const Card *a, const Card *b)
×
2024
                  { return a->m_id < b->m_id; });
×
2025
    }
2026
    std::string last_name;
×
2027
    long double score;
×
2028
    Deck *sim_deck = p.your_decks[0];
×
2029
    Deck *your_deck = original_deck->clone(); // save the original deck
×
2030
    auto cards = your_deck->cards;
×
2031
    // sim original/base result
2032
    sim_deck->commander = your_deck->commander;
×
2033
    sim_deck->cards = your_deck->cards;
×
2034
    sim_deck->alpha_dominion = your_deck->alpha_dominion;
×
2035
    EvaluatedResults results = {EvaluatedResults::first_type(p.enemy_decks.size() * p.your_decks.size()), 0};
×
2036
    results = p.evaluate(iter, results);
×
2037
    const FinalResults<long double> fr_base = compute_score(results, p.factors);
×
2038
    long double base = fr_base.points;
×
2039
    std::multimap<long double, std::string> msn;
×
2040
    std::multimap<std::string, long double> mns;
×
2041
    for (unsigned i = 0; i < cards.size(); ++i)
×
2042
    {
2043
        auto card = cards[i];
×
2044
        // if (card->m_name == last_name)
2045
        //{
2046
        // }
2047
        // else
2048
        //{
2049
        last_name = card->m_name;
×
2050
        // sim it
2051
        sim_deck->cards = your_deck->cards;                 // reset cards
×
2052
        sim_deck->cards.erase(sim_deck->cards.begin() + i); // remove to test card
×
2053
        EvaluatedResults results = {EvaluatedResults::first_type(p.enemy_decks.size() * p.your_decks.size()), 0};
×
2054
        results = p.evaluate(iter, results);
×
2055
        const FinalResults<long double> fr = compute_score(results, p.factors);
×
2056
        score = base - fr.points; // subtract from result to get value
×
2057
        // std::cout << card->m_name << " (" << score << "), ";
2058
        msn.insert(std::make_pair(score, card->m_name));
×
2059
        mns.insert(std::make_pair(card->m_name, score));
×
2060
        //}
2061
    }
×
2062
    sim_deck->cards = your_deck->cards; // reset cards
×
2063
    if (vc_x > 0)
×
2064
    {
2065
        // std::cout << "Locked Deck: ";
2066
        ////std::cout << original_deck->cards.size() << " units: ";
2067
        ////print_score_inline(fr_base);
2068
        ////std::cout <<  ": ";
2069
        // std::cout << original_deck->commander->m_name;
2070
        //  print dominions
2071
        // if (original_deck->alpha_dominion)
2072
        //{ std::cout << ", " << original_deck->alpha_dominion->m_name; }
2073

2074
        for (unsigned i = 0; i < cards.size(); ++i)
×
2075
        {
2076
            original_deck->card_marks.erase(i);
×
2077
            if (vc_x >= std::distance(msn.find(mns.find(cards[i]->m_name)->second), msn.end())) // or mns.start()
×
2078
            {
2079
                original_deck->card_marks[i] = '!';
×
2080
            }
2081
        }
2082
    }
2083
    if (print_values)
×
2084
    {
2085
        std::cout << "Value of Cards: ";
×
2086
        for (unsigned i = 0; i < cards.size(); ++i)
×
2087
        {
2088
            std::cout << cards[i]->m_name << " (" << mns.find(cards[i]->m_name)->second << "), ";
×
2089
        }
2090
        std::cout << std::endl;
×
2091
    }
2092
}
×
2093
//------------------------------------------------------------------------------
2094
void print_deck_inline(const unsigned deck_cost, const FinalResults<long double> score, Deck *deck, bool print_locked)
1,296 ✔
2095
{
2096
    // print units count
2097
    std::cout << deck->cards.size() << " units: ";
1,296 ✔
2098

2099
    // print deck cost (if fund is enabled)
2100
    if (fund > 0)
1,296 ✔
2101
    {
2102
        std::cout << "$" << deck_cost << " ";
×
2103
    }
2104
    print_score_inline(score);
1,296 ✔
2105
    /*
2106
    // print optimization result details
2107
    switch(optimization_mode)
2108
    {
2109
    case OptimizationMode::raid:
2110
    case OptimizationMode::campaign:
2111
    case OptimizationMode::brawl:
2112
    case OptimizationMode::brawl_defense:
2113
    case OptimizationMode::war:
2114
    case OptimizationMode::war_defense:
2115
#ifndef NQUEST
2116
case OptimizationMode::quest:
2117
#endif
2118
std::cout << "(" << score.wins * 100 << "% win";
2119
#ifndef NQUEST
2120
if (optimization_mode == OptimizationMode::quest)
2121
{
2122
std::cout << ", " << (score.points - score.wins * quest.win_score) / (quest.must_win ? score.wins : 1) / quest.quest_score * 100 << "% quest";
2123
}
2124
#endif
2125
if (show_ci)
2126
{
2127
std::cout << ", " << score.points_lower_bound << "-" << score.points_upper_bound;
2128
}
2129
std::cout << ") ";
2130
break;
2131
case OptimizationMode::defense:
2132
std::cout << "(" << score.draws * 100.0 << "% stall) ";
2133
break;
2134
default:
2135
break;
2136
}
2137
std::cout << score.points;
2138
unsigned min_score = min_possible_score[(size_t)optimization_mode];
2139
unsigned max_score = max_possible_score[(size_t)optimization_mode];
2140
if (optimization_mode == OptimizationMode::brawl)
2141
{
2142
auto win_points = score.wins ? ((score.points - min_score * (1.0 - score.wins)) / score.wins) : score.points;
2143
std::cout << " [" << win_points << " per win]";
2144
}
2145
else if (optimization_mode == OptimizationMode::brawl_defense)
2146
{
2147
auto opp_win_points = score.losses ? max_score - ((score.points - (max_score - min_score) * (1.0 - score.losses)) / score.losses) : score.points;
2148
std::cout << " [" << opp_win_points << " per opp win]";
2149
}
2150
else if (optimization_mode == OptimizationMode::war)
2151
{
2152
auto win_points = score.wins ? ((score.points - min_score * (1.0 - score.wins)) / score.wins) : score.points;
2153
std::cout << " [" << win_points << " per win]";
2154
}
2155
else if (optimization_mode == OptimizationMode::war_defense)
2156
{
2157
auto opp_win_points = score.losses ? max_score - ((score.points - (max_score - min_score) * (1.0 - score.losses)) / score.losses) : score.points;
2158
std::cout << " [" << opp_win_points << " per opp win]";
2159
}
2160
*/
2161

2162
    // print commander
2163
    std::cout << ": " << deck->commander->m_name;
1,296 ✔
2164

2165
    // print dominions
2166
    if (deck->alpha_dominion)
1,296 ✔
2167
    {
2168
        std::cout << ", " << deck->alpha_dominion->m_name;
1,228 ✔
2169
    }
2170

2171
    // print deck cards
2172
    if (deck->strategy == DeckStrategy::random || deck->strategy == DeckStrategy::flexible || deck->strategy == DeckStrategy::evaluate || deck->strategy == DeckStrategy::evaluate_twice)
1,296 ✔
2173
    {
2174
        std::sort(deck->cards.begin(), deck->cards.end(), [](const Card *a, const Card *b)
1,296 ✔
2175
                  { return a->m_id < b->m_id; });
23,931 ✔
2176
    }
2177
    std::cout << ", ";
1,296 ✔
2178
    if (print_locked)
1,296 ✔
2179
        print_cards_inline(deck->cards, std::cout, deck);
14 ✔
2180
    else
2181
        print_cards_inline(deck->cards, std::cout);
1,282 ✔
2182
}
1,296 ✔
2183
//------------------------------------------------------------------------------
2184
bool is_timeout_reached()
495 ✔
2185
{
2186
    if (__builtin_expect(maximum_time > 0, false))
495 ✔
2187
    {
2188
        if ((std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now() - start_time)).count() > maximum_time * 60 * 60)
×
2189
        {
2190
            std::cout << "Time expired! Current result:" << std::endl;
×
2191
            return true;
×
2192
        }
2193
    }
2194
    return false;
2195
}
2196
std::vector<std::vector<const Card *>> get_candidate_lists(Process &proc)
7 ✔
2197
{
2198
    std::vector<std::vector<const Card *>> ret_candidates;
7 ✔
2199
    std::vector<const Card *> commander_candidates;
7 ✔
2200
    std::vector<const Card *> alpha_dominion_candidates;
7 ✔
2201
    std::vector<const Card *> card_candidates;
7 ✔
2202

2203
    // resolve available to player cards
2204
    auto player_assaults_and_structures = proc.cards.player_commanders;
7 ✔
2205
    player_assaults_and_structures.insert(player_assaults_and_structures.end(), proc.cards.player_structures.begin(), proc.cards.player_structures.end());
7 ✔
2206
    player_assaults_and_structures.insert(player_assaults_and_structures.end(), proc.cards.player_assaults.begin(), proc.cards.player_assaults.end());
7 ✔
2207
    for (auto it = player_assaults_and_structures.begin(); it != player_assaults_and_structures.end(); ++it)
294,770 ✔
2208
    {
2209
        const Card *card = *it;
294,763 ✔
2210
        // skip illegal
2211
        if ((card->m_category != CardCategory::dominion_alpha) && (card->m_category != CardCategory::normal))
294,763 ✔
2212
        {
2213
            continue;
294,518 ✔
2214
        }
2215

2216
        // skip dominions when their climbing is disabled
2217
        if ((card->m_category == CardCategory::dominion_alpha) && (!use_owned_dominions))
294,763 ✔
2218
        {
2219
            continue;
×
2220
        }
2221

2222
        // try to skip a card unless it's allowed
2223
        if (!allowed_candidates.count(card->m_id))
294,763 ✔
2224
        {
2225
            // skip disallowed always
2226
            if (disallowed_candidates.count(card->m_id))
294,763 ✔
2227
            {
2228
                continue;
×
2229
            }
2230

2231
            // handle dominions
2232
            if (card->m_category == CardCategory::dominion_alpha)
294,763 ✔
2233
            {
2234
                // skip non-top-level dominions anyway
2235
                // (will check it later and downgrade if necessary according to amount of material (shards))
2236
                /*if (!card->is_top_level_card())
2237
                  { continue; }
2238

2239
                // skip basic dominions
2240
                if ((card->m_id == 50001) || (card->m_id == 50002))
2241
                { continue; }*/
2242
            }
2243

2244
            // handle normal cards
2245
            else
2246
            {
2247
                // skip non-top-level cards (adjust_deck() will try to downgrade them if necessary)
2248
                bool use_top_level = (card->m_type == CardType::commander) ? use_top_level_commander : use_top_level_card;
292,257 ✔
2249
                if (!card->is_top_level_card() and (fund || use_top_level || !owned_cards[card->m_id]))
292,257 ✔
2250
                {
2251
                    continue;
242,816 ✔
2252
                }
2253

2254
                // skip lowest fusion levels
2255
                unsigned use_fused_level = (card->m_type == CardType::commander) ? use_fused_commander_level : use_fused_card_level;
49,441 ✔
2256
                if (card->m_fusion_level < use_fused_level)
49,441 ✔
2257
                {
2258
                    continue;
×
2259
                }
2260
            }
2261
        }
2262

2263
        if (use_owned_cards && card->m_category == CardCategory::dominion_alpha && !owned_cards[card->m_id])
51,947 ✔
2264
        {
2265
            if (use_maxed_dominions && card->m_used_for_cards.size() == 0)
2,485 ✔
2266
            {
2267
            }
2268
            else
2269
            {
2270
                continue;
2,485 ✔
2271
            }
2272
        }
2273
        // skip unavailable cards anyway when ownedcards is used
2274
        if (use_owned_cards && !(card->m_category == CardCategory::dominion_alpha) && !is_owned_or_can_be_fused(card))
49,462 ✔
2275
        {
2276
            continue;
49,217 ✔
2277
        }
2278
        // mono
2279
        if (!factions.empty() && (std::find(factions.begin(), factions.end(), card->m_faction) == factions.end()) != invert_factions) // XOR
245 ✔
2280
        {
2281
            continue;
×
2282
        }
2283

2284
        // enqueue candidate according to category & type
2285
        if (card->m_type == CardType::commander)
245 ✔
2286
        {
2287
            commander_candidates.emplace_back(card);
63 ✔
2288
        }
2289
        else if (card->m_category == CardCategory::dominion_alpha)
182 ✔
2290
        {
2291
            alpha_dominion_candidates.emplace_back(card);
21 ✔
2292
        }
2293
        else if (card->m_category == CardCategory::normal)
161 ✔
2294
        {
2295
            bool contains{false};
161 ✔
2296
            if (!skills.empty())
161 ✔
2297
            {
2298
                for (Skill::Skill skill_id : skills)
×
2299
                {
2300
                    if (card->m_skill_value[skill_id])
×
2301
                    {
2302
                        contains = true;
2303
                        break;
2304
                    }
2305
                }
2306
                if (!contains != invert_skills)
×
2307
                    continue; // XOR
×
2308
            }
2309
            if (only_recent && !((it + (player_assaults_and_structures.size() * recent_percent / 100)) > player_assaults_and_structures.end()))
161 ✔
2310
                continue;                                                                                                                      // latest %
×
2311
            if (prefered_recent && it + (player_assaults_and_structures.size() * recent_percent) / 100 > player_assaults_and_structures.end()) // latest %
161 ✔
2312
            {
2313
                for (unsigned k = 0; k < prefered_factor; ++k)
×
2314
                    card_candidates.emplace_back(card);
×
2315
            }
2316
            for (Skill::Skill skill_id : prefered_skills)
161 ✔
2317
            {
2318
                if (card->m_skill_value[skill_id])
×
2319
                {
2320
                    for (unsigned k = 0; k < prefered_factor; ++k)
×
2321
                        card_candidates.emplace_back(card);
×
2322
                }
2323
            }
2324

2325
            card_candidates.emplace_back(card);
161 ✔
2326
        }
2327
    }
2328
    card_candidates.emplace_back(nullptr);
7 ✔
2329

2330
    ret_candidates.emplace_back(commander_candidates);
7 ✔
2331
    ret_candidates.emplace_back(alpha_dominion_candidates);
7 ✔
2332
    ret_candidates.emplace_back(card_candidates);
7 ✔
2333
    return ret_candidates;
7 ✔
2334
}
7 ✔
2335
//------------------------------------------------------------------------------
2336
enum Operation
2337
{
2338
    noop,
2339
    simulate,
2340
    climb,
2341
    climb_forts,
2342
    anneal,
2343
    genetic,
2344
    beam,
2345
    reorder,
2346
    debug,
2347
    debuguntil,
2348
};
2349
//------------------------------------------------------------------------------
2350
extern void (*skill_table[Skill::num_skills])(Field *, CardStatus *src_status, const SkillSpec &);
2351
void print_available_effects()
×
2352
{
2353
    std::cout << "Available effects besides activation skills:\n"
×
2354
                 "  Bloodlust X\n"
2355
                 "  Brigade\n"
2356
                 "  Counterflux\n"
2357
                 "  Divert\n"
2358
                 "  Enduring-Rage\n"
2359
                 "  Fortification\n"
2360
                 "  Heroism\n"
2361
                 "  Zealots-Preservation\n"
2362
                 "  Metamorphosis\n"
2363
                 "  Megamorphosis\n"
2364
                 "  Revenge X\n"
2365
                 "  Turning-Tides\n"
2366
                 "  Virulence\n"
2367
                 "  Halted-Orders\n"
2368
                 "  Devour X\n"
2369
                 "  Critical-Reach\n"
2370
                 "  Temporal-Backlash\n"
2371
                 "  Furiosity\n"
2372
                 "  Oath-Of-Loyalty\n"
2373
                 "  Blood-Vengeance\n"
2374
                 "  Cold-Sleep\n"
2375
                 "  Iron-Will\n"
2376
                 "  Unity\n"
2377
                 "  Devotion\n"
2378
                 "  Crackdown\n"
2379
                 "  SuperHeroism\n";
×
2380
}
×
2381
bool check_input_amount(int argc, const char **argv, int argIndex, int number)
402 ✔
2382
{
2383
    if (argc <= argIndex + number)
402 ✔
2384
    {
2385
        std::cerr << argv[argIndex] << " needs " << number << " paramters" << std::endl;
×
2386
        return true;
×
2387
    }
2388
    return false;
2389
}
2390
void input_error(std::string msg)
×
2391
{
2392
    std::cerr << msg << std::endl;
×
2393
    exit(EXIT_FAILURE);
×
2394
}
2395
void usage(int argc, const char **argv)
×
2396
{
2397
    std::cout << "Tyrant Unleashed Optimizer (TUO) " << TYRANT_OPTIMIZER_VERSION << "\n"
×
2398
                                                                                    "usage: "
2399
              << argv[0] << " Your_Deck Enemy_Deck [Flags] [Operations]\n"
2400
                            "\n"
2401
                            "Your_Deck:\n"
2402
                            "  the name/hash/cards of a custom deck.\n"
2403
                            "\n"
2404
                            "Enemy_Deck:\n"
2405
                            "  semicolon separated list of defense decks, syntax:\n"
2406
                            "  deck1[:factor1];deck2[:factor2];...\n"
2407
                            "  where deck is the name/hash/cards of a mission, raid, quest or custom deck, and factor is optional. The default factor is 1.\n"
2408
                            "  example: \'fear:0.2;slowroll:0.8\' means fear is the defense deck 20% of the time, while slowroll is the defense deck 80% of the time.\n"
2409
                            "\n"
2410
                            "Flags:\n"
2411
                            "  -e \"<effect>\": set the battleground effect; you may use -e multiple times.\n"
2412
                            "  -r: the attack deck is played in order instead of randomly (respects the 3 cards drawn limit).\n"
2413
                            "  -s: use surge (default is fight).\n"
2414
                            "  -t <num>: set the number of threads, default is 4.\n"
2415
                            "  win:     simulate/optimize for win rate. default for non-raids.\n"
2416
                            "  defense: simulate/optimize for win rate + stall rate. can be used for defending deck or win rate oriented raid simulations.\n"
2417
                            "  raid:    simulate/optimize for average raid damage (ARD). default for raids.\n"
2418
                            "Flags for climb:\n"
2419
                            "  -c: don't try to optimize the commander.\n"
2420
                            "  -L <min> <max>: restrict deck size between <min> and <max>.\n"
2421
                            "  -o: restrict to the owned cards listed in \"data/ownedcards.txt\".\n"
2422
                            "  -o=<filename>: restrict to the owned cards listed in <filename>.\n"
2423
                            "  fund <num>: invest <num> SP to upgrade cards.\n"
2424
                            "  target <num>: stop as soon as the score reaches <num>.\n"
2425
                            "\n"
2426
                            "Operations:\n"
2427
                            "  sim <num>: simulate <num> battles to evaluate a deck.\n"
2428
                            "  climb <num>: perform hill-climbing starting from the given attack deck, using up to <num> battles to evaluate a deck.\n"
2429
                            "  reorder <num>: optimize the order for given attack deck, using up to <num> battles to evaluate an order.\n"
2430
#ifndef NDEBUG
2431
                            "  debug: testing purpose only. very verbose output. only one battle.\n"
2432
                            "  debuguntil <min> <max>: testing purpose only. fight until the last fight results in range [<min>, <max>]. recommend to redirect std::coutput.\n"
×
2433
#endif
2434
        ;
2435
}
×
2436

2437
bool parse_bge(
63 ✔
2438
    std::string bge_name,
2439
    unsigned player,
2440
    const std::unordered_map<std::string, std::string> &bge_aliases,
2441
    std::array<signed short, PassiveBGE::num_passive_bges> &your_bg_effects,
2442
    std::array<signed short, PassiveBGE::num_passive_bges> &enemy_bg_effects,
2443
    std::vector<SkillSpec> &your_bg_skills,
2444
    std::vector<SkillSpec> &enemy_bg_skills,
2445
    std::unordered_set<std::string> used_bge_aliases)
2446
{
2447
    // skip empty
2448
    tuo::trim(bge_name);
63 ✔
2449
    if (bge_name.empty())
63 ✔
2450
    {
2451
        return true;
2452
    }
2453

2454
    // is effect combined?
2455
    if (bge_name.find_first_of(";|") != std::string::npos)
37 ✔
2456
    {
2457
        std::vector<std::string> bges;
×
2458
        boost::split(bges, bge_name, boost::is_any_of(";|"));
×
2459
        for (auto &&next_bge : bges)
×
2460
        {
2461
            if (!parse_bge(next_bge, player, bge_aliases, your_bg_effects, enemy_bg_effects, your_bg_skills, enemy_bg_skills, used_bge_aliases))
×
2462
            {
2463
                return false;
×
2464
            }
2465
        }
2466
        return true;
2467
    }
×
2468

2469
    // try to resolve bge name as alias
2470
    std::string simple_bge_name = simplify_name(bge_name);
37 ✔
2471
    const auto bge_alias_itr = bge_aliases.find(simple_bge_name);
37 ✔
2472
    if (bge_alias_itr != bge_aliases.end())
37 ✔
2473
    {
2474
        if (!used_bge_aliases.insert(simple_bge_name).second)
1 ✔
2475
        {
2476
            throw std::runtime_error("BGE alias: " + bge_name + ": Circular reference");
×
2477
        }
2478
        return parse_bge(bge_alias_itr->second, player, bge_aliases, your_bg_effects, enemy_bg_effects, your_bg_skills, enemy_bg_skills, used_bge_aliases);
3 ✔
2479
    }
2480

2481
    // parse as passive or skill based BGE
2482
    std::vector<std::string> tokens, skill_name_list;
36 ✔
2483
    boost::split(tokens, bge_name, boost::is_any_of(" "));
36 ✔
2484
    boost::split(skill_name_list, tokens[0], boost::is_any_of("+"));
36 ✔
2485
    try
36 ✔
2486
    {
2487
        for (auto &&skill_name : skill_name_list)
72 ✔
2488
        {
2489
            PassiveBGE::PassiveBGE passive_bge_id = passive_bge_name_to_id(skill_name);
36 ✔
2490
            Skill::Skill skill_id = skill_name_to_id(skill_name);
36 ✔
2491
            if (passive_bge_id != PassiveBGE::no_bge)
36 ✔
2492
            {
2493
                // map bge id to its value (if present otherwise zero)
2494
                signed short bge_value = (tokens.size() > 1) ? boost::lexical_cast<signed short>(tokens[1]) : 1;
35 ✔
2495
                if (!bge_value)
6 ✔
2496
                    throw std::runtime_error("BGE " + skill_name + ": zero value means no BGE");
×
2497
                if ((player == 0) or (player == 2))
35 ✔
2498
                    your_bg_effects[passive_bge_id] = bge_value;
35 ✔
2499
                if ((player == 1) or (player == 2))
35 ✔
2500
                    enemy_bg_effects[passive_bge_id] = bge_value;
35 ✔
2501
            }
2502
            else if (skill_table[skill_id] != nullptr)
1 ✔
2503
            {
2504
                unsigned skill_index = 1;
1 ✔
2505
                // activation BG skill
2506
                SkillSpec bg_skill{
1 ✔
2507
                    skill_id,
2508
                    0,
2509
                    allfactions,
2510
                    0,
2511
                    0,
2512
                    Skill::no_skill,
2513
                    Skill::no_skill,
2514
                    false,
2515
                    0,
2516
                };
1 ✔
2517

2518
                // skill [ ALL | N ] ...
2519
                if (skill_index < tokens.size() && boost::to_lower_copy(tokens[skill_index]) == "all")
2 ✔
2520
                {
2521
                    bg_skill.all = true;
1 ✔
2522
                    skill_index += 1;
1 ✔
2523
                }
2524
                else if (skill_index + 1 < tokens.size() && isdigit(*tokens[skill_index].c_str()))
×
2525
                {
2526
                    bg_skill.n = boost::lexical_cast<unsigned>(tokens[skill_index]);
×
2527
                    skill_index += 1;
×
2528
                }
2529

2530
                // skill n [ FACTION ] ...
2531
                if ((skill_index + 1) < tokens.size())
1 ✔
2532
                {
2533
                    for (auto f = allfactions + 1; f < num_factions; ++f)
7 ✔
2534
                    {
2535
                        if (boost::to_lower_copy(tokens[skill_index]) == faction_names[f])
6 ✔
2536
                        {
2537
                            bg_skill.y = static_cast<Faction>(f);
×
2538
                            skill_index += 1;
×
2539
                            break;
×
2540
                        }
2541
                    }
2542
                }
2543

2544
                if (skill_index < tokens.size())
1 ✔
2545
                {
2546
                    bg_skill.s = skill_name_to_id(tokens[skill_index]);
1 ✔
2547
                    if (bg_skill.s != Skill::no_skill)
1 ✔
2548
                    {
2549
                        skill_index += 1;
1 ✔
2550
                        if (skill_index < tokens.size() && (boost::to_lower_copy(tokens[skill_index]) == "to" || boost::to_lower_copy(tokens[skill_index]) == "into"))
3 ✔
2551
                        {
2552
                            skill_index += 1;
×
2553
                        }
2554
                        if (skill_index < tokens.size())
1 ✔
2555
                        {
2556
                            bg_skill.s2 = skill_name_to_id(tokens[skill_index]);
1 ✔
2557
                            if (bg_skill.s2 != Skill::no_skill)
1 ✔
2558
                            {
2559
                                skill_index += 1;
×
2560
                            }
2561
                        }
2562
                    }
2563
                }
2564
                if (skill_index < tokens.size())
1 ✔
2565
                {
2566
                    if (bg_skill.id == Skill::jam || bg_skill.id == Skill::overload)
1 ✔
2567
                    {
2568
                        bg_skill.n = boost::lexical_cast<unsigned>(tokens[skill_index]);
×
2569
                    }
2570
                    else
2571
                    {
2572
                        bg_skill.x = boost::lexical_cast<unsigned>(tokens[skill_index]);
1 ✔
2573
                    }
2574
                }
2575
                switch (player)
1 ✔
2576
                {
2577
                case 0:
×
2578
                    your_bg_skills.push_back(bg_skill);
×
2579
                    break;
2580
                case 1:
×
2581
                    enemy_bg_skills.push_back(bg_skill);
×
2582
                    break;
2583
                case 2:
1 ✔
2584
                    your_bg_skills.push_back(bg_skill);
1 ✔
2585
                    enemy_bg_skills.push_back(bg_skill);
1 ✔
2586
                    break;
2587
                default:
×
2588
                    throw std::runtime_error("Bad player number: " + boost::lexical_cast<std::string>(player));
×
2589
                }
2590
            }
2591
            else
2592
            {
2593
                std::cerr << "Error: unrecognized effect \"" << bge_name << "\".\n";
×
2594
                std::cout << "Unrecognized effect \"" << bge_name << "\".\n";
×
2595
                print_available_effects();
×
2596
                return false;
36 ✔
2597
            }
2598
        }
2599
    }
2600
    catch (const boost::bad_lexical_cast &e)
×
2601
    {
2602
        throw std::runtime_error("Expect a number in effect \"" + bge_name + "\"");
×
2603
    }
×
2604
    return true;
2605
}
73 ✔
2606

2607
DeckResults run(int argc, const char **argv)
85 ✔
2608
{
2609
    start_time = std::chrono::system_clock::now();
85 ✔
2610
    DeckResults fr;
85 ✔
2611
    opt_num_threads = 4;
85 ✔
2612
    DeckStrategy::DeckStrategy opt_your_strategy(DeckStrategy::random);
85 ✔
2613
    DeckStrategy::DeckStrategy opt_enemy_strategy(DeckStrategy::random);
85 ✔
2614
    std::string opt_forts, opt_enemy_forts;
85 ✔
2615
    std::string opt_doms, opt_enemy_doms;
85 ✔
2616
    std::string opt_hand, opt_enemy_hand;
85 ✔
2617
    std::string opt_vip;
85 ✔
2618
    std::string opt_allow_candidates;
85 ✔
2619
    std::string opt_disallow_candidates;
85 ✔
2620
    std::string opt_disallow_recipes;
85 ✔
2621
#ifndef NQUEST
2622
    std::string opt_quest;
2623
#endif
2624
    std::string opt_target_score;
85 ✔
2625
    std::vector<std::string> fn_suffix_list{
85 ✔
2626
        "",
2627
    };
170 ✔
2628
    std::string prefix = "";
170 ✔
2629
    std::vector<std::string> opt_owned_cards_str_list;
85 ✔
2630
    bool opt_do_optimization(false);
85 ✔
2631
    bool opt_multi_optimization(false);
85 ✔
2632
    bool opt_do_reorder(false);
85 ✔
2633
    bool opt_keep_commander{false};
85 ✔
2634
    std::vector<std::tuple<unsigned, unsigned, Operation>> opt_todo;
85 ✔
2635
    std::vector<std::string> opt_effects[3]; // 0-you; 1-enemy; 2-global
595 ✔
2636
    std::array<signed short, PassiveBGE::num_passive_bges> opt_bg_effects[2];
2637
    std::vector<SkillSpec> opt_bg_skills[2];
425 ✔
2638

2639
    std::string your_deck_list{argv[1]};
85 ✔
2640
    std::string enemy_deck_list{argv[2]};
85 ✔
2641

2642
    for (int argIndex = 3; argIndex < argc; ++argIndex)
513 ✔
2643
    {
2644
        //bypass MSVS issue: Nesting of code blocks exceeds the limit of 128 nesting levels
2645
        bool tokenParsed = true;
428 ✔
2646
        if (strcmp(argv[argIndex], "deck") == 0)
428 ✔
2647
        {
2648
            your_deck_list = std::string(argv[argIndex + 1]);
×
2649
            argIndex += 1;
×
2650
        }
2651
        else if (strcmp(argv[argIndex], "enemy:deck") == 0)
428 ✔
2652
        {
2653
            enemy_deck_list = std::string(argv[argIndex + 1]);
×
2654
            argIndex += 1;
×
2655
        }
2656
        // Codec
2657
        else if (strcmp(argv[argIndex], "ext_b64") == 0)
428 ✔
2658
        {
2659
            hash_to_ids = hash_to_ids_ext_b64;
×
2660
            encode_deck = encode_deck_ext_b64;
×
2661
        }
2662
        else if (strcmp(argv[argIndex], "wmt_b64") == 0)
428 ✔
2663
        {
2664
            hash_to_ids = hash_to_ids_wmt_b64;
×
2665
            encode_deck = encode_deck_wmt_b64;
×
2666
        }
2667
        else if (strcmp(argv[argIndex], "ddd_b64") == 0)
428 ✔
2668
        {
2669
            hash_to_ids = hash_to_ids_ddd_b64;
×
2670
            encode_deck = encode_deck_ddd_b64;
×
2671
        }
2672
        else if (strcmp(argv[argIndex], "ml") == 0)
428 ✔
2673
        {
2674
            use_ml = true;
1 ✔
2675
            use_db_write = false;
1 ✔
2676
        }
2677
        else if (strcmp(argv[argIndex], "noop") == 0)
427 ✔
2678
        {
2679
        }
2680
        else if (strcmp(argv[argIndex], "no-ml") == 0)
427 ✔
2681
        {
2682
            use_ml = false;
×
2683
        }
2684
        else if (strcmp(argv[argIndex], "only-ml") == 0)
427 ✔
2685
        {
2686
            use_ml = true;
×
2687
            use_only_ml = true;
×
2688
            use_db_write = false;
×
2689
        }
2690
        else if (strcmp(argv[argIndex], "ml-precision") == 0)
427 ✔
2691
        {
2692
            if (check_input_amount(argc, argv, argIndex, 1))
×
2693
                exit(1);
×
2694
            ml_precision = std::stof(argv[argIndex + 1]);
×
2695
            argIndex += 1;
×
2696
        }
2697
        else if (strcmp(argv[argIndex], "no-db-write") == 0)
427 ✔
2698
        {
2699
            use_db_write = false;
×
2700
        }
2701
        else if (strcmp(argv[argIndex], "no-db-load") == 0)
427 ✔
2702
        {
2703
            use_db_load = false;
3 ✔
2704
        }
2705
        else if (strcmp(argv[argIndex], "no-db") == 0)
424 ✔
2706
        {
2707
            use_db_load = false;
16 ✔
2708
            use_db_write = false;
16 ✔
2709
        }
2710
        else if (strcmp(argv[argIndex], "db") == 0)
408 ✔
2711
        {
2712
            use_db_load = true;
4 ✔
2713
            use_db_write = true;
4 ✔
2714
        }
2715
        else if (strcmp(argv[argIndex], "strict-db") == 0)
404 ✔
2716
        {
2717
            use_strict_db = true;
×
2718
            use_db_load = true;
×
2719
            use_db_write = true;
×
2720
        }
2721
        else if (strcmp(argv[argIndex], "no-strict-db") == 0)
404 ✔
2722
        {
2723
            use_strict_db = false;
×
2724
        }
2725
        else if (strcmp(argv[argIndex], "db-limit") == 0)
404 ✔
2726
        {
2727
            if (check_input_amount(argc, argv, argIndex, 1))
×
2728
                exit(1);
×
2729
            db_limit = std::stoi(argv[argIndex + 1]);
×
2730
            argIndex += 1;
×
2731
        }
2732

2733
        // Base Game Mode
2734
        else if (strcmp(argv[argIndex], "fight") == 0)
404 ✔
2735
        {
2736
            gamemode = fight;
×
2737
        }
2738
        else if (strcmp(argv[argIndex], "-s") == 0 || strcmp(argv[argIndex], "surge") == 0)
404 ✔
2739
        {
2740
            gamemode = surge;
×
2741
        }
2742
        // Base Scoring Mode
2743
        else if (strcmp(argv[argIndex], "win") == 0)
404 ✔
2744
        {
2745
            optimization_mode = OptimizationMode::winrate;
×
2746
        }
2747
        else if (strcmp(argv[argIndex], "defense") == 0)
404 ✔
2748
        {
2749
            optimization_mode = OptimizationMode::defense;
×
2750
        }
2751
        else if (strcmp(argv[argIndex], "raid") == 0)
404 ✔
2752
        {
2753
            optimization_mode = OptimizationMode::raid;
×
2754
        }
2755
        // Mode Package
2756
        else if (strcmp(argv[argIndex], "campaign") == 0)
404 ✔
2757
        {
2758
            gamemode = surge;
×
2759
            optimization_mode = OptimizationMode::campaign;
×
2760
        }
2761
        else if (strcmp(argv[argIndex], "pvp") == 0)
404 ✔
2762
        {
2763
            gamemode = fight;
×
2764
            optimization_mode = OptimizationMode::winrate;
×
2765
        }
2766
        else if (strcmp(argv[argIndex], "pvp-defense") == 0)
404 ✔
2767
        {
2768
            gamemode = surge;
×
2769
            optimization_mode = OptimizationMode::defense;
×
2770
        }
2771
        else if (strcmp(argv[argIndex], "brawl") == 0)
404 ✔
2772
        {
2773
            gamemode = surge;
×
2774
            optimization_mode = OptimizationMode::brawl;
×
2775
        }
2776
        else if (strcmp(argv[argIndex], "brawl-defense") == 0)
404 ✔
2777
        {
2778
            gamemode = fight;
×
2779
            optimization_mode = OptimizationMode::brawl_defense;
×
2780
        }
2781
        else if (strcmp(argv[argIndex], "gw") == 0)
404 ✔
2782
        {
2783
            gamemode = surge;
×
2784
            optimization_mode = OptimizationMode::war;
×
2785
        }
2786
        else if (strcmp(argv[argIndex], "gw-defense") == 0)
404 ✔
2787
        {
2788
            gamemode = fight;
×
2789
            optimization_mode = OptimizationMode::war_defense;
×
2790
        }
2791
        // Others
2792
        else if (strcmp(argv[argIndex], "keep-commander") == 0 || strcmp(argv[argIndex], "-c") == 0)
404 ✔
2793
        {
2794
            opt_keep_commander = true;
2795
        }
2796
        else if (strcmp(argv[argIndex], "mono") == 0 || strcmp(argv[argIndex], "-m") == 0 || strcmp(argv[argIndex], "factions") == 0 || strcmp(argv[argIndex], "-f") == 0)
404 ✔
2797
        {
2798
            if (check_input_amount(argc, argv, argIndex, 1))
×
2799
                exit(1);
×
2800
            if (strcmp(argv[argIndex + 1], "") != 0)
×
2801
            {
2802
                factions.push_back(faction_name_to_id(argv[argIndex + 1]));
×
2803
            }
2804
            argIndex += 1;
×
2805
        }
2806
        else if (strcmp(argv[argIndex], "no-mono") == 0 || strcmp(argv[argIndex], "no-factions") == 0)
404 ✔
2807
        {
2808
            if (check_input_amount(argc, argv, argIndex, 1))
×
2809
                exit(1);
×
2810
            factions.push_back(faction_name_to_id(argv[argIndex + 1]));
×
2811
            invert_factions = true;
×
2812
            argIndex += 1;
×
2813
        }
2814
        else if (strcmp(argv[argIndex], "strategy") == 0 || strcmp(argv[argIndex], "skill") == 0)
404 ✔
2815
        {
2816
            if (check_input_amount(argc, argv, argIndex, 1))
×
2817
                exit(1);
×
2818
            if (strcmp(argv[argIndex + 1], "") != 0)
×
2819
            {
2820
                if (strcmp(argv[argIndex + 1], "recent") == 0)
×
2821
                {
2822
                    only_recent = true;
×
2823
                }
2824
                else
2825
                {
2826
                    skills.push_back(skill_name_to_id(argv[argIndex + 1]));
×
2827
                }
2828
            }
2829
            argIndex += 1;
×
2830
        }
2831
        else if (strcmp(argv[argIndex], "no-strategy") == 0 || strcmp(argv[argIndex], "no-skill") == 0)
404 ✔
2832
        {
2833
            if (check_input_amount(argc, argv, argIndex, 1))
×
2834
                exit(1);
×
2835
            if (strcmp(argv[argIndex + 1], "") != 0)
×
2836
            {
2837
                skills.push_back(skill_name_to_id(argv[argIndex + 1]));
×
2838
                invert_skills = true;
×
2839
            }
2840
            argIndex += 1;
×
2841
        }
2842
        else if (strcmp(argv[argIndex], "prefered-strategy") == 0 || strcmp(argv[argIndex], "prefered-skill") == 0)
404 ✔
2843
        {
2844
            if (check_input_amount(argc, argv, argIndex, 1))
×
2845
                exit(1);
×
2846
            if (strcmp(argv[argIndex + 1], "") != 0)
×
2847
            {
2848
                if (strcmp(argv[argIndex + 1], "recent") == 0)
×
2849
                {
2850
                    prefered_recent = true;
×
2851
                }
2852
                else
2853
                {
2854
                    prefered_skills.push_back(skill_name_to_id(argv[argIndex + 1]));
×
2855
                }
2856
            }
2857
            argIndex += 1;
×
2858
        }
2859
        else if (strcmp(argv[argIndex], "prefered-factor") == 0)
404 ✔
2860
        {
2861
            if (check_input_amount(argc, argv, argIndex, 1))
×
2862
                exit(1);
×
2863
            prefered_factor = std::stoi(argv[argIndex + 1]);
×
2864
            argIndex += 1;
×
2865
        }
2866
        else if (strcmp(argv[argIndex], "recent-percent") == 0)
404 ✔
2867
        {
2868
            if (check_input_amount(argc, argv, argIndex, 1))
×
2869
                exit(1);
×
2870
            recent_percent = std::stoi(argv[argIndex + 1]);
×
2871
            argIndex += 1;
×
2872
        }
2873
        else if (strcmp(argv[argIndex], "effect") == 0 || strcmp(argv[argIndex], "-e") == 0)
404 ✔
2874
        {
2875
            if (check_input_amount(argc, argv, argIndex, 1))
62 ✔
2876
                exit(1);
×
2877
            opt_effects[2].push_back(argv[argIndex + 1]);
124 ✔
2878
            argIndex += 1;
62 ✔
2879
        }
2880
        else if (strcmp(argv[argIndex], "ye") == 0 || strcmp(argv[argIndex], "yeffect") == 0)
342 ✔
2881
        {
2882
            if (check_input_amount(argc, argv, argIndex, 1))
×
2883
                exit(1);
×
2884
            opt_effects[0].push_back(argv[argIndex + 1]);
×
2885
            argIndex += 1;
×
2886
        }
2887
        else if (strcmp(argv[argIndex], "ee") == 0 || strcmp(argv[argIndex], "eeffect") == 0)
342 ✔
2888
        {
2889
            if (check_input_amount(argc, argv, argIndex, 1))
×
2890
                exit(1);
×
2891
            opt_effects[1].push_back(argv[argIndex + 1]);
×
2892
            argIndex += 1;
×
2893
        }
2894
        else if (strcmp(argv[argIndex], "freeze") == 0 || strcmp(argv[argIndex], "-F") == 0)
342 ✔
2895
        {
2896
            if (check_input_amount(argc, argv, argIndex, 1))
×
2897
                exit(1);
×
2898
            opt_freezed_cards = atoi(argv[argIndex + 1]);
×
2899
            argIndex += 1;
×
2900
        }
2901
        else if (strcmp(argv[argIndex], "-L") == 0)
342 ✔
2902
        {
2903
            if (check_input_amount(argc, argv, argIndex, 2))
×
2904
                exit(1);
×
2905
            min_deck_len = atoi(argv[argIndex + 1]);
×
2906
            max_deck_len = atoi(argv[argIndex + 2]);
×
2907
            argIndex += 2;
×
2908
        }
2909
        else if (strcmp(argv[argIndex], "-o-") == 0)
342 ✔
2910
        {
2911
            use_owned_cards = false;
×
2912
        }
2913
        else if (strcmp(argv[argIndex], "-o") == 0)
342 ✔
2914
        {
2915
            opt_owned_cards_str_list.push_back(prefix + "data/ownedcards.txt");
×
2916
            use_owned_cards = true;
×
2917
        }
2918
        else if (strncmp(argv[argIndex], "-o=", 3) == 0)
342 ✔
2919
        {
2920
            std::string fname{prefix};
×
2921
            fname += (argv[argIndex] + 3);
×
2922
            opt_owned_cards_str_list.push_back(fname);
×
2923
            use_owned_cards = true;
×
2924
        }
×
2925
        else if (strncmp(argv[argIndex], "_", 1) == 0)
342 ✔
2926
        {
2927
            fn_suffix_list.push_back(argv[argIndex]);
×
2928
        }
2929
        else if (strcmp(argv[argIndex], "prefix") == 0)
342 ✔
2930
        {
2931
            if (check_input_amount(argc, argv, argIndex, 1))
85 ✔
2932
                exit(1);
×
2933
            prefix = argv[argIndex + 1];
85 ✔
2934
            argIndex += 1;
85 ✔
2935
        }
2936
        else if (strcmp(argv[argIndex], "fund") == 0)
257 ✔
2937
        {
2938
            if (check_input_amount(argc, argv, argIndex, 1))
×
2939
                exit(1);
×
2940
            fund = atoi(argv[argIndex + 1]);
×
2941
            argIndex += 1;
×
2942
        }
2943
        else if (strcmp(argv[argIndex], "dom-none") == 0)
257 ✔
2944
        {
2945
            use_owned_dominions = false;
×
2946
            use_maxed_dominions = false;
×
2947
        }
2948
        else if (strcmp(argv[argIndex], "dom+") == 0 || strcmp(argv[argIndex], "dominion+") == 0 || strcmp(argv[argIndex], "dom-owned") == 0)
257 ✔
2949
        {
2950
            use_owned_dominions = true;
×
2951
            use_maxed_dominions = false;
×
2952
        }
2953
        else if (strcmp(argv[argIndex], "dom-") == 0 || strcmp(argv[argIndex], "dominion-") == 0 || strcmp(argv[argIndex], "dom-maxed") == 0)
257 ✔
2954
        {
2955
            use_owned_dominions = true;
×
2956
            use_maxed_dominions = true;
×
2957
        }
2958
        else if (strcmp(argv[argIndex], "random") == 0)
257 ✔
2959
        {
2960
            opt_your_strategy = DeckStrategy::random;
2961
        }
2962
        else if (strcmp(argv[argIndex], "-r") == 0 || strcmp(argv[argIndex], "ordered") == 0)
257 ✔
2963
        {
2964
            opt_your_strategy = DeckStrategy::ordered;
2965
        }
2966
        else if (strcmp(argv[argIndex], "flexible") == 0 || strcmp(argv[argIndex], "flex") == 0)
257 ✔
2967
        {
2968
            opt_your_strategy = DeckStrategy::flexible;
2969
        }
2970
        else if (strcmp(argv[argIndex], "flexible-iter") == 0)
257 ✔
2971
        {
2972
            if (check_input_amount(argc, argv, argIndex, 1))
×
2973
                exit(1);
×
2974
            flexible_iter = atoi(argv[argIndex + 1]);
×
2975
            argIndex += 1;
×
2976
        }
2977
        else if (strcmp(argv[argIndex], "flexible-turn") == 0)
257 ✔
2978
        {
2979
            if (check_input_amount(argc, argv, argIndex, 1))
×
2980
                exit(1);
×
2981
            flexible_turn = atoi(argv[argIndex + 1]);
×
2982
            argIndex += 1;
×
2983
        }
2984
        else if (strcmp(argv[argIndex], "evaluate") == 0 || strcmp(argv[argIndex], "eval") == 0)
257 ✔
2985
        {
2986
            opt_your_strategy = DeckStrategy::evaluate;
2987
        }
2988
        else if (strcmp(argv[argIndex], "evaluate2") == 0 || strcmp(argv[argIndex], "eval2") == 0)
257 ✔
2989
        {
2990
            opt_your_strategy = DeckStrategy::evaluate_twice;
2991
        }
2992
        else if (strcmp(argv[argIndex], "eval-iter") == 0)
257 ✔
2993
        {
2994
            if (check_input_amount(argc, argv, argIndex, 1))
×
2995
                exit(1);
×
2996
            eval_iter = atoi(argv[argIndex + 1]);
×
2997
            argIndex += 1;
×
2998
        }
2999
        else if (strcmp(argv[argIndex], "eval-turn") == 0)
257 ✔
3000
        {
3001
            if (check_input_amount(argc, argv, argIndex, 1))
×
3002
                exit(1);
×
3003
            eval_turn = atoi(argv[argIndex + 1]);
×
3004
            argIndex += 1;
×
3005
        }
3006
        else if (strcmp(argv[argIndex], "exact-ordered") == 0)
257 ✔
3007
        {
3008
            opt_your_strategy = DeckStrategy::exact_ordered;
3009
        }
3010
        else if (strcmp(argv[argIndex], "enemy:evaluate") == 0)
257 ✔
3011
        {
3012
            opt_enemy_strategy = DeckStrategy::evaluate;
3013
        }
3014
        else if (strcmp(argv[argIndex], "enemy:evaluate2") == 0)
257 ✔
3015
        {
3016
            opt_enemy_strategy = DeckStrategy::evaluate_twice;
3017
        }
3018
        else if (strcmp(argv[argIndex], "enemy:flexible") == 0)
257 ✔
3019
        {
3020
            opt_enemy_strategy = DeckStrategy::flexible;
3021
        }
3022
        else if (strcmp(argv[argIndex], "enemy:ordered") == 0)
257 ✔
3023
        {
3024
            opt_enemy_strategy = DeckStrategy::ordered;
3025
        }
3026
        else if (strcmp(argv[argIndex], "enemy:flexible") == 0)
257 ✔
3027
        {
3028
            opt_enemy_strategy = DeckStrategy::flexible;
3029
        }
3030
        else if (strcmp(argv[argIndex], "enemy:exact-ordered") == 0)
257 ✔
3031
        {
3032
            opt_enemy_strategy = DeckStrategy::exact_ordered;
3033
        }
3034
        else if (strcmp(argv[argIndex], "endgame") == 0)
257 ✔
3035
        {
3036
            if (check_input_amount(argc, argv, argIndex, 1))
×
3037
                exit(1);
×
3038
            use_fused_card_level = atoi(argv[argIndex + 1]);
×
3039
            argIndex += 1;
×
3040
        }
3041
#ifndef NQUEST
3042
        else if (strcmp(argv[argIndex], "quest") == 0)
3043
        {
3044
            if (check_input_amount(argc, argv, argIndex, 1))
3045
                exit(1);
3046
            opt_quest = argv[argIndex + 1];
3047
            argIndex += 1;
3048
        }
3049
#endif
3050
        else if (strcmp(argv[argIndex], "threads") == 0 || strcmp(argv[argIndex], "-t") == 0)
257 ✔
3051
        {
3052
            if (check_input_amount(argc, argv, argIndex, 1))
85 ✔
3053
                exit(1);
×
3054
            opt_num_threads = atoi(argv[argIndex + 1]);
85 ✔
3055
#ifdef _OPENMP
3056
            omp_set_num_threads(opt_num_threads);
3057
#endif
3058
            argIndex += 1;
85 ✔
3059
        }
3060
        else if (strcmp(argv[argIndex], "target") == 0)
172 ✔
3061
        {
3062
            if (check_input_amount(argc, argv, argIndex, 1))
×
3063
                exit(1);
×
3064
            opt_target_score = argv[argIndex + 1];
×
3065
            argIndex += 1;
×
3066
        }
3067
        else if (strcmp(argv[argIndex], "turnlimit") == 0)
172 ✔
3068
        {
3069
            if (check_input_amount(argc, argv, argIndex, 1))
×
3070
                exit(1);
×
3071
            turn_limit = atoi(argv[argIndex + 1]);
×
3072
            argIndex += 1;
×
3073
        }
3074
        else if (strcmp(argv[argIndex], "mis") == 0)
172 ✔
3075
        {
3076
            if (check_input_amount(argc, argv, argIndex, 1))
×
3077
                exit(1);
×
3078
            min_increment_of_score = atof(argv[argIndex + 1]);
×
3079
            argIndex += 1;
×
3080
        }
3081
        else if (strcmp(argv[argIndex], "timeout") == 0) // set timeout in hours. tuo will stop approx. at the given time.
172 ✔
3082
        {
3083
            if (check_input_amount(argc, argv, argIndex, 1))
×
3084
                exit(1);
×
3085
            maximum_time = atof(argv[argIndex + 1]);
×
3086
            argIndex += 1;
×
3087
        }
3088
        else if (strcmp(argv[argIndex], "strict-ownedcards") == 0) // won't add missing cards, instead skips faulty decks
172 ✔
3089
        {
3090
            opt_skip_unclaimed_decks = true;
×
3091
        }
3092
        /*else if (strcmp(argv[argIndex], "trim-ownedcards") == 0) //won't add missing cards, instead removes missing cards from decks
3093
          {
3094
          opt_trim_unclaimed_decks = true;
3095
          }*/
3096
        else if (strcmp(argv[argIndex], "cl") == 0)
172 ✔
3097
        {
3098
            if (check_input_amount(argc, argv, argIndex, 1))
×
3099
                exit(1);
×
3100
            confidence_level = atof(argv[argIndex + 1]);
×
3101
            argIndex += 1;
×
3102
        }
3103
        else if (strcmp(argv[argIndex], "+so") == 0)
172 ✔
3104
        {
3105
            simplify_output = true;
×
3106
        }
3107
        else if (strcmp(argv[argIndex], "+uc") == 0)
172 ✔
3108
        {
3109
            print_upgraded = true;
×
3110
        }
3111
        else if (strcmp(argv[argIndex], "+vc") == 0)
172 ✔
3112
        {
3113
            print_values = true;
×
3114
        }
3115
        else if (strcmp(argv[argIndex], "+vc-x") == 0)
172 ✔
3116
        {
3117
            if (check_input_amount(argc, argv, argIndex, 1))
×
3118
                exit(1);
×
3119
            vc_x = atoi(argv[argIndex + 1]);
×
3120
            // print_values = true;
3121
            argIndex += 1;
×
3122
        }
3123
        else if (strcmp(argv[argIndex], "+ci") == 0)
172 ✔
3124
        {
3125
            show_ci = true;
×
3126
        }
3127
        else if (strcmp(argv[argIndex], "+hm") == 0)
172 ✔
3128
        {
3129
            use_harmonic_mean = true;
×
3130
        }
3131
        else if (strcmp(argv[argIndex], "no-fix") == 0)
172 ✔
3132
        {
3133
            for (int i = 0; i < Fix::num_fixes; ++i)
×
3134
                fixes[i] = false;
×
3135
        }
3136
        else if (strcmp(argv[argIndex], "fix-enhance-early") == 0)
172 ✔
3137
        {
3138
            fixes[Fix::enhance_early] = true;
×
3139
        }
3140
        else if (strcmp(argv[argIndex], "no-fix-enhance-early") == 0)
172 ✔
3141
        {
3142
            fixes[Fix::enhance_early] = false;
×
3143
        }
3144
        else if (strcmp(argv[argIndex], "fix-revenge-on-death") == 0)
172 ✔
3145
        {
3146
            fixes[Fix::revenge_on_death] = true;
×
3147
        }
3148
        else if (strcmp(argv[argIndex], "no-fix-revenge-on-death") == 0)
172 ✔
3149
        {
3150
            fixes[Fix::revenge_on_death] = false;
×
3151
        }
3152
        else if (strcmp(argv[argIndex], "fix-death-from-bge") == 0)
172 ✔
3153
        {
3154
            fixes[Fix::death_from_bge] = true;
×
3155
        }
3156
        else if (strcmp(argv[argIndex], "no-fix-death-from-bge") == 0)
172 ✔
3157
        {
3158
            fixes[Fix::death_from_bge] = false;
×
3159
        }
3160
        else if (strcmp(argv[argIndex], "fix-legion-under-megamorphosis") == 0)
172 ✔
3161
        {
3162
            fixes[Fix::legion_under_mega] = true;
×
3163
        }
3164
        else if (strcmp(argv[argIndex], "no-fix-legion-under-megamorphosis") == 0)
172 ✔
3165
        {
3166
            fixes[Fix::legion_under_mega] = false;
×
3167
        }
3168
        else if (strcmp(argv[argIndex], "update-barrier-each-turn") == 0)
172 ✔
3169
                {
3170
                        fixes[Fix::barrier_each_turn] = true;
×
3171
                }
3172
        else if (strcmp(argv[argIndex], "no-update-barrier-each-turn") == 0)
172 ✔
3173
                {
3174
                        fixes[Fix::barrier_each_turn] = false;
×
3175
                }
3176
        else if (strcmp(argv[argIndex], "update-dont-evade-mimic-selection") == 0)
172 ✔
3177
                {
3178
                        fixes[Fix::dont_evade_mimic_selection] = true;
×
3179
                }
3180
        else if (strcmp(argv[argIndex], "no-update-dont-evade-mimic-selection") == 0)
172 ✔
3181
                {
3182
                        fixes[Fix::dont_evade_mimic_selection] = false;
×
3183
                }
3184
        else if (strcmp(argv[argIndex], "update-leech-increase-max-hp") == 0)
172 ✔
3185
                {
3186
                        fixes[Fix::leech_increase_max_hp] = true;
×
3187
                }
3188
        else if (strcmp(argv[argIndex], "no-update-leech-increase-max-hp") == 0)
172 ✔
3189
                {
3190
                        fixes[Fix::leech_increase_max_hp] = false;
×
3191
                }
3192
        else if (strcmp(argv[argIndex], "update-counter-without-damage") == 0)
172 ✔
3193
                {
3194
                        fixes[Fix::counter_without_damage] = true;
×
3195
                }
3196
        else if (strcmp(argv[argIndex], "no-update-counter-without-damage") == 0)
172 ✔
3197
                {
3198
                        fixes[Fix::counter_without_damage] = false;
×
3199
                }
3200
        else if (strcmp(argv[argIndex], "update-corrosive-protect-armor") == 0)
172 ✔
3201
                {
3202
                        fixes[Fix::corrosive_protect_armor] = true;
×
3203
                }
3204
        else if (strcmp(argv[argIndex], "no-update-corrosive-protect-armor") == 0)
172 ✔
3205
                {
3206
                        fixes[Fix::corrosive_protect_armor] = false;
×
3207
                }
3208
        else if (strcmp(argv[argIndex], "update-poison-after-attacked") == 0)
172 ✔
3209
                {
3210
                        fixes[Fix::poison_after_attacked] = true;
×
3211
                }
3212
        else if (strcmp(argv[argIndex], "no-update-poison-after-attacked") == 0)
172 ✔
3213
                {
3214
                        fixes[Fix::poison_after_attacked] = false;
×
3215
                }
3216
        else if (strcmp(argv[argIndex], "update-subdue-before-attack") == 0)
172 ✔
3217
                {
3218
                        fixes[Fix::subdue_before_attack] = true;
×
3219
                }
3220
        else if (strcmp(argv[argIndex], "no-update-subdue-before-attack") == 0)
172 ✔
3221
                {
3222
                        fixes[Fix::subdue_before_attack] = false;
×
3223
                }
3224
        else if (strcmp(argv[argIndex], "update-reduce-delay-summoned-by-tower") == 0)
172 ✔
3225
        {
3226
            fixes[Fix::reduce_delay_summoned_by_tower] = true;
1 ✔
3227
        }
3228
        else if (strcmp(argv[argIndex], "no-update-reduce-delay-summoned-by-tower") == 0)
171 ✔
3229
        {
3230
            fixes[Fix::reduce_delay_summoned_by_tower] = false;
1 ✔
3231
        }
3232
        else if (strcmp(argv[argIndex], "seed") == 0)
170 ✔
3233
        {
3234
            if (check_input_amount(argc, argv, argIndex, 1))
85 ✔
3235
                exit(1);
×
3236
            sim_seed = atoi(argv[argIndex + 1]);
85 ✔
3237
            argIndex += 1;
85 ✔
3238
        }
3239
        else if (strcmp(argv[argIndex], "-v") == 0)
85 ✔
3240
        {
3241
            --debug_print;
×
3242
        }
3243
        else if (strcmp(argv[argIndex], "+v") == 0)
85 ✔
3244
        {
3245
            ++debug_print;
×
3246
        }
3247
        else if (strcmp(argv[argIndex], "vip") == 0)
85 ✔
3248
        {
3249
            if (check_input_amount(argc, argv, argIndex, 1))
×
3250
                exit(1);
×
3251
            opt_vip = argv[argIndex + 1];
×
3252
            argIndex += 1;
×
3253
        }
3254
        else if (strcmp(argv[argIndex], "allow-candidates") == 0)
85 ✔
3255
        {
3256
            if (check_input_amount(argc, argv, argIndex, 1))
×
3257
                exit(1);
×
3258
            opt_allow_candidates = argv[argIndex + 1];
×
3259
            argIndex += 1;
×
3260
        }
3261
        else if (strcmp(argv[argIndex], "disallow-candidates") == 0)
85 ✔
3262
        {
3263
            if (check_input_amount(argc, argv, argIndex, 1))
×
3264
                exit(1);
×
3265
            opt_disallow_candidates = argv[argIndex + 1];
×
3266
            argIndex += 1;
×
3267
        }
3268
        else if (strcmp(argv[argIndex], "disallow-recipes") == 0)
85 ✔
3269
        {
3270
            if (check_input_amount(argc, argv, argIndex, 1))
×
3271
                exit(1);
×
3272
            opt_disallow_recipes = argv[argIndex + 1];
×
3273
            argIndex += 1;
×
3274
        }
3275
        else if (strcmp(argv[argIndex], "hand") == 0) // set initial hand for test
85 ✔
3276
        {
3277
            if (check_input_amount(argc, argv, argIndex, 1))
×
3278
                exit(1);
×
3279
            opt_hand = argv[argIndex + 1];
×
3280
            argIndex += 1;
×
3281
        }
3282
        else if (strcmp(argv[argIndex], "enemy:hand") == 0) // set enemies' initial hand for test
85 ✔
3283
        {
3284
            if (check_input_amount(argc, argv, argIndex, 1))
×
3285
                exit(1);
×
3286
            opt_enemy_hand = argv[argIndex + 1];
×
3287
            argIndex += 1;
×
3288
        }
3289
        else if (strcmp(argv[argIndex], "yf") == 0 || strcmp(argv[argIndex], "yfort") == 0) // set forts
85 ✔
3290
        {
3291
            if (check_input_amount(argc, argv, argIndex, 1))
×
3292
                exit(1);
×
3293
            opt_forts = std::string(argv[argIndex + 1]);
×
3294
            argIndex += 1;
×
3295
        }
3296
        else if (strcmp(argv[argIndex], "yfpool") == 0 || strcmp(argv[argIndex], "yfortpool") == 0) // set forts
85 ✔
3297
        {
3298
            if (check_input_amount(argc, argv, argIndex, 1))
×
3299
                exit(1);
×
3300
            yfpool = std::stoi(argv[argIndex + 1]);
×
3301
            argIndex += 1;
×
3302
        }
3303
        else if (strcmp(argv[argIndex], "ef") == 0 || strcmp(argv[argIndex], "efort") == 0) // set enemies' forts
85 ✔
3304
        {
3305
            if (check_input_amount(argc, argv, argIndex, 1))
×
3306
                exit(1);
×
3307
            opt_enemy_forts = std::string(argv[argIndex + 1]);
×
3308
            argIndex += 1;
×
3309
        }
3310
        else if (strcmp(argv[argIndex], "efpool") == 0 || strcmp(argv[argIndex], "efortpool") == 0) // set forts
85 ✔
3311
        {
3312
            if (check_input_amount(argc, argv, argIndex, 1))
×
3313
                exit(1);
×
3314
            efpool = std::stoi(argv[argIndex + 1]);
×
3315
            argIndex += 1;
×
3316
        }
3317
        else if (strcmp(argv[argIndex], "yd") == 0 || strcmp(argv[argIndex], "ydom") == 0) // set dominions
85 ✔
3318
        {
3319
            if (check_input_amount(argc, argv, argIndex, 1))
×
3320
                exit(1);
×
3321
            opt_doms = std::string(argv[argIndex + 1]);
×
3322
            argIndex += 1;
×
3323
        }
3324
        else if (strcmp(argv[argIndex], "ed") == 0 || strcmp(argv[argIndex], "edom") == 0) // set enemies' dominions
85 ✔
3325
        {
3326
            if (check_input_amount(argc, argv, argIndex, 1))
×
3327
                exit(1);
×
3328
            opt_enemy_doms = std::string(argv[argIndex + 1]);
×
3329
            argIndex += 1;
×
3330
        }
3331
        else if (strcmp(argv[argIndex], "sim") == 0)
85 ✔
3332
        {
3333
            if (check_input_amount(argc, argv, argIndex, 1))
78 ✔
3334
                exit(1);
×
3335
            opt_todo.push_back(std::make_tuple((unsigned)atoi(argv[argIndex + 1]), 0u, simulate));
78 ✔
3336
            if (std::get<0>(opt_todo.back()) < 10)
78 ✔
3337
            {
3338
                opt_num_threads = 1;
×
3339
            }
3340
            argIndex += 1;
78 ✔
3341
        }
3342
        // climbing tasks
3343
        else if (strcmp(argv[argIndex], "climbex") == 0)
7 ✔
3344
        {
3345
            if (check_input_amount(argc, argv, argIndex, 2))
1 ✔
3346
                exit(1);
×
3347
            opt_todo.push_back(std::make_tuple((unsigned)atoi(argv[argIndex + 1]), (unsigned)atoi(argv[argIndex + 2]), climb));
1 ✔
3348
            if (std::get<1>(opt_todo.back()) < 10)
1 ✔
3349
            {
3350
                opt_num_threads = 1;
×
3351
            }
3352
            opt_do_optimization = true;
1 ✔
3353
            opt_multi_optimization = true;
1 ✔
3354
            argIndex += 2;
1 ✔
3355
        }
3356
        else if (strcmp(argv[argIndex], "climb") == 0)
6 ✔
3357
        {
3358
            if (check_input_amount(argc, argv, argIndex, 1))
2 ✔
3359
                exit(1);
×
3360
            opt_todo.push_back(std::make_tuple((unsigned)atoi(argv[argIndex + 1]), (unsigned)atoi(argv[argIndex + 1]), climb));
2 ✔
3361
            if (std::get<1>(opt_todo.back()) < 10)
2 ✔
3362
            {
3363
                opt_num_threads = 1;
1 ✔
3364
            }
3365
            opt_do_optimization = true;
2 ✔
3366
            opt_multi_optimization = true;
2 ✔
3367
            argIndex += 1;
2 ✔
3368
        }
3369
        else if (strcmp(argv[argIndex], "climb_forts") == 0)
4 ✔
3370
        {
3371
            if (check_input_amount(argc, argv, argIndex, 1))
×
3372
                exit(1);
×
3373
            opt_todo.push_back(std::make_tuple((unsigned)atoi(argv[argIndex + 1]), (unsigned)atoi(argv[argIndex + 1]), climb_forts));
×
3374
            if (std::get<1>(opt_todo.back()) < 10)
×
3375
            {
3376
                opt_num_threads = 1;
×
3377
            }
3378
            argIndex += 1;
×
3379
        }
3380
        else if (strcmp(argv[argIndex], "anneal") == 0)
4 ✔
3381
        {
3382
            if (check_input_amount(argc, argv, argIndex, 3))
1 ✔
3383
                exit(1);
×
3384
            opt_todo.push_back(std::make_tuple((unsigned)atoi(argv[argIndex + 1]), (unsigned)atoi(argv[argIndex + 1]), anneal));
1 ✔
3385
            temperature = std::stod(argv[argIndex + 2]);
2 ✔
3386
            coolingRate = std::stod(argv[argIndex + 3]);
2 ✔
3387
            if (std::get<1>(opt_todo.back()) < 10)
1 ✔
3388
            {
3389
                opt_num_threads = 1;
×
3390
            }
3391
            opt_do_optimization = true;
1 ✔
3392
            opt_multi_optimization = true;
1 ✔
3393
            argIndex += 3;
1 ✔
3394
        }
3395
        else {
3396
            tokenParsed = false;
3397
        }
3398
        
3399
        if (!tokenParsed)
428 ✔
3400
        {
3401
        //no indent: keep two parts of a nested if at the same level
3402
        if (strcmp(argv[argIndex], "genetic") == 0)
3 ✔
3403
        {
3404
            if (check_input_amount(argc, argv, argIndex, 1))
1 ✔
3405
                exit(1);
×
3406
            opt_todo.push_back(std::make_tuple((unsigned)atoi(argv[argIndex + 1]), (unsigned)atoi(argv[argIndex + 1]), genetic));
1 ✔
3407
            if (std::get<1>(opt_todo.back()) < 10)
1 ✔
3408
            {
3409
                opt_num_threads = 1;
×
3410
            }
3411
            opt_do_optimization = true;
1 ✔
3412
            opt_multi_optimization = true;
1 ✔
3413
            argIndex += 1;
1 ✔
3414
        }
3415
        else if (strcmp(argv[argIndex], "genetic-pool") == 0 || strcmp(argv[argIndex], "beam-size") == 0 || strcmp(argv[argIndex], "size") == 0)
2 ✔
3416
        {
3417
            if (check_input_amount(argc, argv, argIndex, 1))
×
3418
                exit(1);
×
3419
            pool_size = std::stod(argv[argIndex + 1]);
×
3420
            argIndex += 1;
×
3421
        }
3422
        else if (strcmp(argv[argIndex], "genetic-gen") == 0)
2 ✔
3423
        {
3424
            if (check_input_amount(argc, argv, argIndex, 1))
×
3425
                exit(1);
×
3426
            generations = std::stod(argv[argIndex + 1]);
×
3427
            argIndex += 1;
×
3428
        }
3429
        else if (strcmp(argv[argIndex], "genetic-opts") == 0)
2 ✔
3430
        {
3431
            if (check_input_amount(argc, argv, argIndex, 3))
×
3432
                exit(1);
×
3433
            opt_pool_keep = std::stod(argv[argIndex + 1]);
×
3434
            opt_pool_cross = std::stod(argv[argIndex + 2]);
×
3435
            opt_pool_mutate = std::stod(argv[argIndex + 3]);
×
3436
            argIndex += 3;
×
3437
        }
3438
        else if (strcmp(argv[argIndex], "beam") == 0)
2 ✔
3439
        {
3440
            if (check_input_amount(argc, argv, argIndex, 1))
2 ✔
3441
                exit(1);
×
3442
            opt_todo.push_back(std::make_tuple((unsigned)atoi(argv[argIndex + 1]), (unsigned)atoi(argv[argIndex + 1]), beam));
2 ✔
3443
            if (std::get<1>(opt_todo.back()) < 10)
2 ✔
3444
            {
3445
                opt_num_threads = 1;
1 ✔
3446
            }
3447
            opt_do_optimization = true;
2 ✔
3448
            opt_multi_optimization = true;
2 ✔
3449
            argIndex += 1;
2 ✔
3450
        }
3451
        else if (strcmp(argv[argIndex], "reorder") == 0)
×
3452
        {
3453
            if (check_input_amount(argc, argv, argIndex, 1))
×
3454
                exit(1);
×
3455
            opt_todo.push_back(std::make_tuple((unsigned)atoi(argv[argIndex + 1]), (unsigned)atoi(argv[argIndex + 1]), reorder));
×
3456
            if (std::get<1>(opt_todo.back()) < 10)
×
3457
            {
3458
                opt_num_threads = 1;
×
3459
            }
3460
            opt_do_reorder = true;
×
3461
            argIndex += 1;
×
3462
        }
3463
        else if (strncmp(argv[argIndex], "scale-opts:", 11) == 0)
×
3464
        {
3465
            std::string climb_opts_str(argv[argIndex] + 11);
×
3466
            boost::tokenizer<boost::char_delimiters_separator<char>> climb_opts{climb_opts_str, boost::char_delimiters_separator<char>{false, ",", ""}};
×
3467
            for (const auto &opt : climb_opts)
×
3468
            {
3469
                const auto dot_pos = opt.find(".");
×
3470
                const auto slash_pos = opt.find("/");
×
3471
                const bool has_value = (dot_pos != std::string::npos);
×
3472
                if (slash_pos == std::string::npos)
×
3473
                    throw std::runtime_error("scale-opts:" + opt + " requires an argument");
×
3474
                const std::string &opt_type = has_value ? opt.substr(0, dot_pos) : "";
×
3475
                const std::string opt_name{has_value ? opt.substr(dot_pos + 1, slash_pos - dot_pos - 1) : opt.substr(0, slash_pos)};
×
3476
                const std::string opt_value{opt.substr(slash_pos + 1)};
×
3477
                if ((opt_name == "hp"))
×
3478
                {
3479
                    hp_scale = atof(opt_value.c_str());
×
3480
                }
3481
                else if ((opt_name == "atk"))
×
3482
                {
3483
                    atk_scale = atof(opt_value.c_str());
×
3484
                }
3485
                else if (opt_name == "x")
×
3486
                {
3487
                    x_skill_scale[skill_name_to_id(opt_type)] = atof(opt_value.c_str());
×
3488
                }
3489
                else if (opt_name == "n")
×
3490
                {
3491
                    n_skill_scale[skill_name_to_id(opt_type)] = atof(opt_value.c_str());
×
3492
                }
3493
                else if (opt_name == "c")
×
3494
                {
3495
                    c_skill_scale[skill_name_to_id(opt_type)] = atof(opt_value.c_str());
×
3496
                }
3497
                else
3498
                {
3499
                    std::cerr << "Error: Unknown scale option " << opt_name << " of " << opt_type;
×
3500
                    if (has_value)
×
3501
                    {
3502
                        std::cerr << " (value is: " << opt_value << ")";
×
3503
                    }
3504
                    std::cerr << std::endl;
×
3505
                    exit(1);
×
3506
                }
3507
            }
×
3508
        }
×
3509
        // climbing options
3510
        else if (strncmp(argv[argIndex], "climb-opts:", 11) == 0)
×
3511
        {
3512
            std::string climb_opts_str(argv[argIndex] + 11);
×
3513
            boost::tokenizer<boost::char_delimiters_separator<char>> climb_opts{climb_opts_str, boost::char_delimiters_separator<char>{false, ",", ""}};
×
3514
            for (const auto &opt : climb_opts)
×
3515
            {
3516
                const auto delim_pos = opt.find("=");
×
3517
                const bool has_value = (delim_pos != std::string::npos);
×
3518
                const std::string &opt_name = has_value ? opt.substr(0, delim_pos) : opt;
×
3519
                const std::string opt_value{has_value ? opt.substr(delim_pos + 1) : opt};
×
3520
                auto ensure_opt_value = [](const bool has_value, const std::string &opt_name)
×
3521
                {
3522
                    if (!has_value)
×
3523
                    {
3524
                        throw std::runtime_error("climb-opts:" + opt_name + " requires an argument");
×
3525
                    }
3526
                };
×
3527
                if ((opt_name == "iter-mul") or (opt_name == "iterations-multiplier"))
×
3528
                {
3529
                    ensure_opt_value(has_value, opt_name);
×
3530
                    iterations_multiplier = std::stoi(opt_value);
×
3531
                }
3532
                else if ((opt_name == "egc") or (opt_name == "endgame-commander") or (opt_name == "min-commander-fusion-level"))
×
3533
                {
3534
                    ensure_opt_value(has_value, opt_name);
×
3535
                    use_fused_commander_level = std::stoi(opt_value);
×
3536
                }
3537
                else if (opt_name == "use-all-commander-levels")
×
3538
                {
3539
                    use_top_level_commander = false;
×
3540
                }
3541
                else if (opt_name == "use-all-card-levels")
×
3542
                {
3543
                    use_top_level_card = false;
×
3544
                }
3545
                else if ((opt_name == "recent-boost") or (opt_name == "rb")) // prefer new cards in hill climb and break climb loop faster
×
3546
                {
3547
                    prefered_recent = true;
×
3548
                }
3549
                else if ((opt_name == "recent-boost-times") or (opt_name == "rbt")) // prefer new cards in hill climb and break climb loop faster
×
3550
                {
3551
                    ensure_opt_value(has_value, opt_name);
×
3552
                    prefered_factor = std::stoi(opt_value);
×
3553
                }
3554
                else if ((opt_name == "recent-boost-percent") or (opt_name == "rbp")) // prefer new cards in hill climb and break climb loop faster
×
3555
                {
3556
                    ensure_opt_value(has_value, opt_name);
×
3557
                    recent_percent = std::stoi(opt_value);
×
3558
                }
3559
                else if ((opt_name == "otd") or (opt_name == "open-the-deck"))
×
3560
                {
3561
                    mode_open_the_deck = true;
×
3562
                }
3563
                else
3564
                {
3565
                    std::cerr << "Error: Unknown climb option " << opt_name;
×
3566
                    if (has_value)
×
3567
                    {
3568
                        std::cerr << " (value is: " << opt_value << ")";
×
3569
                    }
3570
                    std::cerr << std::endl;
×
3571
                    exit(1);
×
3572
                }
3573
            }
×
3574
        }
×
3575
        else if (strcmp(argv[argIndex], "debug") == 0)
×
3576
        {
3577
            opt_todo.push_back(std::make_tuple(0u, 0u, debug));
×
3578
            opt_num_threads = 1;
×
3579
            // disable saving to db
3580
            use_db_write= false;
×
3581
            use_db_load = false;
×
3582
        }
3583
        else if (strcmp(argv[argIndex], "debuguntil") == 0)
×
3584
        {
3585
            // output the debug info for the first battle that min_score <= score <= max_score.
3586
            // E.g., 0 0: lose; 100 100: win (non-raid); 20 100: at least 20 damage (raid).
3587
            if (check_input_amount(argc, argv, argIndex, 2))
×
3588
                exit(1);
×
3589
            opt_todo.push_back(std::make_tuple((unsigned)atoi(argv[argIndex + 1]), (unsigned)atoi(argv[argIndex + 2]), debuguntil));
×
3590
            opt_num_threads = 1;
×
3591
            argIndex += 2;
×
3592
            // disable saving to db
3593
            use_db_write= false;
×
3594
            use_db_load = false;
×
3595
        }
3596
        else
3597
        {
3598
            std::cerr << "Error: Unknown option " << argv[argIndex] << std::endl;
×
3599
            exit(1);
×
3600
        }
3601
        } // if (tokenParsed)
3602
    }
3603
    load_db(prefix);
170 ✔
3604
    load_ml(prefix);
170 ✔
3605

3606
#ifdef _OPENMP
3607
    opt_num_threads = omp_get_max_threads();
3608
#endif
3609
    // delete, since prefix/suffix might change we reload all cards.
3610
    // redundant to calling init() before run()
3611
    all_cards.clear();
85 ✔
3612
    owned_alpha_dominion = nullptr;
85 ✔
3613

3614
    all_cards = Cards();
85 ✔
3615
    Decks decks;
85 ✔
3616
    std::unordered_map<std::string, std::string> bge_aliases;
85 ✔
3617
    load_skills_set_xml(all_cards, prefix + "data/skills_set.xml", true);
85 ✔
3618
    for (unsigned section = 1;
1,828 ✔
3619
         load_cards_xml(all_cards, prefix + "data/cards_section_" + std::to_string(section) + ".xml", false);
3,656 ✔
3620
         ++section)
3621
        ;
3622
    all_cards.organize();
85 ✔
3623
    load_levels_xml(all_cards, prefix + "data/levels.xml", true);
85 ✔
3624
    all_cards.fix_dominion_recipes();
85 ✔
3625
    for (const auto &suffix : fn_suffix_list)
170 ✔
3626
    {
3627
        load_decks_xml(decks, all_cards, prefix + "data/missions" + suffix + ".xml", prefix + "data/raids" + suffix + ".xml", suffix.empty());
510 ✔
3628
        load_recipes_xml(all_cards, prefix + "data/fusion_recipes_cj2" + suffix + ".xml", suffix.empty());
340 ✔
3629
        read_card_abbrs(all_cards, prefix + "data/cardabbrs" + suffix + ".txt");
340 ✔
3630
    }
3631
    for (const auto &suffix : fn_suffix_list)
170 ✔
3632
    {
3633
        load_custom_decks(decks, all_cards, prefix + "data/customdecks" + suffix + ".txt");
340 ✔
3634
        map_keys_to_set(read_custom_cards(all_cards, prefix + "data/allowed_candidates" + suffix + ".txt", false), allowed_candidates);
340 ✔
3635
        map_keys_to_set(read_custom_cards(all_cards, prefix + "data/disallowed_candidates" + suffix + ".txt", false), disallowed_candidates);
340 ✔
3636
        map_keys_to_set(read_custom_cards(all_cards, prefix + "data/disallowed_recipes" + suffix + ".txt", false), disallowed_recipes);
340 ✔
3637
    }
3638

3639
    read_bge_aliases(bge_aliases, prefix + "data/bges.txt");
85 ✔
3640

3641
    fill_skill_table();
85 ✔
3642

3643
    if (opt_do_optimization and use_owned_cards)
85 ✔
3644
    {
3645
        if (opt_owned_cards_str_list.empty())
7 ✔
3646
        { // load default files only if specify no -o=
3647
            for (const auto &suffix : fn_suffix_list)
14 ✔
3648
            {
3649
                std::string filename = prefix + "data/ownedcards" + suffix + ".txt";
21 ✔
3650
                if (boost::filesystem::exists(filename))
21 ✔
3651
                {
3652
                    opt_owned_cards_str_list.push_back(filename);
7 ✔
3653
                }
3654
            }
7 ✔
3655
        }
3656
        std::map<unsigned, unsigned> _owned_cards;
7 ✔
3657
        for (const auto &oc_str : opt_owned_cards_str_list)
14 ✔
3658
        {
3659
            read_owned_cards(all_cards, _owned_cards, oc_str);
7 ✔
3660
        }
3661

3662
        // keep only one copy of alpha dominion
3663
        for (auto owned_it = _owned_cards.begin(); owned_it != _owned_cards.end();)
175 ✔
3664
        {
3665
            const Card *owned_card = all_cards.by_id(owned_it->first);
168 ✔
3666
            bool need_remove = (!owned_it->second);
168 ✔
3667
            if (!need_remove && (owned_card->m_category == CardCategory::dominion_alpha))
168 ✔
3668
            {
3669
                if (!owned_alpha_dominion)
21 ✔
3670
                {
3671
                    owned_alpha_dominion = owned_card;
7 ✔
3672
                }
3673
                else
3674
                {
3675
                    /*std::cerr << "Warning: ownedcards already contains alpha dominion (" << owned_alpha_dominion->m_name
3676
                      << "): removing additional " << owned_card->m_name << std::endl;
3677
                      need_remove = true;*/
3678
                }
3679
            }
3680
            if (need_remove)
168 ✔
3681
            {
3682
                owned_it = _owned_cards.erase(owned_it);
×
3683
            }
3684
            else
3685
            {
3686
                ++owned_it;
168 ✔
3687
            }
3688
        }
3689
        if (!owned_alpha_dominion && use_owned_dominions)
7 ✔
3690
        {
3691
            // owned_alpha_dominion = all_cards.by_id(50002);
3692
            // std::cerr << "Warning: dominion climbing enabled and no alpha dominion found in owned cards, adding default "
3693
            //     << owned_alpha_dominion->m_name << std::endl;
3694
        }
3695
        if (owned_alpha_dominion)
7 ✔
3696
        {
3697
            _owned_cards[owned_alpha_dominion->m_id] = 1;
7 ✔
3698
        }
3699

3700
        // remap owned cards to unordered map (should be quicker for searching)
3701
        owned_cards.reserve(_owned_cards.size());
7 ✔
3702
        for (auto owned_it = _owned_cards.begin(); owned_it != _owned_cards.end(); ++owned_it)
175 ✔
3703
        {
3704
            owned_cards[owned_it->first] = owned_it->second;
168 ✔
3705
        }
3706
    }
7 ✔
3707

3708
    // parse BGEs
3709
    opt_bg_effects[0].fill(0);
2,380 ✔
3710
    opt_bg_effects[1].fill(0);
340 ✔
3711
    for (int player = 2; player >= 0; --player)
340 ✔
3712
    {
3713
        for (auto &&opt_effect : opt_effects[player])
317 ✔
3714
        {
3715
            std::unordered_set<std::string> used_bge_aliases;
62 ✔
3716
            if (!parse_bge(opt_effect, player, bge_aliases, opt_bg_effects[0], opt_bg_effects[1], opt_bg_skills[0], opt_bg_skills[1], used_bge_aliases))
186 ✔
3717
            {
3718
                exit(1);
×
3719
            }
3720
        }
62 ✔
3721
    }
3722

3723
    // parse allowed candidates from options
3724
    try
85 ✔
3725
    {
3726
        auto &&id_marks = string_to_ids(all_cards, opt_allow_candidates, "allowed-candidates");
85 ✔
3727
        for (const auto &cid : id_marks.first)
85 ✔
3728
        {
3729
            allowed_candidates.insert(cid);
×
3730
        }
3731
    }
×
3732
    catch (const std::runtime_error &e)
×
3733
    {
3734
        std::cerr << "Error: allow-candidates " << opt_allow_candidates << ": " << e.what() << std::endl;
×
3735
        exit(1);
×
3736
    }
×
3737

3738
    // parse disallowed candidates from options
3739
    try
85 ✔
3740
    {
3741
        auto &&id_marks = string_to_ids(all_cards, opt_disallow_candidates, "disallowed-candidates");
85 ✔
3742
        for (const auto &cid : id_marks.first)
85 ✔
3743
        {
3744
            disallowed_candidates.insert(cid);
×
3745
        }
3746
    }
×
3747
    catch (const std::runtime_error &e)
×
3748
    {
3749
        std::cerr << "Error: disallow-candidates " << opt_disallow_candidates << ": " << e.what() << std::endl;
×
3750
        exit(1);
×
3751
    }
×
3752

3753
    // parse & drop disallowed recipes
3754
    try
85 ✔
3755
    {
3756
        auto &&id_dis_recipes = string_to_ids(all_cards, opt_disallow_recipes, "disallowed-recipes");
85 ✔
3757
        for (auto &cid : id_dis_recipes.first)
85 ✔
3758
        {
3759
            all_cards.erase_fusion_recipe(cid);
×
3760
        }
3761
    }
×
3762
    catch (const std::runtime_error &e)
×
3763
    {
3764
        std::cerr << "Error: disallow-recipes " << opt_disallow_recipes << ": " << e.what() << std::endl;
×
3765
        exit(1);
×
3766
    }
×
3767
    for (auto cid : disallowed_recipes)
85 ✔
3768
    {
3769
        all_cards.erase_fusion_recipe(cid);
×
3770
    }
3771

3772
#ifndef NQUEST
3773
    if (!opt_quest.empty())
3774
    {
3775
        try
3776
        {
3777
            optimization_mode = OptimizationMode::quest;
3778
            std::vector<std::string> tokens;
3779
            boost::split(tokens, opt_quest, boost::is_any_of(" -"));
3780
            if (tokens.size() < 3)
3781
            {
3782
                throw std::runtime_error("Expect one of: su n skill; sd n skill; cu n faction/strcture; ck n structure");
3783
            }
3784
            auto type_str = boost::to_lower_copy(tokens[0]);
3785
            tuo::quest.quest_value = boost::lexical_cast<unsigned>(tokens[1]);
3786
            auto key_str = boost::to_lower_copy(tokens[2]);
3787
            unsigned quest_index = 3;
3788
            if (type_str == "su" || type_str == "sd")
3789
            {
3790
                Skill::Skill skill_id = skill_name_to_id(key_str);
3791
                if (skill_id == Skill::no_skill)
3792
                {
3793
                    std::cerr << "Error: Expect skill in quest \"" << opt_quest << "\".\n";
3794
                    exit(1);
3795
                }
3796
                tuo::quest.quest_type = type_str == "su" ? QuestType::skill_use : QuestType::skill_damage;
3797
                tuo::quest.quest_key = skill_id;
3798
            }
3799
            else if (type_str == "cu" || type_str == "ck")
3800
            {
3801
                if (key_str == "assault")
3802
                {
3803
                    tuo::quest.quest_type = type_str == "cu" ? QuestType::type_card_use : QuestType::type_card_kill;
3804
                    tuo::quest.quest_key = CardType::assault;
3805
                }
3806
                else if (key_str == "structure")
3807
                {
3808
                    tuo::quest.quest_type = type_str == "cu" ? QuestType::type_card_use : QuestType::type_card_kill;
3809
                    tuo::quest.quest_key = CardType::structure;
3810
                }
3811
                else
3812
                {
3813
                    for (unsigned i = 1; i < Faction::num_factions; ++i)
3814
                    {
3815
                        if (key_str == boost::to_lower_copy(faction_names[i]))
3816
                        {
3817
                            tuo::quest.quest_type = type_str == "cu" ? QuestType::faction_assault_card_use : QuestType::faction_assault_card_kill;
3818
                            tuo::quest.quest_key = i;
3819
                            break;
3820
                        }
3821
                    }
3822
                    if (tuo::quest.quest_key == 0)
3823
                    {
3824
                        std::cerr << "Error: Expect assault, structure or faction in quest \"" << opt_quest << "\".\n";
3825
                        exit(1);
3826
                    }
3827
                }
3828
            }
3829
            else if (type_str == "cs")
3830
            {
3831
                unsigned card_id;
3832
                unsigned card_num;
3833
                char num_sign;
3834
                char mark;
3835
                try
3836
                {
3837
                    parse_card_spec(all_cards, key_str, card_id, card_num, num_sign, mark);
3838
                    tuo::quest.quest_type = QuestType::card_survival;
3839
                    tuo::quest.quest_key = card_id;
3840
                }
3841
                catch (const std::runtime_error &e)
3842
                {
3843
                    std::cerr << "Error: Expect a card in quest \"" << opt_quest << "\".\n";
3844
                    exit(1);
3845
                }
3846
            }
3847
            else if (type_str == "suoc" && tokens.size() >= 4)
3848
            {
3849
                Skill::Skill skill_id = skill_name_to_id(key_str);
3850
                if (skill_id == Skill::no_skill)
3851
                {
3852
                    std::cerr << "Error: Expect skill in quest \"" << opt_quest << "\".\n";
3853
                    exit(1);
3854
                }
3855
                unsigned card_id;
3856
                unsigned card_num;
3857
                char num_sign;
3858
                char mark;
3859
                try
3860
                {
3861
                    parse_card_spec(all_cards, boost::to_lower_copy(tokens[3]), card_id, card_num, num_sign, mark);
3862
                    quest_index += 1;
3863
                    tuo::quest.quest_type = QuestType::skill_use;
3864
                    tuo::quest.quest_key = skill_id;
3865
                    tuo::quest.quest_2nd_key = card_id;
3866
                }
3867
                catch (const std::runtime_error &e)
3868
                {
3869
                    std::cerr << "Error: Expect a card in quest \"" << opt_quest << "\".\n";
3870
                    exit(1);
3871
                }
3872
            }
3873
            else
3874
            {
3875
                throw std::runtime_error("Expect one of: su n skill; sd n skill; cu n faction/strcture; ck n structure");
3876
            }
3877
            tuo::quest.quest_score = tuo::quest.quest_value;
3878
            for (unsigned i = quest_index; i < tokens.size(); ++i)
3879
            {
3880
                const auto &token = tokens[i];
3881
                if (token == "each")
3882
                {
3883
                    tuo::quest.must_fulfill = true;
3884
                    tuo::quest.quest_score = 100;
3885
                }
3886
                else if (token == "win")
3887
                {
3888
                    tuo::quest.must_win = true;
3889
                }
3890
                else if (token.substr(0, 2) == "q=")
3891
                {
3892
                    tuo::quest.quest_score = boost::lexical_cast<unsigned>(token.substr(2));
3893
                }
3894
                else if (token.substr(0, 2) == "w=")
3895
                {
3896
                    tuo::quest.win_score = boost::lexical_cast<unsigned>(token.substr(2));
3897
                }
3898
                else
3899
                {
3900
                    throw std::runtime_error("Cannot recognize " + token);
3901
                }
3902
            }
3903
            max_possible_score[(size_t)optimization_mode] = tuo::quest.quest_score + tuo::quest.win_score;
3904
        }
3905
        catch (const boost::bad_lexical_cast &e)
3906
        {
3907
            std::cerr << "Error: Expect a number in quest \"" << opt_quest << "\".\n";
3908
            exit(1);
3909
        }
3910
        catch (const std::runtime_error &e)
3911
        {
3912
            std::cerr << "Error: quest " << opt_quest << ": " << e.what() << std::endl;
3913
            exit(1);
3914
        }
3915
    }
3916
#endif
3917

3918
    // std::string your_deck_name{argv[1]};
3919
    auto &&your_deck_list_parsed = parse_deck_list(your_deck_list, decks);
170 ✔
3920
    auto &&enemy_deck_list_parsed = parse_deck_list(enemy_deck_list, decks);
170 ✔
3921

3922
    // Deck* your_deck{nullptr};
3923
    std::vector<Deck *> your_decks;
85 ✔
3924
    std::vector<Deck *> enemy_decks;
85 ✔
3925
    std::vector<long double> your_decks_factors;
85 ✔
3926
    std::vector<long double> enemy_decks_factors;
85 ✔
3927
    for (auto deck_parsed : your_deck_list_parsed)
398 ✔
3928
    {
3929
        Deck *your_deck{nullptr};
313 ✔
3930
        try
313 ✔
3931
        {
3932
            your_deck = find_deck(decks, all_cards, deck_parsed.first)->clone();
626 ✔
3933
        }
3934
        catch (const std::runtime_error &e)
×
3935
        {
3936
            std::cerr << "Error: Deck " << deck_parsed.first << ": " << e.what() << std::endl;
×
3937
            exit(1);
×
3938
        }
×
3939
        if (your_deck == nullptr)
313 ✔
3940
        {
3941
            std::cerr << "Error: Invalid attack deck name/hash " << deck_parsed.first << ".\n";
×
3942
            exit(1);
×
3943
        }
3944
        else if (!your_deck->variable_cards.empty())
313 ✔
3945
        {
3946
            std::cerr << "Error: Invalid attack deck " << deck_parsed.first << ": has optional cards.\n";
×
3947
            your_deck = nullptr;
×
3948
        }
3949
        else if (!your_deck->variable_forts.empty())
313 ✔
3950
        {
3951
            std::cerr << "Error: Invalid attack deck " << deck_parsed.first << ": has optional cards.\n";
×
3952
            your_deck = nullptr;
×
3953
        }
3954
        if (your_deck == nullptr)
313 ✔
3955
        {
3956
            usage(argc, argv);
×
3957
            exit(1);
×
3958
            // return 255;
3959
        }
3960

3961
        your_deck->strategy = opt_your_strategy;
313 ✔
3962
        if (!opt_forts.empty())
313 ✔
3963
        {
3964
            try
×
3965
            {
3966
                if (!yfpool)
×
3967
                    your_deck->add_forts(opt_forts + ",");
×
3968
                else
3969
                    your_deck->add_pool_forts(opt_forts + ",", yfpool);
×
3970
            }
3971
            catch (const std::runtime_error &e)
×
3972
            {
3973
                std::cerr << "Error: yfort " << opt_forts << ": " << e.what() << std::endl;
×
3974
                exit(1);
×
3975
            }
×
3976
        }
3977
        if (!opt_doms.empty())
313 ✔
3978
        {
3979
            try
×
3980
            {
3981
                your_deck->add_dominions(opt_doms + ",", true);
×
3982
            }
3983
            catch (const std::runtime_error &e)
×
3984
            {
3985
                std::cerr << "Error: ydom " << opt_doms << ": " << e.what() << std::endl;
×
3986
                exit(1);
×
3987
            }
×
3988
        }
3989

3990
        try
313 ✔
3991
        {
3992
            your_deck->set_vip_cards(opt_vip);
313 ✔
3993
        }
3994
        catch (const std::runtime_error &e)
×
3995
        {
3996
            std::cerr << "Error: vip " << opt_vip << ": " << e.what() << std::endl;
×
3997
            exit(1);
×
3998
        }
×
3999

4000
        try
313 ✔
4001
        {
4002
            your_deck->set_given_hand(opt_hand);
313 ✔
4003
        }
4004
        catch (const std::runtime_error &e)
×
4005
        {
4006
            std::cerr << "Error: hand " << opt_hand << ": " << e.what() << std::endl;
×
4007
            exit(1);
×
4008
        }
×
4009

4010
        // add cards from the decks to requirement/inventory
4011
        if (opt_do_optimization || opt_do_reorder)
313 ✔
4012
        {
4013
            if (opt_keep_commander) // TODO this does not work with multi deck mode
7 ✔
4014
            {
4015
                requirement.num_cards[your_deck->commander] = 1;
×
4016
            }
4017
            for (auto &&card_mark : your_deck->card_marks)
7 ✔
4018
            {
4019
                auto &&card = card_mark.first < 0 ? your_deck->commander : your_deck->cards[card_mark.first];
×
4020
                auto mark = card_mark.second;
×
4021
                if ((mark == '!') && ((card_mark.first >= 0) || !opt_keep_commander))
×
4022
                {
4023
                    requirement.num_cards[card] += 1;
×
4024
                }
4025
            }
4026
            if (opt_skip_unclaimed_decks)
7 ✔
4027
            {
4028
                // skip decks that can not be build
4029
                if (claim_cards_needed({your_deck->commander}))
×
4030
                    continue;
×
4031
                if (claim_cards_needed(your_deck->cards))
×
4032
                    continue;
×
4033
                if (your_deck->alpha_dominion && claim_cards_needed({your_deck->alpha_dominion}))
×
4034
                    continue;
×
4035
            }
4036
            else if (opt_do_optimization and use_owned_cards)
7 ✔
4037
            {
4038
                // Force to claim cards in your initial deck.
4039
                claim_cards({your_deck->commander});
7 ✔
4040
                claim_cards(your_deck->cards);
7 ✔
4041
                if (your_deck->alpha_dominion)
7 ✔
4042
                    claim_cards({your_deck->alpha_dominion});
×
4043
            }
4044

4045
            // shrink any oversized deck to maximum of 10 cards + commander
4046
            // NOTE: do this AFTER the call to claim_cards so that passing an initial deck of >10 cards
4047
            //       can be used as a "shortcut" for adding them to owned cards. Also this allows climb
4048
            //       to figure out which are the best 10, rather than restricting climb to the first 10.
4049
            if (your_deck->cards.size() > max_deck_len)
7 ✔
4050
            {
4051
                your_deck->shrink(max_deck_len);
×
4052
                if (debug_print >= 0)
×
4053
                {
4054
                    std::cerr << "WARNING: Too many cards in your deck. Trimmed.\n";
×
4055
                }
4056
            }
4057
        }
4058

4059
        your_decks.push_back(your_deck);
313 ✔
4060
        your_decks_factors.push_back(deck_parsed.second);
313 ✔
4061
    }
313 ✔
4062
    if (your_decks.size() == 0)
85 ✔
4063
    {
4064
        std::cerr << "No deck set. Probably due to 'strict-ownedcards' and a deck that is incompatible to the set 'ownedcards'." << std::endl;
×
4065
        exit(1);
×
4066
    }
4067
    target_score = opt_target_score.empty() ? max_possible_score[(size_t)optimization_mode] : boost::lexical_cast<long double>(opt_target_score);
85 ✔
4068

4069
    for (auto deck_parsed : enemy_deck_list_parsed)
398 ✔
4070
    {
4071
        Deck *enemy_deck{nullptr};
313 ✔
4072
        try
313 ✔
4073
        {
4074
            enemy_deck = find_deck(decks, all_cards, deck_parsed.first);
626 ✔
4075
        }
4076
        catch (const std::runtime_error &e)
×
4077
        {
4078
            std::cerr << "Error: Deck " << deck_parsed.first << ": " << e.what() << std::endl;
×
4079
            exit(1);
×
4080
        }
×
4081
        if (enemy_deck == nullptr)
313 ✔
4082
        {
4083
            std::cerr << "Error: Invalid defense deck name/hash " << deck_parsed.first << ".\n";
×
4084
            usage(argc, argv);
×
4085
            exit(1);
×
4086
        }
4087
        if (optimization_mode == OptimizationMode::notset)
313 ✔
4088
        {
4089
            if (enemy_deck->decktype == DeckType::raid)
85 ✔
4090
            {
4091
                optimization_mode = OptimizationMode::raid;
×
4092
            }
4093
            else if (enemy_deck->decktype == DeckType::campaign)
85 ✔
4094
            {
4095
                gamemode = surge;
×
4096
                optimization_mode = OptimizationMode::campaign;
×
4097
            }
4098
            else
4099
            {
4100
                optimization_mode = OptimizationMode::winrate;
85 ✔
4101
            }
4102
        }
4103
        enemy_deck->strategy = opt_enemy_strategy;
313 ✔
4104
        if (!opt_enemy_doms.empty())
313 ✔
4105
        {
4106
            try
×
4107
            {
4108
                enemy_deck->add_dominions(opt_enemy_doms + ",", true);
×
4109
            }
4110
            catch (const std::runtime_error &e)
×
4111
            {
4112
                std::cerr << "Error: edom " << opt_enemy_doms << ": " << e.what() << std::endl;
×
4113
                exit(1);
×
4114
            }
×
4115
        }
4116
        if (!opt_enemy_forts.empty())
313 ✔
4117
        {
4118
            try
×
4119
            {
4120
                if (!efpool)
×
4121
                    enemy_deck->add_forts(opt_enemy_forts + ",");
×
4122
                else
4123
                    enemy_deck->add_pool_forts(opt_enemy_forts + ",", efpool);
×
4124
            }
4125
            catch (const std::runtime_error &e)
×
4126
            {
4127
                std::cerr << "Error: efort " << opt_enemy_forts << ": " << e.what() << std::endl;
×
4128
                exit(1);
×
4129
            }
×
4130
        }
4131
        try
313 ✔
4132
        {
4133
            enemy_deck->set_given_hand(opt_enemy_hand);
313 ✔
4134
        }
4135
        catch (const std::runtime_error &e)
×
4136
        {
4137
            std::cerr << "Error: enemy:hand " << opt_enemy_hand << ": " << e.what() << std::endl;
×
4138
            exit(1);
×
4139
        }
×
4140
        enemy_decks.push_back(enemy_deck);
313 ✔
4141
        enemy_decks_factors.push_back(deck_parsed.second);
313 ✔
4142
    }
313 ✔
4143

4144
    std::vector<long double> factors((opt_multi_optimization ? 1 : your_decks_factors.size()) * enemy_decks_factors.size());
85 ✔
4145
    for (unsigned i = 0; i < factors.size(); ++i)
2,146 ✔
4146
    {
4147
        factors[i] = your_decks_factors[i / enemy_decks_factors.size()] * enemy_decks_factors[i % enemy_decks_factors.size()];
2,061 ✔
4148
    }
4149

4150
    if ((opt_do_optimization || opt_do_reorder) && (your_decks.size() != 1 && !opt_multi_optimization))
85 ✔
4151
    {
4152
        std::cerr << "Optimization only works with a single deck" << std::endl;
×
4153
        exit(1);
×
4154
    }
4155

4156
    if (debug_print >= 0)
85 ✔
4157
    {
4158
        for (unsigned i(0); i < your_decks.size(); ++i)
398 ✔
4159
        {
4160
            auto your_deck = your_decks[i];
313 ✔
4161
            std::cout << "Your Deck:" << your_decks_factors[i] << ": " << (debug_print > 0 ? your_deck->long_description() : your_deck->medium_description()) << std::endl;
626 ✔
4162
        }
4163
        for (unsigned bg_effect = PassiveBGE::no_bge; bg_effect < PassiveBGE::num_passive_bges; ++bg_effect)
2,380 ✔
4164
        {
4165
            auto bge_value = opt_bg_effects[0][bg_effect];
2,295 ✔
4166
            if (!bge_value)
2,295 ✔
4167
                continue;
2,260 ✔
4168
            std::cout << "Your BG Effect: " << passive_bge_names[bg_effect];
35 ✔
4169
            if (bge_value != -1)
35 ✔
4170
                std::cout << " " << bge_value;
35 ✔
4171
            std::cout << std::endl;
2,295 ✔
4172
        }
4173
        for (const auto &bg_skill : opt_bg_skills[0])
86 ✔
4174
        {
4175
            std::cout << "Your BG Skill: " << skill_description(all_cards, bg_skill) << std::endl;
1 ✔
4176
        }
4177

4178
        for (unsigned i(0); i < enemy_decks.size(); ++i)
398 ✔
4179
        {
4180
            auto enemy_deck = enemy_decks[i];
313 ✔
4181
            std::cout << "Enemy's Deck:" << enemy_decks_factors[i] << ": "
313 ✔
4182
                      << (debug_print > 0 ? enemy_deck->long_description() : enemy_deck->medium_description()) << std::endl;
626 ✔
4183
        }
4184
        for (unsigned bg_effect = PassiveBGE::no_bge; bg_effect < PassiveBGE::num_passive_bges; ++bg_effect)
2,380 ✔
4185
        {
4186
            auto bge_value = opt_bg_effects[1][bg_effect];
2,295 ✔
4187
            if (!bge_value)
2,295 ✔
4188
                continue;
2,260 ✔
4189
            std::cout << "Enemy's BG Effect: " << passive_bge_names[bg_effect];
35 ✔
4190
            if (bge_value != -1)
35 ✔
4191
                std::cout << " " << bge_value;
35 ✔
4192
            std::cout << std::endl;
2,295 ✔
4193
        }
4194
        for (const auto &bg_skill : opt_bg_skills[1])
86 ✔
4195
        {
4196
            std::cout << "Enemy's BG Skill: " << skill_description(all_cards, bg_skill) << std::endl;
1 ✔
4197
        }
4198
    }
4199
    if (enemy_decks.size() == 1)
85 ✔
4200
    {
4201
        auto enemy_deck = enemy_decks[0];
47 ✔
4202
        for (auto x_mult_ss : enemy_deck->effects)
47 ✔
4203
        {
4204
            if (debug_print >= 0)
×
4205
            {
4206
                std::cout << "Enemy's X-Mult BG Skill (effective X = round_up[X * " << enemy_deck->level << "]): "
×
4207
                          << skill_description(all_cards, x_mult_ss);
×
4208
                if (x_mult_ss.x)
×
4209
                {
4210
                    std::cout << " (eff. X = " << ceil(x_mult_ss.x * enemy_deck->level) << ")";
×
4211
                }
4212
                std::cout << std::endl;
×
4213
            }
4214
            opt_bg_skills[1].push_back({x_mult_ss.id,
×
4215
                                        (unsigned)ceil(x_mult_ss.x * enemy_deck->level),
×
4216
                                        x_mult_ss.y, x_mult_ss.n, x_mult_ss.c,
×
4217
                                        x_mult_ss.s, x_mult_ss.s2, x_mult_ss.all});
×
4218
        }
4219
    }
4220
    auto proc_decks = your_decks;
85 ✔
4221
    if (opt_multi_optimization)
85 ✔
4222
    { // only one deck at a time
4223
        proc_decks.erase(proc_decks.begin() + 1, proc_decks.end());
7 ✔
4224
    }
4225
    Process p(opt_num_threads, all_cards, decks, proc_decks, enemy_decks, factors, gamemode,
85 ✔
4226
#ifndef NQUEST
4227
              tuo::quest,
4228
#endif
4229
              opt_bg_effects[0], opt_bg_effects[1], opt_bg_skills[0], opt_bg_skills[1]);
85 ✔
4230

4231
    auto your_deck = your_decks[0];
85 ✔
4232

4233
    if (!opt_todo.empty())
85 ✔
4234
    {
4235
    auto op = opt_todo.back();
85 ✔
4236
    // for (auto op: opt_todo)
4237
    {
85 ✔
4238
        switch (std::get<2>(op))
85 ✔
4239
        {
4240
        case noop:
4241
            break;
4242
        case simulate:
78 ✔
4243
        {
78 ✔
4244
            EvaluatedResults results = {EvaluatedResults::first_type(enemy_decks.size() * your_decks.size()), 0};
78 ✔
4245
            results = p.evaluate(std::get<0>(op), results);
78 ✔
4246
            print_results(results, p.factors);
78 ✔
4247
            fr = std::make_pair(your_deck->clone(), compute_score(results, p.factors));
78 ✔
4248
            print_sim_card_values(fr.first, p, std::get<0>(op));
78 ✔
4249
            break;
78 ✔
4250
        }
78 ✔
4251
        case climb_forts:
×
4252
        {
×
4253
            fr = forts_climbing(std::get<0>(op), p);
×
4254
            break;
×
4255
        }
4256
        case climb:
3 ✔
4257
        {
3 ✔
4258
            // TODO check for your_decks.size()==1
4259
            fr = hill_climbing(std::get<0>(op), std::get<1>(op), your_decks, p, requirement
3 ✔
4260
#ifndef NQUEST
4261
                               ,
4262
                               tuo::quest
4263
#endif
4264
            );
3 ✔
4265
            break;
3 ✔
4266
        }
4267
        case anneal:
1 ✔
4268
        {
1 ✔
4269
            // TODO check for your_decks.size()==1
4270
            fr = simulated_annealing(std::get<0>(op), std::get<1>(op), your_decks, p, requirement
1 ✔
4271
#ifndef NQUEST
4272
                                     ,
4273
                                     tuo::quest
4274
#endif
4275
            );
1 ✔
4276
            break;
1 ✔
4277
        }
4278
        case genetic:
1 ✔
4279
        {
1 ✔
4280
            fr = genetic_algorithm(std::get<0>(op), std::get<1>(op), your_decks, p, requirement
1 ✔
4281
#ifndef NQUEST
4282
                                   ,
4283
                                   tuo::quest
4284
#endif
4285
            );
1 ✔
4286
            break;
1 ✔
4287
        }
4288

4289
        case beam:
2 ✔
4290
        {
2 ✔
4291
            fr = beam_climb(std::get<0>(op), std::get<1>(op), your_decks, p, requirement
2 ✔
4292
#ifndef NQUEST
4293
                            ,
4294
                            tuo::quest
4295
#endif
4296
            );
2 ✔
4297
            break;
2 ✔
4298
        }
4299
        case reorder:
×
4300
        {
×
4301
            // TODO multi deck mode for reorder
4302
            your_deck->strategy = DeckStrategy::ordered;
×
4303
            use_owned_cards = true;
×
4304
            use_top_level_card = false;
×
4305
            use_top_level_commander = false;
×
4306
            use_owned_dominions = false;
×
4307
            if (min_deck_len == 1 && max_deck_len == 10)
×
4308
            {
4309
                min_deck_len = max_deck_len = your_deck->cards.size();
×
4310
            }
4311
            fund = 0;
×
4312
            debug_print = -1;
×
4313
            owned_cards.clear();
×
4314
            claim_cards({your_deck->commander});
×
4315
            claim_cards(your_deck->cards);
×
4316
            std::vector<Deck *> single_deck = {your_deck};
×
4317
            fr = hill_climbing(std::get<0>(op), std::get<1>(op), single_deck, p, requirement
×
4318
#ifndef NQUEST
4319
                               ,
4320
                               tuo::quest
4321
#endif
4322
            );
×
4323
            break;
×
4324
        }
×
4325
            // fr=nllptr no return
4326
        case debug:
×
4327
        {
×
4328
            ++debug_print;
×
4329
            debug_str.clear();
×
4330
            EvaluatedResults results{EvaluatedResults::first_type(enemy_decks.size()), 0};
×
4331
            results = p.evaluate(1, results);
×
4332
            print_results(results, p.factors);
×
4333
            --debug_print;
×
4334
            break;
×
4335
        }
×
4336
            // fr=nllptr no return
4337
        case debuguntil:
×
4338
        {
×
4339
            ++debug_print;
×
4340
            ++debug_cached;
×
4341
            while (true)
×
4342
            {
4343
                debug_str.clear();
×
4344
                EvaluatedResults results{EvaluatedResults::first_type(enemy_decks.size()), 0};
×
4345
                results = p.evaluate(1, results);
×
4346
                auto score = compute_score(results, p.factors);
×
4347
                if (score.points >= std::get<0>(op) && score.points <= std::get<1>(op))
×
4348
                {
4349
                    std::cout << debug_str << std::flush;
×
4350
                    print_results(results, p.factors);
×
4351
                    break;
×
4352
                }
4353
            }
×
4354
            --debug_cached;
×
4355
            --debug_print;
×
4356
            break;
×
4357
        }
4358
        }
4359
    }
4360
    write_db(prefix);
255 ✔
4361
    }
4362
    else {
4363
        std::cout << "No operation specified" << std::endl;
×
4364
    }
4365
    return fr;
170 ✔
4366
}
935 ✔
4367

4368
std::vector<const char *> strlist(std::vector<std::string> &input)
×
4369
{
4370
    std::vector<const char *> result;
×
4371

4372
    // remember the nullptr terminator
4373
    result.reserve(input.size() + 1);
×
4374

4375
    for (auto &i : input)
×
4376
        result.push_back(i.data());
×
4377
    result.push_back(nullptr);
×
4378
    return result;
×
4379
}
×
4380

4381
DeckResults start(int argc, const char **argv)
×
4382
{
4383
    std::vector<std::string> result_decks;
×
4384
    DeckResults drc;
×
4385
    bool first = true;
×
4386
    result_decks.push_back(argv[1]);
×
4387
    for (int j = 0; j < argc; ++j)
×
4388
    {
4389
        int add_j_inc = 0;
×
4390
        bool do_it = false;
×
4391
        std::stringstream param_file;
×
4392
        if (strcmp(argv[j], "boost-ml") == 0)
×
4393
        {
4394
            do_it = true;
×
4395
            add_j_inc = -1;
×
4396
            param_file << "noop" << std::endl
×
4397
                       << "only-ml" << std::endl
×
4398
                       << "deck @1@ no-ml" << std::endl;
×
4399
        }
4400
        if (strcmp(argv[j], "-p") == 0 || strcmp(argv[j], "params") == 0)
×
4401
        {
4402
            if (j + 1 < argc)
×
4403
            {
4404
                std::ifstream in_param_file(argv[j + 1]);
×
4405
                if (in_param_file.good())
×
4406
                {
4407
                    param_file << in_param_file.rdbuf();
×
4408
                    in_param_file.close();
×
4409
                    do_it = true;
4410
                }
4411
                else
4412
                {
4413
                    std::cout << "Error loading params file " << argv[j + 1] << std::endl;
×
4414
                }
4415
            }
×
4416
            else
4417
            {
4418
                std::cout << "-p/params needs a file as parameter" << std::endl;
×
4419
            }
4420
        }
4421
        if (do_it)
×
4422
        {
4423
            {
×
4424
                param_file.clear();
×
4425
                param_file.seekg(0, std::ios::beg);
×
4426
                // param_file to istream
4427
                std::cout << "Loading params file " << argv[j + 1] << std::endl;
×
4428
                std::string line, tmp, first_line = "";
×
4429
                std::vector<std::string> first_split, cur_split;
×
4430
                // first count parameters in file
4431
                while (param_file && !param_file.eof())
×
4432
                {
4433
                    std::getline(param_file, line);
×
4434
                    if (is_line_empty_or_commented(line))
×
4435
                        continue;
×
4436
                    for (int z = 0; z < argc - j - 1; ++z)
×
4437
                    {
4438
                        std::string rep("$" + std::to_string(z) + "$");
×
4439
                        if (line.find(rep) != std::string::npos && z > add_j_inc)
×
4440
                            add_j_inc = z;
×
4441
                    }
×
4442
                }
4443
                param_file.clear();
×
4444
                param_file.seekg(0, std::ios::beg);
×
4445
                while (param_file && !param_file.eof())
×
4446
                {
4447
                    std::getline(param_file, line);
×
4448
                    if (is_line_empty_or_commented(line))
×
4449
                        continue;
×
4450
                    // std::cout << line << std::endl;
4451
                    if (first_line == "")
×
4452
                    {
4453
                        first_line = line;
×
4454
                        std::istringstream ss(first_line);
×
4455
                        while (ss >> boost::io::quoted(tmp))
×
4456
                        {
4457
                            for (unsigned z = 0; z < result_decks.size(); ++z)
×
4458
                            {
4459
                                boost::replace_all(tmp, "@" + std::to_string(z) + "@", result_decks[z]);
×
4460
                            }
4461
                            for (int z = 0; z < argc - j - 1; ++z)
×
4462
                            {
4463
                                std::string rep("$" + std::to_string(z) + "$");
×
4464
                                boost::replace_all(tmp, rep, std::string(argv[j + 1 + z]));
×
4465
                            }
×
4466
                            first_split.push_back(tmp);
×
4467
                        }
4468
                    }
×
4469
                    else
4470
                    {
4471
                        cur_split = first_split;
×
4472
                        std::istringstream ss(line);
×
4473
                        while (ss >> boost::io::quoted(tmp))
×
4474
                        {
4475
                            for (unsigned z = 0; z < result_decks.size(); ++z)
×
4476
                            {
4477
                                boost::replace_all(tmp, "@" + std::to_string(z) + "@", result_decks[z]);
×
4478
                            }
4479
                            for (int z = 0; z < argc - j - 1; ++z)
×
4480
                            {
4481
                                std::string rep("$" + std::to_string(z) + "$");
×
4482
                                boost::replace_all(tmp, rep, std::string(argv[j + 1 + z]));
×
4483
                            }
×
4484
                            cur_split.push_back(tmp);
×
4485
                        }
4486
                        for (int i = 0; i < argc; ++i)
×
4487
                        {
4488
                            if (i < j)
×
4489
                                cur_split.insert(cur_split.begin() + i, std::string(argv[i]));
×
4490
                            if (i > j + 1 + add_j_inc)
×
4491
                                cur_split.push_back(std::string(argv[i]));
×
4492
                        }
4493
                        if (!first)
×
4494
                        {
4495
                            // replace passed deck with most recent deck
4496
                            cur_split.erase(cur_split.begin() + 1);
×
4497
                            cur_split.insert(cur_split.begin() + 1, result_decks[result_decks.size() - 1]);
×
4498
                        }
4499
                        first = false;
×
4500

4501
                        std::cout << std::endl
×
4502
                                  << "///////////////" << std::endl;
×
4503
                        // std::cout << result_decks[result_decks.size()-1] <<std::endl;
4504
                        int k = 0;
×
4505
                        for (auto &str : cur_split)
×
4506
                        {
4507
                            if (k > 0)
×
4508
                                std::cout << "\"";
×
4509
                            std::cout << str;
×
4510
                            if (k > 0)
×
4511
                                std::cout << "\"";
×
4512
                            std::cout << ' ';
×
4513
                            k++;
×
4514
                        }
4515
                        std::cout << std::endl;
×
4516
                        std::cout << "///////////////" << std::endl
×
4517
                                  << std::endl;
×
4518

4519
                        drc = start(cur_split.size(), strlist(cur_split).data());
×
4520

4521
                        // result to string
4522
                        std::stringstream oss;
×
4523
                        if (drc.first->commander)
×
4524
                            oss << drc.first->commander->m_name << ", ";
×
4525
                        if (drc.first->alpha_dominion)
×
4526
                            oss << drc.first->alpha_dominion->m_name << ", ";
×
4527
                        print_cards_inline(drc.first->cards, oss, drc.first);
×
4528
                        std::string decks(oss.str());
×
4529
                        std::replace(decks.begin(), decks.end(), '\n', ' ');
×
4530
                        result_decks.push_back(decks);
×
4531

4532
                        // print_cards_inline(drc.first->cards,std::cout);
4533
                    }
×
4534
                }
4535
                return drc;
×
4536
            }
×
4537
        }
4538
        else
4539
        {
4540
            // return run(argc,argv);
4541
        }
4542
    }
×
4543
    init();
×
4544
    auto rtrn = run(argc, argv);
×
4545
    return rtrn;
×
4546
}
×
4547

4548
#if !defined(TEST)
4549
int main(int argc, const char **argv)
4550
{
4551
#ifndef NTIMER
4552
    boost::timer::auto_cpu_timer t;
4553
#endif
4554
    if (argc == 2 && strcmp(argv[1], "-version") == 0)
4555
    {
4556
        std::cout << "Tyrant Unleashed Optimizer " << TYRANT_OPTIMIZER_VERSION << std::endl;
4557
        return 0;
4558
    }
4559
    if (argc < 2)
4560
    {
4561
        usage(argc, argv);
4562
        return 255;
4563
    }
4564
    start(argc, argv);
4565
    return 0;
4566
}
4567
#endif
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc