-
-
Notifications
You must be signed in to change notification settings - Fork 988
/
attack_prediction.cpp
2805 lines (2437 loc) · 83.9 KB
/
attack_prediction.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
/*
Copyright (C) 2006 - 2017 by Rusty Russell <rusty@rustcorp.com.au>
Part of the Battle for Wesnoth Project http://www.wesnoth.org/
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY.
See the COPYING file for more details.
Full algorithm by Yogin. Original typing and optimization by Rusty.
Monte Carlo simulation mode implemented by Jyrki Vesterinen.
This code has lots of debugging. It is there for a reason:
this code is kinda tricky. Do not remove it.
*/
/**
* @file
* Simulate combat to calculate attacks.
* This can be compiled as a stand-alone program to either verify
* correctness or to benchmark performance.
*
* Compile with -O3 -DBENCHMARK for speed testing, and with -DCHECK for
* testing correctness (redirect the output to a file, then compile
* utils/wesnoth-attack-sim.c and run that with the arguments
* --check \<file name\>).
* For either option, use -DHUMAN_READABLE if you want to see the results
* from each combat displayed in a prettier format (but no longer suitable
* for wesnoth-attack-sim.c).
*/
#include "attack_prediction.hpp"
#include "actions/attack.hpp"
#include "game_config.hpp"
#include "log.hpp"
#include "preferences/general.hpp"
#include "random.hpp"
#include "serialization/string_utils.hpp"
#include "utils/general.hpp"
#include <array>
#include <cfloat>
#include <cmath>
#include <iostream>
#include <memory>
#include <numeric>
#include <sstream>
#if defined(BENCHMARK) || defined(CHECK)
#include <chrono>
#include <cstdio>
#include <cstdlib>
#endif
#ifdef ATTACK_PREDICTION_DEBUG
#define debug(x) printf x
#else
#define debug(x)
#endif
#ifdef ATTACK_PREDICTION_DEBUG
namespace
{
/** Prints the attack statistics of a unit to cout. */
void dump(const battle_context_unit_stats& stats)
{
std::ostringstream ss;
ss << "==================================";
<< std::boolalpha
<< "\n" << "is_attacker: " << stats.is_attacker
<< "\n" << "is_poisoned: " << stats.is_poisoned
<< "\n" << "is_slowed: " << stats.is_slowed
<< "\n" << "slows: " << stats.slows
<< "\n" << "drains: " << stats.drains
<< "\n" << "petrifies: " << stats.petrifies
<< "\n" << "poisons: " << stats.poisons
<< "\n" << "backstab_pos: " << stats.backstab_pos
<< "\n" << "swarm: " << stats.swarm
<< "\n" << "firststrike: " << stats.firststrike
<< std::noboolalpha
<< "\n" << "rounds: " << stats.rounds
<< "\n\n"
<< "\n" << "hp: " << stats.hp
<< "\n" << "max_hp: " << stats.max_hp
<< "\n" << "chance_to_hit: " << stats.chance_to_hit
<< "\n" << "damage: " << stats.damage
<< "\n" << "slow_damage: " << stats.slow_damage
<< "\n" << "drain_percent: " << stats.drain_percent
<< "\n" << "drain_constant: " << stats.drain_constant
<< "\n" << "num_blows: " << stats.num_blows
<< "\n" << "swarm_min: " << stats.swarm_min
<< "\n" << "swarm_max: " << stats.swarm_max
<< "\n\n";
std::cout << ss.rdbuf() << std::endl;
}
}
#endif
namespace
{
using summary_t = std::array<std::vector<double>, 2>;
/**
* A struct to describe one possible combat scenario.
* (Needed when the number of attacks can vary due to swarm.)
*/
struct combat_slice
{
// The hit point range this slice covers.
unsigned begin_hp; // included in the range.
unsigned end_hp; // excluded from the range.
// The probability of this slice.
double prob;
// The number of strikes applicable with this slice.
unsigned strikes;
combat_slice(
const summary_t& src_summary, unsigned begin, unsigned end, unsigned num_strikes);
combat_slice(const summary_t& src_summary, unsigned num_strikes);
};
/**
* Creates a slice from a summary, and associates a number of strikes.
*/
combat_slice::combat_slice(
const summary_t& src_summary, unsigned begin, unsigned end, unsigned num_strikes)
: begin_hp(begin)
, end_hp(end)
, prob(0.0)
, strikes(num_strikes)
{
if(src_summary[0].empty()) {
// No summary; this should be the only slice.
prob = 1.0;
return;
}
// Avoid accessing beyond the end of the vectors.
if(end > src_summary[0].size()) {
end = src_summary[0].size();
}
// Sum the probabilities in the slice.
for(unsigned i = begin; i < end; ++i) {
prob += src_summary[0][i];
}
if(!src_summary[1].empty()) {
for(unsigned i = begin; i < end; ++i) {
prob += src_summary[1][i];
}
}
}
/**
* Creates a slice from the summaries, and associates a number of strikes.
* This version of the constructor creates a slice consisting of everything.
*/
combat_slice::combat_slice(const summary_t& src_summary, unsigned num_strikes)
: begin_hp(0)
, end_hp(src_summary[0].size())
, prob(1.0)
, strikes(num_strikes)
{
}
/**
* Returns the number of hit points greater than cur_hp, and at most
* stats.max_hp+1, at which the unit would get another attack because
* of swarm.
* Helper function for split_summary().
*/
unsigned hp_for_next_attack(unsigned cur_hp, const battle_context_unit_stats& stats)
{
unsigned old_strikes = stats.calc_blows(cur_hp);
// A formula would have to deal with rounding issues; instead
// loop until we find more strikes.
while(++cur_hp <= stats.max_hp) {
if(stats.calc_blows(cur_hp) != old_strikes) {
break;
}
}
return cur_hp;
}
/**
* Split the combat by number of attacks per combatant (for swarm).
* This also clears the current summaries.
*/
std::vector<combat_slice> split_summary(
const battle_context_unit_stats& unit_stats, summary_t& summary)
{
std::vector<combat_slice> result;
if(unit_stats.swarm_min == unit_stats.swarm_max || summary[0].empty()) {
// We use the same number of blows for all possibilities.
result.emplace_back(summary, unit_stats.num_blows);
return result;
}
debug(("Slicing:\n"));
// Loop through our slices.
unsigned cur_end = 0;
do {
// Advance to the next slice.
const unsigned cur_begin = cur_end;
cur_end = hp_for_next_attack(cur_begin, unit_stats);
// Add this slice.
combat_slice slice(summary, cur_begin, cur_end, unit_stats.calc_blows(cur_begin));
if(slice.prob != 0.0) {
result.push_back(slice);
debug(("\t%2u-%2u hp; strikes: %u; probability: %6.2f\n", cur_begin, cur_end, slice.strikes,
slice.prob * 100.0));
}
} while(cur_end <= unit_stats.max_hp);
return result;
}
/**
* A matrix of A's hitpoints vs B's hitpoints vs. their slowed states.
* This class is concerned only with the matrix implementation and
* implements functionality for shifting and retrieving probabilities
* (i.e. low-level stuff).
*/
class prob_matrix
{
// Since this gets used very often (especially by the AI), it has
// been optimized for speed as a sparse matrix.
public:
prob_matrix(unsigned int a_max,
unsigned int b_max,
bool need_a_slowed,
bool need_b_slowed,
unsigned int a_cur,
unsigned int b_cur,
const summary_t& a_initial,
const summary_t& b_initial);
// Shift columns on this plane (b taking damage).
void shift_cols(unsigned dst, unsigned src, unsigned damage, double prob, int drain_constant, int drain_percent);
// Shift rows on this plane (a taking damage).
void shift_rows(unsigned dst, unsigned src, unsigned damage, double prob, int drain_constant, int drain_percent);
/// Move a column (adding it to the destination).
void move_column(unsigned d_plane, unsigned s_plane, unsigned d_col, unsigned s_col);
/// Move a row (adding it to the destination).
void move_row(unsigned d_plane, unsigned s_plane, unsigned d_row, unsigned s_row);
// Move values within a row (or column) to a specified column (or row).
void merge_col(unsigned d_plane, unsigned s_plane, unsigned col, unsigned d_row);
void merge_cols(unsigned d_plane, unsigned s_plane, unsigned d_row);
void merge_row(unsigned d_plane, unsigned s_plane, unsigned row, unsigned d_col);
void merge_rows(unsigned d_plane, unsigned s_plane, unsigned d_col);
// Set all values to zero and clear the lists of used columns/rows.
void clear();
// Record the result of a single Monte Carlo simulation iteration.
void record_monte_carlo_result(unsigned int a_hp, unsigned int b_hp, bool a_slowed, bool b_slowed);
// Returns the index of the plane with the given slow statuses.
static unsigned int plane_index(bool a_slowed, bool b_slowed)
{
return (a_slowed ? 1 : 0) + (b_slowed ? 2 : 0);
}
/// What is the chance that an indicated combatant (one of them) is at zero?
double prob_of_zero(bool check_a, bool check_b) const;
/// Sums the values in the specified row.
double row_sum(unsigned plane, unsigned row) const;
/// Sums the values in the specified column.
double col_sum(unsigned plane, unsigned column) const;
/// Sums the values in the specified plane.
void sum(unsigned plane, std::vector<double>& row_sums, std::vector<double>& col_sums) const;
/// Returns true if the specified plane might have data in it.
bool plane_used(unsigned p) const
{
return p < NUM_PLANES && plane_[p] != nullptr;
}
unsigned int num_rows() const
{
return rows_;
}
unsigned int num_cols() const
{
return cols_;
}
// Debugging tool.
void dump() const;
// We need four matrices, or "planes", reflecting the possible
// "slowed" states (neither slowed, A slowed, B slowed, both slowed).
enum {
NEITHER_SLOWED,
A_SLOWED,
B_SLOWED,
BOTH_SLOWED,
NUM_PLANES // Symbolic constant for the number of planes.
};
private:
// This gives me 10% speed improvement over std::vector<> (g++4.0.3 x86)
std::unique_ptr<double[]> new_plane() const;
void initialize_plane(unsigned plane,
unsigned a_cur,
unsigned b_cur,
const std::vector<double>& a_initial,
const std::vector<double>& b_initial);
void initialize_row(
unsigned plane, unsigned row, double row_prob, unsigned b_cur, const std::vector<double>& b_initial);
double& val(unsigned plane, unsigned row, unsigned col);
const double& val(unsigned plane, unsigned row, unsigned col) const;
/// Transfers a portion (value * prob) of one value in the matrix to another.
void xfer(unsigned dst_plane,
unsigned src_plane,
unsigned row_dst,
unsigned col_dst,
unsigned row_src,
unsigned col_src,
double prob);
/// Transfers one value in the matrix to another.
void xfer(unsigned dst_plane,
unsigned src_plane,
unsigned row_dst,
unsigned col_dst,
unsigned row_src,
unsigned col_src);
void shift_cols_in_row(unsigned dst,
unsigned src,
unsigned row,
const std::vector<unsigned>& cols,
unsigned damage,
double prob,
int drainmax,
int drain_constant,
int drain_percent);
void shift_rows_in_col(unsigned dst,
unsigned src,
unsigned col,
const std::vector<unsigned>& rows,
unsigned damage,
double prob,
int drainmax,
int drain_constant,
int drain_percent);
private: // data
const unsigned int rows_, cols_;
std::array<std::unique_ptr<double[]>, NUM_PLANES> plane_;
// For optimization, we keep track of the rows and columns with data.
// (The matrices are likely going to be rather sparse, with data on a grid.)
std::array<std::set<unsigned>, NUM_PLANES> used_rows_, used_cols_;
};
/**
* Constructor.
* @param a_max The maximum value we will track for A.
* @param b_max The maximum value we will track for B.
* @param need_a_slowed Set to true if there might be transfers to a "slow" plane for A.
* @param need_b_slowed Set to true if there might be transfers to a "slow" plane for B.
* @param a_cur The current value for A. (Ignored if a_initial[0] is not empty.)
* @param b_cur The current value for B. (Ignored if b_initial[0] is not empty.)
* @param a_initial The initial distribution of values for A. Element [0] is for normal A. while [1] is for slowed
* A.
* @param b_initial The initial distribution of values for B. Element [0] is for normal B. while [1] is for slowed
* B.
*/
prob_matrix::prob_matrix(unsigned int a_max,
unsigned int b_max,
bool need_a_slowed,
bool need_b_slowed,
unsigned int a_cur,
unsigned int b_cur,
const summary_t& a_initial,
const summary_t& b_initial)
: rows_(a_max + 1)
, cols_(b_max + 1)
, plane_()
, used_rows_()
, used_cols_()
{
// Make sure we do not access the matrix in invalid positions.
a_cur = std::min<unsigned int>(a_cur, rows_ - 1);
b_cur = std::min<unsigned int>(b_cur, cols_ - 1);
// It will be convenient to always consider row/col 0 to be used.
for(unsigned plane = 0; plane != NUM_PLANES; ++plane) {
used_rows_[plane].insert(0u);
used_cols_[plane].insert(0u);
}
// We will need slowed planes if the initial vectors have them.
need_a_slowed = need_a_slowed || !a_initial[1].empty();
need_b_slowed = need_b_slowed || !b_initial[1].empty();
// Allocate the needed planes.
plane_[NEITHER_SLOWED] = new_plane();
plane_[A_SLOWED] = !need_a_slowed ? nullptr : new_plane();
plane_[B_SLOWED] = !need_b_slowed ? nullptr : new_plane();
plane_[BOTH_SLOWED] = !(need_a_slowed && need_b_slowed) ? nullptr : new_plane();
// Initialize the probability distribution.
initialize_plane(NEITHER_SLOWED, a_cur, b_cur, a_initial[0], b_initial[0]);
if(!a_initial[1].empty()) {
initialize_plane(A_SLOWED, a_cur, b_cur, a_initial[1], b_initial[0]);
}
if(!b_initial[1].empty()) {
initialize_plane(B_SLOWED, a_cur, b_cur, a_initial[0], b_initial[1]);
}
if(!a_initial[1].empty() && !b_initial[1].empty()) {
initialize_plane(BOTH_SLOWED, a_cur, b_cur, a_initial[1], b_initial[1]);
}
// Some debugging messages.
if(!a_initial[0].empty()) {
debug(("A has fought before (or is slowed).\n"));
dump();
}
if(!b_initial[0].empty()) {
debug(("B has fought before (or is slowed).\n"));
dump();
}
}
/** Allocate a new probability array, initialized to 0. */
std::unique_ptr<double[]> prob_matrix::new_plane() const
{
const unsigned int size = rows_ * cols_;
std::unique_ptr<double[]> res(new double[size]);
std::fill_n(res.get(), size, 0);
return res;
}
/**
* Fills the indicated plane with its initial (non-zero) values.
* (Part of construction)
* @param plane The plane to initialize.
* @param a_cur The current value for A. (Ignored if a_initial is not empty.)
* @param b_cur The current value for B. (Ignored if b_initial is not empty.)
* @param a_initial The initial distribution of values for A for this plane.
* @param b_initial The initial distribution of values for B for this plane.
*/
void prob_matrix::initialize_plane(unsigned plane,
unsigned a_cur,
unsigned b_cur,
const std::vector<double>& a_initial,
const std::vector<double>& b_initial)
{
if(!a_initial.empty()) {
unsigned row_count = std::min<unsigned>(a_initial.size(), rows_);
// The probabilities for each row are contained in a_initial.
for(unsigned row = 0; row < row_count; ++row) {
if(a_initial[row] != 0.0) {
used_rows_[plane].insert(row);
initialize_row(plane, row, a_initial[row], b_cur, b_initial);
}
}
} else {
used_rows_[plane].insert(a_cur);
// Only the row indicated by a_cur is a possibility.
initialize_row(plane, a_cur, 1.0, b_cur, b_initial);
}
}
/**
* Fills the indicated row with its initial (non-zero) values.
* (Part of construction)
* @param plane The plane containing the row to initialize.
* @param row The row to initialize.
* @param row_prob The probability of A having the value for this row.
* @param b_cur The current value for B. (Ignored if b_initial is not empty.)
* @param b_initial The initial distribution of values for B for this plane.
*/
void prob_matrix::initialize_row(
unsigned plane, unsigned row, double row_prob, unsigned b_cur, const std::vector<double>& b_initial)
{
if(!b_initial.empty()) {
unsigned col_count = std::min<unsigned>(b_initial.size(), cols_);
// The probabilities for each column are contained in b_initial.
for(unsigned col = 0; col < col_count; ++col) {
if(b_initial[col] != 0.0) {
used_cols_[plane].insert(col);
val(plane, row, col) = row_prob * b_initial[col];
}
}
} else {
// Only the column indicated by b_cur is a possibility.
used_cols_[plane].insert(b_cur);
val(plane, row, b_cur) = row_prob;
}
}
double& prob_matrix::val(unsigned plane, unsigned row, unsigned col)
{
assert(row < rows_);
assert(col < cols_);
return plane_[plane][row * cols_ + col];
}
const double& prob_matrix::val(unsigned plane, unsigned row, unsigned col) const
{
assert(row < rows_);
assert(col < cols_);
return plane_[plane][row * cols_ + col];
}
// xfer, shift_cols and shift_rows use up most of our time. Careful!
/**
* Transfers a portion (value * prob) of one value in the matrix to another.
*/
void prob_matrix::xfer(unsigned dst_plane,
unsigned src_plane,
unsigned row_dst,
unsigned col_dst,
unsigned row_src,
unsigned col_src,
double prob)
{
double& src = val(src_plane, row_src, col_src);
if(src != 0.0) {
double diff = src * prob;
src -= diff;
double& dst = val(dst_plane, row_dst, col_dst);
if(dst == 0.0) {
// Track that this entry is now used.
used_rows_[dst_plane].insert(row_dst);
used_cols_[dst_plane].insert(col_dst);
}
dst += diff;
debug(("Shifted %4.3g from %s(%u,%u) to %s(%u,%u).\n", diff,
src_plane == NEITHER_SLOWED
? ""
: src_plane == A_SLOWED
? "[A_SLOWED]"
: src_plane == B_SLOWED
? "[B_SLOWED]"
: src_plane == BOTH_SLOWED
? "[BOTH_SLOWED]"
: "INVALID",
row_src, col_src,
dst_plane == NEITHER_SLOWED
? ""
: dst_plane == A_SLOWED
? "[A_SLOWED]"
: dst_plane == B_SLOWED
? "[B_SLOWED]"
: dst_plane == BOTH_SLOWED
? "[BOTH_SLOWED]"
: "INVALID",
row_dst, col_dst)
);
}
}
/**
* Transfers one value in the matrix to another.
*/
void prob_matrix::xfer(
unsigned dst_plane, unsigned src_plane, unsigned row_dst, unsigned col_dst, unsigned row_src, unsigned col_src)
{
if(dst_plane == src_plane && row_dst == row_src && col_dst == col_src)
// Transferring to itself. Nothing to do.
return;
double& src = val(src_plane, row_src, col_src);
if(src != 0.0) {
debug(("Shifting %4.3g from %s(%u,%u) to %s(%u,%u).\n", src,
src_plane == NEITHER_SLOWED
? ""
: src_plane == A_SLOWED
? "[A_SLOWED]"
: src_plane == B_SLOWED
? "[B_SLOWED]"
: src_plane == BOTH_SLOWED
? "[BOTH_SLOWED]"
: "INVALID",
row_src, col_src,
dst_plane == NEITHER_SLOWED
? ""
: dst_plane == A_SLOWED
? "[A_SLOWED]"
: dst_plane == B_SLOWED
? "[B_SLOWED]"
: dst_plane == BOTH_SLOWED
? "[BOTH_SLOWED]"
: "INVALID",
row_dst, col_dst)
);
double& dst = val(dst_plane, row_dst, col_dst);
if(dst == 0.0) {
// Track that this entry is now used.
used_rows_[dst_plane].insert(row_dst);
used_cols_[dst_plane].insert(col_dst);
}
dst += src;
src = 0.0;
}
}
/**
* Transfers a portion (value * prob) of the values in a row to another.
* Part of shift_cols().
*/
void prob_matrix::shift_cols_in_row(unsigned dst,
unsigned src,
unsigned row,
const std::vector<unsigned>& cols,
unsigned damage,
double prob,
int drainmax,
int drain_constant,
int drain_percent)
{
// Some conversions to (signed) int.
int row_i = static_cast<int>(row);
int max_row = static_cast<int>(rows_) - 1;
// cols[0] is excluded since that should be 0, representing already dead.
unsigned col_x = 1;
// Killing blows can have different drain amounts, so handle them first
for(; col_x < cols.size() && cols[col_x] < damage; ++col_x) {
// These variables are not strictly necessary, but they make the
// calculation easier to parse.
int col_i = static_cast<int>(cols[col_x]);
int drain_amount = col_i * drain_percent / 100 + drain_constant;
unsigned newrow = utils::clamp(row_i + drain_amount, 1, max_row);
xfer(dst, src, newrow, 0, row, cols[col_x], prob);
}
// The remaining columns use the specified drainmax.
unsigned newrow = utils::clamp(row_i + drainmax, 1, max_row);
for(; col_x < cols.size(); ++col_x) {
xfer(dst, src, newrow, cols[col_x] - damage, row, cols[col_x], prob);
}
}
/**
* Transfers a portion (value * prob) of each column in a plane to another.
* Each column in the @a src plane gets shifted @a damage columns towards 0, and
* also shifted into the @a dst plane. In addition, the rows can shift if
* @a drain constant or @a drain_percent is nonzero.
*/
void prob_matrix::shift_cols(
unsigned dst, unsigned src, unsigned damage, double prob, int drain_constant, int drain_percent)
{
int drainmax = (drain_percent * (static_cast<signed>(damage)) / 100 + drain_constant);
if(drain_constant || drain_percent) {
debug(("Drains %i (%i%% of %u plus %i)\n", drainmax, drain_percent, damage, drain_constant));
}
// Get lists of indices currently used in the source plane.
// (This needs to be cached since we might add indices while shifting.)
const std::vector<unsigned> rows(used_rows_[src].begin(), used_rows_[src].end());
const std::vector<unsigned> cols(used_cols_[src].begin(), used_cols_[src].end());
// Loop downwards if we drain positive, but upwards if we drain negative,
// so we write behind us (for when src == dst).
if(drainmax > 0) {
// rows[0] is excluded since that should be 0, representing already dead.
for(unsigned row_x = rows.size() - 1; row_x != 0; --row_x) {
shift_cols_in_row(dst, src, rows[row_x], cols, damage, prob, drainmax, drain_constant, drain_percent);
}
} else {
// rows[0] is excluded since that should be 0, representing already dead.
for(unsigned row_x = 1; row_x != rows.size(); ++row_x) {
shift_cols_in_row(dst, src, rows[row_x], cols, damage, prob, drainmax, drain_constant, drain_percent);
}
}
}
/**
* Transfers a portion (value * prob) of the values in a column to another.
* Part of shift_rows().
*/
void prob_matrix::shift_rows_in_col(unsigned dst,
unsigned src,
unsigned col,
const std::vector<unsigned>& rows,
unsigned damage,
double prob,
int drainmax,
int drain_constant,
int drain_percent)
{
// Some conversions to (signed) int.
int col_i = static_cast<int>(col);
int max_col = static_cast<int>(cols_) - 1;
// rows[0] is excluded since that should be 0, representing already dead.
unsigned row_x = 1;
// Killing blows can have different drain amounts, so handle them first
for(; row_x < rows.size() && rows[row_x] < damage; ++row_x) {
// These variables are not strictly necessary, but they make the
// calculation easier to parse.
int row_i = static_cast<int>(rows[row_x]);
int drain_amount = row_i * drain_percent / 100 + drain_constant;
unsigned newcol = utils::clamp(col_i + drain_amount, 1, max_col);
xfer(dst, src, 0, newcol, rows[row_x], col, prob);
}
// The remaining rows use the specified drainmax.
unsigned newcol = utils::clamp(col_i + drainmax, 1, max_col);
for(; row_x < rows.size(); ++row_x) {
xfer(dst, src, rows[row_x] - damage, newcol, rows[row_x], col, prob);
}
}
/**
* Transfers a portion (value * prob) of each row in a plane to another.
* Each row in the @a src plane gets shifted @a damage columns towards 0, and
* also shifted into the @a dst plane. In addition, the columns can shift if
* @a drain constant or @a drain_percent is nonzero.
*/
void prob_matrix::shift_rows(
unsigned dst, unsigned src, unsigned damage, double prob, int drain_constant, int drain_percent)
{
int drainmax = (drain_percent * (static_cast<signed>(damage)) / 100 + drain_constant);
if(drain_constant || drain_percent) {
debug(("Drains %i (%i%% of %u plus %i)\n", drainmax, drain_percent, damage, drain_constant));
}
// Get lists of indices currently used in the source plane.
// (This needs to be cached since we might add indices while shifting.)
const std::vector<unsigned> rows(used_rows_[src].begin(), used_rows_[src].end());
const std::vector<unsigned> cols(used_cols_[src].begin(), used_cols_[src].end());
// Loop downwards if we drain positive, but upwards if we drain negative,
// so we write behind us (for when src == dst).
if(drainmax > 0) {
// cols[0] is excluded since that should be 0, representing already dead.
for(unsigned col_x = cols.size() - 1; col_x != 0; --col_x)
shift_rows_in_col(dst, src, cols[col_x], rows, damage, prob, drainmax, drain_constant, drain_percent);
} else {
// cols[0] is excluded since that should be 0, representing already dead.
for(unsigned col_x = 1; col_x != cols.size(); ++col_x) {
shift_rows_in_col(dst, src, cols[col_x], rows, damage, prob, drainmax, drain_constant, drain_percent);
}
}
}
/**
* Move a column (adding it to the destination).
*/
void prob_matrix::move_column(unsigned d_plane, unsigned s_plane, unsigned d_col, unsigned s_col)
{
// Transfer the data.
for(const unsigned& row : used_rows_[s_plane]) {
xfer(d_plane, s_plane, row, d_col, row, s_col);
}
}
/**
* Move a row (adding it to the destination).
*/
void prob_matrix::move_row(unsigned d_plane, unsigned s_plane, unsigned d_row, unsigned s_row)
{
// Transfer the data.
for(const unsigned& col : used_cols_[s_plane]) {
xfer(d_plane, s_plane, d_row, col, s_row, col);
}
}
/**
* Move values in the specified column -- excluding row zero -- to the
* specified row in that column (possibly shifting planes in the process).
*/
void prob_matrix::merge_col(unsigned d_plane, unsigned s_plane, unsigned col, unsigned d_row)
{
auto rows_end = used_rows_[s_plane].end();
auto row_it = used_rows_[s_plane].begin();
// Transfer the data, excluding row zero.
for(++row_it; row_it != rows_end; ++row_it) {
xfer(d_plane, s_plane, d_row, col, *row_it, col);
}
}
/**
* Move values within columns in the specified plane -- excluding row zero --
* to the specified row (possibly shifting planes in the process).
*/
void prob_matrix::merge_cols(unsigned d_plane, unsigned s_plane, unsigned d_row)
{
auto rows_end = used_rows_[s_plane].end();
auto row_it = used_rows_[s_plane].begin();
// Transfer the data, excluding row zero.
for(++row_it; row_it != rows_end; ++row_it) {
for(const unsigned& col : used_cols_[s_plane]) {
xfer(d_plane, s_plane, d_row, col, *row_it, col);
}
}
}
/**
* Move values in the specified row -- excluding column zero -- to the
* specified column in that row (possibly shifting planes in the process).
*/
void prob_matrix::merge_row(unsigned d_plane, unsigned s_plane, unsigned row, unsigned d_col)
{
auto cols_end = used_cols_[s_plane].end();
auto col_it = used_cols_[s_plane].begin();
// Transfer the data, excluding column zero.
for(++col_it; col_it != cols_end; ++col_it) {
xfer(d_plane, s_plane, row, d_col, row, *col_it);
}
}
/**
* Move values within rows in the specified plane -- excluding column zero --
* to the specified column (possibly shifting planes in the process).
*/
void prob_matrix::merge_rows(unsigned d_plane, unsigned s_plane, unsigned d_col)
{
auto cols_end = used_cols_[s_plane].end();
// Exclude column zero.
auto cols_begin = std::next(used_cols_[s_plane].begin());
// Transfer the data, excluding column zero.
for(const unsigned row : used_rows_[s_plane]) {
for(auto col_it = cols_begin; col_it != cols_end; ++col_it) {
xfer(d_plane, s_plane, row, d_col, row, *col_it);
}
}
}
/**
* Set all values to zero and clear the lists of used columns/rows.
*/
void prob_matrix::clear()
{
for(unsigned int p = 0u; p < NUM_PLANES; ++p) {
if(!plane_used(p)) {
continue;
}
if(used_rows_[p].empty()) {
// Nothing to do
continue;
}
decltype(used_rows_[p].begin()) first_row, last_row;
std::tie(first_row, last_row) = std::minmax_element(used_rows_[p].begin(), used_rows_[p].end());
for(unsigned int r = *first_row; r <= *last_row; ++r) {
for(unsigned int c = 0u; c < cols_; ++c) {
plane_[p][r * cols_ + c] = 0.0;
}
}
used_rows_[p].clear();
used_cols_[p].clear();
/* Row and column 0 are always considered to be used.
Functions like merge_col() access *used_rows_[plane].begin() without checking if there are
any used rows: thus, ensuring that there are used rows and columns is necessary to avoid
memory corruption. */
used_rows_[p].insert(0u);
used_cols_[p].insert(0u);
}
}
/**
* Record the result of a single Monte Carlo simulation iteration.
*/
void prob_matrix::record_monte_carlo_result(unsigned int a_hp, unsigned int b_hp, bool a_slowed, bool b_slowed)
{
assert(a_hp <= rows_);
assert(b_hp <= cols_);
unsigned int plane = plane_index(a_slowed, b_slowed);
++val(plane, a_hp, b_hp);
used_rows_[plane].insert(a_hp);
used_cols_[plane].insert(b_hp);
}
/**
* What is the chance that an indicated combatant (one of them) is at zero?
*/
double prob_matrix::prob_of_zero(bool check_a, bool check_b) const
{
double prob = 0.0;
for(unsigned p = 0; p < NUM_PLANES; ++p) {
if(!plane_used(p)) {
continue;
}
// Column 0 is where b is at zero.
if(check_b) {
for(const unsigned& row : used_rows_[p]) {
prob += val(p, row, 0);
}
}
// Row 0 is where a is at zero.
if(check_a) {
for(const unsigned& col : used_cols_[p]) {
prob += val(p, 0, col);
}
}
// Theoretically, if checking both, we should subtract the chance that
// both are dead, but that chance is zero, so don't worry about it.
}
return prob;
}
/**
* Sums the values in the specified row.
*/
double prob_matrix::row_sum(unsigned plane, unsigned row) const
{
double sum = 0.0;
for(unsigned col : used_cols_[plane]) {
sum += val(plane, row, col);
}
return sum;
}
/**
* Sums the values in the specified column.
*/
double prob_matrix::col_sum(unsigned plane, unsigned column) const
{
double sum = 0.0;
for(unsigned row : used_rows_[plane]) {
sum += val(plane, row, column);
}
return sum;
}
/**
* Sums the values in the specified plane.
* The sum of each row is added to the corresponding entry in row_sums.
* The sum of each column is added to the corresponding entry in col_sums.
*/
void prob_matrix::sum(unsigned plane, std::vector<double>& row_sums, std::vector<double>& col_sums) const
{
for(const unsigned& row : used_rows_[plane]) {
for(const unsigned& col : used_cols_[plane]) {
const double& prob = val(plane, row, col);
row_sums[row] += prob;
col_sums[col] += prob;
}
}
}
#if defined(CHECK) && defined(ATTACK_PREDICTION_DEBUG)
void prob_matrix::dump() const
{
unsigned int row, col, m;
const char* names[] {"NEITHER_SLOWED", "A_SLOWED", "B_SLOWED", "BOTH_SLOWED"};
for(m = 0; m < NUM_PLANES; ++m) {
if(!plane_used(m)) {
continue;
}
debug(("%s:\n", names[m]));
for(row = 0; row < rows_; ++row) {
debug((" "));
for(col = 0; col < cols_; ++col) {
debug(("%4.3g ", val(m, row, col) * 100));
}