forked from DataBeaver/trimps-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathspire.cpp
1450 lines (1282 loc) · 36 KB
/
spire.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "spire.h"
#include <signal.h>
#include <chrono>
#include <functional>
#include <iomanip>
#include <iostream>
#include <regex>
#include "console.h"
#include "getopt.h"
#include "spirepool.h"
struct FancyCell
{
uint8_t bg_color[3];
uint8_t text_color;
std::string line1;
std::string line2;
};
using namespace std;
using namespace std::placeholders;
#if defined(_WIN32) && !defined(_POSIX_THREAD_SAFE_FUNCTIONS)
struct tm *localtime_r(const time_t *timep, struct tm *result)
{
if(!localtime_s(result, timep))
return result;
return 0;
}
#endif
int main(int argc, char **argv)
{
try
{
Spire spire(argc, argv);
return spire.main();
}
catch(const usage_error &e)
{
cout << e.what() << endl;
const char *help = e.help();
if(help[0])
cout << help << endl;
return 1;
}
catch(const exception &e)
{
cout << "An error occurred: " << e.what() << endl;
}
}
Spire *Spire::instance;
Spire::Spire(int argc, char **argv):
n_pools(10),
prune_interval(0),
next_prune(0),
prune_limit(3),
extinction_interval(0),
next_extinction(0),
isolation_period(10000),
cross_rate(500),
foreign_rate(500),
core_rate(1000),
heterogeneous(false),
n_workers(4),
loops_per_cycle(200),
cycle(1),
loops_per_second(0),
debug_layout(false),
update_mode(Layout::FAST),
numeric_format(false),
raw_values(false),
fancy_output(false),
show_pools(false),
network(0),
live(false),
athome(false),
connection(0),
athome_boredom(500000),
next_work(0),
intr_flag(false),
budget(0),
core_budget(0),
core_mutate(Core::ALL_MUTATIONS),
no_core_downgrade(false),
income(false),
towers(false),
score_func(damage_score)
{
instance = this;
unsigned pool_size = 100;
unsigned n_pools_seen = 0;
unsigned prune_interval_seen = 0;
unsigned prune_limit_seen = 0;
unsigned extinction_interval_seen = 0;
unsigned isolation_period_seen = 0;
unsigned foreign_rate_seen = 0;
unsigned floors = 0;
unsigned floors_seen = 0;
string upgrades;
string core;
string layout_str;
string preset;
bool online = false;
bool exact = false;
std::string budget_str;
std::string core_budget_str;
unsigned keep_core_mods = 0;
std::string tower_type;
unsigned towers_seen = 0;
GetOpt getopt;
getopt.add_option('b', "budget", budget_str, GetOpt::REQUIRED_ARG).set_help("Maximum amount of runestones to spend", "NUM");
getopt.add_option('f', "floors", floors, GetOpt::REQUIRED_ARG).set_help("Number of floors in the spire", "NUM").bind_seen_count(floors_seen);
getopt.add_option('u', "upgrades", upgrades, GetOpt::REQUIRED_ARG).set_help("Set all trap upgrade levels", "NNNN");
getopt.add_option('c', "core", core, GetOpt::REQUIRED_ARG).set_help("Set spire core description", "DESC");
getopt.add_option('d', "core-budget", core_budget_str, GetOpt::REQUIRED_ARG).set_help("Maximum amount of spirestones to spend on core", "NUM");
getopt.add_option('k', "keep-core-mods", keep_core_mods, GetOpt::NO_ARG).set_help("Do not swap core mods");
getopt.add_option('n', "numeric-format", numeric_format, GetOpt::NO_ARG).set_help("Output layouts in numeric format");
getopt.add_option('i', "income", income, GetOpt::NO_ARG).set_help("Optimize runestones per second");
getopt.add_option("towers", tower_type, GetOpt::OPTIONAL_ARG).set_help("Try to use as many towers as possible").bind_seen_count(towers_seen);
getopt.add_option("online", online, GetOpt::NO_ARG).set_help("Use the online layout database");
getopt.add_option("live", live, GetOpt::NO_ARG).set_help("Perform a live query to the database");
#ifdef WITH_128BIT
getopt.add_option("athome", athome, GetOpt::NO_ARG).set_help("Work on random layouts provided by the database");
getopt.add_option("boredom", athome_boredom, GetOpt::REQUIRED_ARG).set_help("Get new work after this many cycles of no improvement", "NUM");
#endif
getopt.add_option('t', "preset", preset, GetOpt::REQUIRED_ARG).set_help("Select a preset to base settings on", "NAME");
getopt.add_option("fancy", fancy_output, GetOpt::NO_ARG).set_help("Produce fancy output");
getopt.add_option('e', "exact", exact, GetOpt::NO_ARG).set_help("Use exact calculations, at cost of performance");
getopt.add_option('w', "workers", n_workers, GetOpt::REQUIRED_ARG).set_help("Number of threads to use", "NUM");
getopt.add_option('l', "loops", loops_per_cycle, GetOpt::REQUIRED_ARG).set_help("Number of loops per cycle", "NUM");
getopt.add_option('p', "pools", n_pools, GetOpt::REQUIRED_ARG).set_help("Number of population pools", "NUM").bind_seen_count(n_pools_seen);
getopt.add_option('s', "pool-size", pool_size, GetOpt::REQUIRED_ARG).set_help("Size of each population pool", "NUM");
getopt.add_option("prune-interval", prune_interval, GetOpt::REQUIRED_ARG).set_help("Interval for pruning pools, in cycles", "NUM").bind_seen_count(prune_interval_seen);
getopt.add_option("prune-limit", prune_limit, GetOpt::REQUIRED_ARG).set_help("Minimum number of pools to keep", "NUM").bind_seen_count(prune_limit_seen);
getopt.add_option("extinction-interval", extinction_interval, GetOpt::REQUIRED_ARG).set_help("Interval between extinctions, in cycles", "NUM").bind_seen_count(extinction_interval_seen);
getopt.add_option("isolation-period", isolation_period, GetOpt::REQUIRED_ARG).set_help("Isolation period after extinction, in cycles", "NUM").bind_seen_count(isolation_period_seen);
getopt.add_option("heterogeneous", heterogeneous, GetOpt::NO_ARG).set_help("Use heterogeneous pool configurations");
getopt.add_option('r', "cross-rate", cross_rate, GetOpt::REQUIRED_ARG).set_help("Probability of crossing two layouts (out of 1000)", "NUM");
getopt.add_option('o', "foreign-rate", foreign_rate, GetOpt::REQUIRED_ARG).set_help("Probability of crossing from another pool (out of 1000)", "NUM").bind_seen_count(foreign_rate_seen);
getopt.add_option("core-rate", core_rate, GetOpt::REQUIRED_ARG).set_help("Probability of mutating the core (out of 1000)", "NUM");
getopt.add_option('g', "debug-layout", debug_layout, GetOpt::NO_ARG).set_help("Print detailed information about the layout");
getopt.add_option("show-pools", show_pools, GetOpt::NO_ARG).set_help("Show population pool contents while running");
getopt.add_option("raw-values", raw_values, GetOpt::NO_ARG).set_help("Display raw numeric values");
getopt.add_argument("layout", layout_str, GetOpt::OPTIONAL_ARG).set_help("Layout to start with");
getopt(argc, argv);
if(floors_seen && floors<1)
throw usage_error("Invalid number of floors");
if(n_workers<1)
throw usage_error("Invalid number of worker threads");
if(loops_per_cycle<1)
throw usage_error("Invalid number of loops per cycle");
if(pool_size<1)
throw usage_error("Invalid pool size");
if(n_pools<1)
throw usage_error("Invalid number of pools");
if(prune_limit<1)
throw usage_error("Invalid prune limit");
if(athome)
{
prune_interval = 0;
heterogeneous = false;
online = true;
live = false;
towers_seen = false;
core_mutate = Core::VALUES_ONLY;
if(!extinction_interval_seen)
extinction_interval = 25000;
}
else if(preset=="single")
{
if(!n_pools_seen)
n_pools = 1;
}
else if(preset=="diverse")
{
if(!n_pools_seen)
n_pools = 50;
if(!prune_interval_seen)
prune_interval = 50000;
if(!prune_limit_seen)
prune_limit = 10;
if(!extinction_interval_seen)
extinction_interval = 25000;
}
else if(preset=="advanced")
{
if(!prune_interval_seen)
prune_interval = 100000;
heterogeneous = true;
if(!foreign_rate_seen)
foreign_rate = 1000;
}
else if(!preset.empty() && preset!="basic")
throw usage_error("Invalid preset");
towers = towers_seen;
if(towers_seen)
{
if(tower_type=="SC" || tower_type=="CS")
tower_type = "-K";
else if(tower_type=="SK" || tower_type=="KS")
tower_type = "-C";
else if(tower_type=="CK" || tower_type=="KC")
tower_type = "-S";
bool exclude = false;
if(!tower_type.empty() && tower_type[0]=='-')
{
exclude = true;
tower_type.erase(0, 1);
}
char tower = 0;
if(tower_type=="S" || tower_type=="strength")
tower = 'S';
else if(tower_type=="C" || tower_type=="condenser")
tower = 'C';
else if(tower_type=="K" || tower_type=="knowledge")
tower = 'K';
else if(!tower_type.empty())
throw usage_error("Invalid tower type");
if(income)
score_func = get_towers_score_func<income_score>(tower, exclude);
else
score_func = get_towers_score_func<damage_score>(tower, exclude);
}
else if(income)
score_func = income_score;
if(income)
update_mode = Layout::FULL;
else if(exact)
update_mode = Layout::EXACT_DAMAGE;
if(keep_core_mods)
{
core_mutate = Core::VALUES_ONLY;
no_core_downgrade = (keep_core_mods>=2);
}
if(!n_pools_seen && heterogeneous)
n_pools = 21;
if(n_pools==1)
{
foreign_rate = 0;
prune_interval = 0;
}
if(n_pools<=prune_limit)
prune_interval = 0;
if(prune_interval)
next_prune = prune_interval;
if(extinction_interval)
{
next_extinction = extinction_interval;
if(!isolation_period_seen)
isolation_period = 3*extinction_interval;
}
if(!athome)
init_start_layout(parse_layout(layout_str, upgrades, core, floors));
init_pools(pool_size);
if(!budget_str.empty())
{
try
{
budget = parse_value<NumberIO>(budget_str).value;
}
catch(const exception &e)
{
throw usage_error(format("Invalid argument for --budget (%s)", e.what()));
}
if(budget_str[0]=='+')
budget += start_layout.get_cost();
else if(budget<start_layout.get_cost())
throw usage_error("Runestone budget is too low for the layout");
}
else if(!start_layout.get_traps().empty())
budget = start_layout.get_cost();
else
budget = 1000000;
if(!core_budget_str.empty())
{
try
{
core_budget = parse_value<NumberIO>(core_budget_str).value;
}
catch(const exception &e)
{
throw usage_error(format("Invalid argument for --core-budget (%s)", e.what()));
}
if(core_budget_str[0]=='+')
core_budget += start_layout.get_core().cost;
else if(core_budget<start_layout.get_core().cost)
throw usage_error("Spirestone budget is too low for the core");
}
if(!core_budget)
core_rate = 0;
if(online || live)
init_network(false);
}
void Spire::parse_numeric_layout(const string& layout, ParsedLayout &parsed)
{
auto first_plus = layout.find('+');
auto second_plus = first_plus+5;
parsed.traps = layout.substr(0, first_plus);
for(char &c: parsed.traps)
{
if(c<'0' || '7'<c)
throw usage_error(format("Invalid trap '%c'", c));
c = Layout::traps[c-'0'];
}
parsed.upgrades = layout.substr(first_plus+1, 4);
parsed.floors = parse_value<unsigned>(layout.substr(second_plus+1));
}
void Spire::parse_alpha_layout(const string &layout_in, ParsedLayout &parsed)
{
parsed.upgrades = layout_in.substr(0, 4);
parsed.traps = remove_spaces(layout_in.substr(5));
parsed.floors = parsed.traps.length()/5;
}
Spire::ParsedLayout Spire::parse_layout(const string &layout_in, const string &upgrades_in, const string& core_in, unsigned floors)
{
ParsedLayout parsed;
/* Checks for a layout string in Swaq format:
swaq ::= [traps] '+' [upgrades] '+' [floors]
traps ::= r'(\d{5})+'
upgrades ::= r'\d{4}'
floors ::= r'\d' */
static regex numeric_regex("(\\d{5})+\\+\\d{4}\\+\\d{1,2}");
/* Checks for a layout string in the optimizer format:
tower ::= [upgrades] ' ' [traps] | [upgrades] [traps]
upgrades ::= r'\d{4}'
traps ::= [trap_row] | [trap_row] ' ' [trap_row] | [trap_row] [trap_row]
trap_row := r'[FZPLSCK_]{5}' */
static regex alpha_regex("\\d{4} ?([FZPLSCK_]{5} ?)*[FZPLSCK_]{5}+");
if(regex_match(layout_in, numeric_regex))
parse_numeric_layout(layout_in, parsed);
else if(regex_match(layout_in, alpha_regex))
parse_alpha_layout(layout_in, parsed);
else if(!layout_in.empty())
throw usage_error("Unknown layout format");
else
parsed.floors = 0;
if(!upgrades_in.empty())
parsed.upgrades = upgrades_in;
if(!core_in.empty())
parsed.core = core_in;
if(floors!=0)
parsed.floors = floors;
return parsed;
}
void Spire::init_start_layout(const ParsedLayout &layout)
{
if(!layout.upgrades.empty())
{
try
{
start_layout.set_upgrades(layout.upgrades);
}
catch(const exception &)
{
throw usage_error("Upgrades string must consist of four numbers");
}
}
const TrapUpgrades &start_upgrades = start_layout.get_upgrades();
if(start_upgrades.fire>8)
throw usage_error("Invalid fire trap upgrade level");
if(start_upgrades.frost>8)
throw usage_error("Invalid frost trap upgrade level");
if(start_upgrades.poison>9)
throw usage_error("Invalid poison trap upgrade level");
if(start_upgrades.lightning>6)
throw usage_error("Invalid lightning trap upgrade level");
if(!layout.core.empty())
{
try
{
Core core = layout.core;
core.update();
start_layout.set_core(core);
}
catch(const invalid_argument &e)
{
throw usage_error(e.what());
}
}
if(!layout.traps.empty())
{
string clean_data;
clean_data.reserve(layout.traps.size());
for(char c: layout.traps)
{
if(c>='0' && c<='7')
clean_data += Layout::traps[c-'0'];
else if(c!=' ')
{
unsigned i;
for(i=7; (i>0 && Layout::traps[i]!=c); --i) ;
clean_data += Layout::traps[i];
}
}
start_layout.set_traps(clean_data, layout.floors);
start_layout.update(Layout::FULL);
}
else
{
start_layout.set_traps(string(), (layout.floors ? layout.floors : 7));
start_layout.update(Layout::COST_ONLY);
}
}
void Spire::init_pools(unsigned pool_size)
{
pools.reserve(n_pools);
for(unsigned i=0; i<n_pools; ++i)
pools.push_back(new Pool(pool_size, score_func));
unsigned floors = start_layout.get_traps().size()/5;
uint8_t downgrade[4] = { };
for(unsigned i=0; i<pools.size(); ++i)
{
if(i==0 && start_layout.get_damage())
{
pools[i]->add_layout(start_layout);
continue;
}
TrapUpgrades pool_upgrades = start_layout.get_upgrades();
unsigned reduce = 0;
for(unsigned j=0; j<sizeof(downgrade); ++j)
{
if(downgrade[j]==1 && pool_upgrades.fire>1)
--pool_upgrades.fire;
else if(downgrade[j]==2 && pool_upgrades.frost>1)
--pool_upgrades.frost;
else if(downgrade[j]==3 && pool_upgrades.poison>1)
--pool_upgrades.poison;
else if(downgrade[j]==4 && pool_upgrades.lightning>1)
--pool_upgrades.lightning;
else if(downgrade[j]==5 && reduce+1<floors)
++reduce;
}
Layout empty;
empty.set_upgrades(pool_upgrades);
empty.set_core(start_layout.get_core());
empty.set_traps(string(), floors-reduce);
pools[i]->add_layout(empty);
if(heterogeneous)
{
++downgrade[0];
for(unsigned j=1; (j<sizeof(downgrade) && downgrade[j-1]>5); ++j)
{
++downgrade[j];
for(unsigned k=0; k<j; ++k)
downgrade[k] = downgrade[j];
}
}
}
}
void Spire::init_network(bool reconnect)
{
if(!network)
network = new Network;
try
{
connection = network->connect("spiredb.tdb.fi", 8676, bind(&Spire::receive, this, _1, _2));
if(reconnect)
{
if(fancy_output)
{
console.set_cursor_position(58, 16+(core_budget!=0));
console << "Online ";
}
else
console << "Reconnected to online build database" << endl;
}
}
catch(const exception &e)
{
if(!fancy_output && !reconnect)
{
console << "Can't connect to online build database:" << endl;
console << e.what() << endl;
console << "Connection will be reattempted automatically" << endl;
}
reconnect_timeout = chrono::steady_clock::now()+chrono::seconds(30);
}
}
Spire::~Spire()
{
for(auto p: pools)
delete p;
}
int Spire::main()
{
if(debug_layout)
{
start_layout.debug(start_layout.get_damage());
console << "Threat: " << start_layout.get_threat() << endl;
console << "Runestones: " << start_layout.get_runestones_per_second() << "/s" << endl;
console << " " << start_layout.get_runestones_per_enemy() << "/enemy" << endl;
return 0;
}
if(show_pools || fancy_output)
{
console.clear_screen();
console.set_cursor_position(0, 0);
}
best_layout = pools.front()->get_best_layout();
if(best_layout.get_damage() && !show_pools)
report(best_layout, "Initial layout");
if(connection)
{
if(!athome && !fancy_output)
console << "Querying online database for best known layout" << endl;
if(athome)
;
else if(query_network())
{
if(!show_pools)
report(best_layout, "Layout from database");
}
else
{
if(!fancy_output)
console << "Database returned no better layout" << endl;
submit_best();
}
}
signal(SIGINT, sighandler);
Random random;
for(unsigned i=0; i<n_workers; ++i)
workers.push_back(new Worker(*this, random(), athome));
chrono::steady_clock::time_point period_start_time = chrono::steady_clock::now();
unsigned period_start_cycle = cycle;
bool leave_loop = false;
while(!leave_loop)
{
this_thread::sleep_for(chrono::milliseconds(500));
chrono::steady_clock::time_point current_time = chrono::steady_clock::now();
unsigned period_end_cycle = cycle;
loops_per_second = loops_per_cycle*(period_end_cycle-period_start_cycle)/chrono::duration<float>(current_time-period_start_time).count();
period_start_time = current_time;
period_start_cycle = period_end_cycle;
if(intr_flag)
{
for(auto w: workers)
w->interrupt();
for(auto w: workers)
w->join();
leave_loop = true;
}
check_reconnect(current_time);
check_athome_work();
lock_guard<mutex> lock(best_mutex);
bool new_best_found = check_results();
update_output(new_best_found);
}
for(auto w: workers)
delete w;
if(show_pools || fancy_output)
{
console.set_cursor_position(0, console.get_height()-1);
cout.flush();
}
return 0;
}
bool Spire::query_network()
{
if(!connection)
return false;
unsigned floors = best_layout.get_traps().size()/5;
string query = format("query upg=%s f=%s rs=%s", best_layout.get_upgrades().str(), floors, budget);
if(best_layout.get_core().tier>=0)
query += format(" core=%s", best_layout.get_core().str(true));
if(core_budget>0)
query += format(" ss=%s", core_budget);
if(income)
query += " income";
if(towers)
query += " towers";
if(live)
query += " live";
string reply = network->communicate(connection, query);
if(reply.empty())
return false;
vector<string> parts = split(reply);
if(parts[0]=="ok")
{
Layout layout;
layout.set_upgrades(best_layout.get_upgrades());
layout.set_core(best_layout.get_core());
parts.erase(parts.begin());
process_network_reply(parts, layout);
if(score_func(layout)>score_func(best_layout))
{
best_layout = layout;
pools.front()->add_layout(best_layout);
return true;
}
}
return false;
}
void Spire::process_network_reply(const vector<string> &args, Layout &layout)
{
unsigned floors = layout.get_traps().size()/5;
Core received_core;
for(const auto &arg: args)
{
if(!arg.compare(0, 2, "t="))
layout.set_traps(arg.substr(2), floors);
else if(!arg.compare(0, 5, "core="))
{
received_core = arg.substr(5);
received_core.update();
}
else if(athome)
{
if(!arg.compare(0, 4, "upg="))
layout.set_upgrades(arg.substr(4));
else if(!arg.compare(0, 3, "rs="))
budget = parse_value<NumberIO>(arg.substr(3));
else if(!arg.compare(0, 3, "ss="))
core_budget = parse_value<NumberIO>(arg.substr(3));
else if(arg=="income")
income = true;
else if(arg=="damage")
income = false;
else if(arg=="towers")
towers = true;
}
}
layout.update(Layout::FULL);
if(received_core.tier>=0 && (athome || check_better_core(layout, received_core)))
{
layout.set_core(received_core);
layout.update(Layout::FULL);
}
}
bool Spire::check_better_core(const Layout &layout, const Core &core)
{
if(!validate_core(core))
return false;
Layout with_core = layout;
with_core.set_core(core);
with_core.update(Layout::FULL);
return score_func(with_core)>score_func(layout);
}
bool Spire::validate_core(const Core &core)
{
if(core.cost>core_budget)
return false;
if(core_mutate==Core::ALL_MUTATIONS)
return true;
const Core &start_core = start_layout.get_core();
if(no_core_downgrade)
{
for(unsigned j=0; j<Core::N_MODS; ++j)
if(core.get_mod(j)<start_core.get_mod(j))
return false;
}
else
{
for(unsigned j=0; j<Core::N_MODS; ++j)
if((core.get_mod(j)!=0) != (start_core.get_mod(j)!=0))
return false;
}
return true;
}
void Spire::check_reconnect(const chrono::steady_clock::time_point ¤t_time)
{
if(!network || connection || current_time<reconnect_timeout)
return;
init_network(true);
if(connection)
{
lock_guard<mutex> lock(best_mutex);
if(athome)
;
else if(query_network())
{
if(!show_pools)
report(best_layout, "New best layout from database");
}
else
submit_best();
}
}
void Spire::check_athome_work()
{
unsigned current_cycle = cycle.load();
if(!athome || !connection || current_cycle<next_work)
return;
network->send_message(connection, "getwork");
next_work = current_cycle+athome_boredom;
}
bool Spire::check_results()
{
bool new_best = false;
for(auto *p: pools)
{
if(p->get_best_layout(best_layout))
new_best = true;
if(heterogeneous)
break;
}
if(new_best)
{
best_layout.update(Layout::FULL);
next_work = best_layout.get_cycle()+athome_boredom;
submit_best();
}
if(next_prune && cycle>=next_prune)
prune_pools();
if(next_extinction && cycle>=next_extinction)
extinct_pools(score_func(best_layout));
return new_best;
}
void Spire::submit_best()
{
if(!network || !score_func(best_layout))
return;
string submit = format("submit upg=%s t=%s", best_layout.get_upgrades().str(), best_layout.get_traps());
if(best_layout.get_core().tier>=0)
submit += format(" core=%s", best_layout.get_core().str(true));
network->send_message(connection, submit);
}
void Spire::update_output(bool new_best_found)
{
if(show_pools)
{
console.update_size();
console.set_cursor_position(0, 0);
unsigned n_print = (console.get_height()-2)/n_pools-1;
for(unsigned i=0; i<n_pools; ++i)
{
unsigned count = n_print;
pools[i]->visit_layouts(bind(&Spire::print, this, _1, ref(count)));
if(n_print>1)
{
for(++count; count>0; --count)
{
console.clear_current_line();
console << endl;
}
}
}
console << loops_per_second << " loops/sec" << endl_clear;
}
else
{
if(new_best_found)
report(best_layout, "New best layout found");
else if(fancy_output)
{
unsigned line = 14+(core_budget!=0);
console.set_cursor_position(69, line++);
console << cycle;
console.set_cursor_position(69, line++);
console << NumberIO(loops_per_second) << clear_to_end;
cout.flush();
}
}
}
unsigned Spire::get_next_cycle()
{
return cycle.fetch_add(1U, memory_order_relaxed);
}
void Spire::prune_pools()
{
if(n_pools<=1)
return;
pause_workers();
lock_guard<mutex> lock(pools_mutex);
unsigned lowest = 0;
if(heterogeneous)
++lowest;
Number score = pools[lowest]->get_best_score();
for(unsigned i=lowest+1; i<n_pools; ++i)
{
Number s = pools[i]->get_best_score();
if(s<score)
{
lowest = i;
score = s;
}
}
if(lowest+1<n_pools)
swap(pools[lowest], pools[n_pools-1]);
--n_pools;
delete pools.back();
pools.pop_back();
if(n_pools>prune_limit)
next_prune += prune_interval;
else
{
if(n_pools==1)
foreign_rate = 0;
next_prune = 0;
}
resume_workers();
}
void Spire::extinct_pools(Number score_limit)
{
if(n_pools<=1)
return;
pause_workers();
lock_guard<mutex> lock(pools_mutex);
Pool *pool = 0;
unsigned index = cycle.load();
for(unsigned i=0; (!pool && i<100); ++i)
{
Pool *p = pools[(index*(i+1)+i*i)%n_pools];
if(p->get_best_score()<score_limit)
pool = p;
}
if(pool)
{
Layout pool_best = pool->get_best_layout();
Layout empty;
empty.set_upgrades(pool_best.get_upgrades());
empty.set_core(pool_best.get_core());
empty.set_traps(string(), pool_best.get_traps().size()/5);
pool->reset(0);
pool->add_layout(empty);
pool->set_isolated_until(cycle.load()+isolation_period);
}
next_extinction += extinction_interval;
resume_workers();
}
void Spire::receive(Network::ConnectionTag, const string &message)
{
if(message.empty())
{
if(fancy_output)
{
console.set_cursor_position(58, 17);
console << "Disconnected";
}
else
console << "Connection to online database lost" << endl;
reconnect_timeout = chrono::steady_clock::now()+chrono::seconds(30);
connection = 0;
return;
}
vector<string> parts = split(message);
string cmd = parts.front();
parts.erase(parts.begin());
if(cmd=="push")
{
Layout layout;
{
lock_guard<mutex> lock_best(best_mutex);
layout.set_core(best_layout.get_core());
}
process_network_reply(parts, layout);
lock_guard<mutex> lock_best(best_mutex);
if(score_func(layout)>score_func(best_layout))
{
best_layout = layout;
report(best_layout, "New best layout from database");
lock_guard<mutex> lock_pools(pools_mutex);
pools.front()->add_layout(layout);
}
}
else if(cmd=="work")
{
budget = 0;
core_budget = 0;
income = false;
towers = false;
Layout layout;
process_network_reply(parts, layout);
pause_workers();
Layout empty;
empty.set_upgrades(layout.get_upgrades());
empty.set_core(layout.get_core());
empty.set_traps(string(), layout.get_traps().size()/5);
update_mode = (income ? Layout::FULL : Layout::FAST);
if(towers)
score_func = (income ? &towers_score<income_score, 0x40404> : &towers_score<damage_score, 0x40404>);
else
score_func = (income ? &income_score : &damage_score);
{
lock_guard<mutex> lock(pools_mutex);
for(auto i=pools.begin(); i!=pools.end(); ++i)
{
(*i)->reset(score_func);
(*i)->add_layout(i==pools.begin() ? layout : empty);
}
}
{
lock_guard<mutex> lock(best_mutex);
best_layout = layout;
}
budget = max(budget, layout.get_cost());
resume_workers();