/
attack.cpp
1689 lines (1370 loc) · 49.5 KB
/
attack.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) 2003 - 2018 by David White <dave@whitevine.net>
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.
*/
/**
* @file
* Fighting.
*/
#include "actions/attack.hpp"
#include "actions/advancement.hpp"
#include "actions/vision.hpp"
#include "ai/lua/aspect_advancements.hpp"
#include "game_config.hpp"
#include "game_data.hpp"
#include "game_events/pump.hpp"
#include "gettext.hpp"
#include "log.hpp"
#include "map/map.hpp"
#include "mouse_handler_base.hpp"
#include "play_controller.hpp"
#include "preferences/game.hpp"
#include "random.hpp"
#include "replay.hpp"
#include "resources.hpp"
#include "statistics.hpp"
#include "synced_checkup.hpp"
#include "synced_user_choice.hpp"
#include "team.hpp"
#include "tod_manager.hpp"
#include "units/abilities.hpp"
#include "units/animation_component.hpp"
#include "units/helper.hpp"
#include "units/map.hpp"
#include "units/udisplay.hpp"
#include "units/unit.hpp"
#include "whiteboard/manager.hpp"
#include "wml_exception.hpp"
static lg::log_domain log_engine("engine");
#define DBG_NG LOG_STREAM(debug, log_engine)
#define LOG_NG LOG_STREAM(info, log_engine)
#define WRN_NG LOG_STREAM(err, log_engine)
#define ERR_NG LOG_STREAM(err, log_engine)
static lg::log_domain log_config("config");
#define LOG_CF LOG_STREAM(info, log_config)
// ==================================================================================
// BATTLE CONTEXT UNIT STATS
// ==================================================================================
battle_context_unit_stats::battle_context_unit_stats(const unit& u,
const map_location& u_loc,
int u_attack_num,
bool attacking,
const unit& opp,
const map_location& opp_loc,
const_attack_ptr opp_weapon,
const unit_map& units)
: weapon(nullptr)
, attack_num(u_attack_num)
, is_attacker(attacking)
, is_poisoned(u.get_state(unit::STATE_POISONED))
, is_slowed(u.get_state(unit::STATE_SLOWED))
, slows(false)
, drains(false)
, petrifies(false)
, plagues(false)
, poisons(false)
, backstab_pos(false)
, swarm(false)
, firststrike(false)
, disable(false)
, experience(u.experience())
, max_experience(u.max_experience())
, level(u.level())
, rounds(1)
, hp(0)
, max_hp(u.max_hitpoints())
, chance_to_hit(0)
, damage(0)
, slow_damage(0)
, drain_percent(0)
, drain_constant(0)
, num_blows(0)
, swarm_min(0)
, swarm_max(0)
, plague_type()
{
// Get the current state of the unit.
if(attack_num >= 0) {
weapon = u.attacks()[attack_num].shared_from_this();
}
if(u.hitpoints() < 0) {
LOG_CF << "Unit with " << u.hitpoints() << " hitpoints found, set to 0 for damage calculations\n";
hp = 0;
} else if(u.hitpoints() > u.max_hitpoints()) {
// If a unit has more hp than its maximum, the engine will fail with an
// assertion failure due to accessing the prob_matrix out of bounds.
hp = u.max_hitpoints();
} else {
hp = u.hitpoints();
}
// Exit if no weapon.
if(!weapon) {
return;
}
// Get the weapon characteristics as appropriate.
auto ctx = weapon->specials_context(u, opp, u_loc, opp_loc, attacking, opp_weapon);
boost::optional<decltype(ctx)> opp_ctx;
if(opp_weapon) {
opp_ctx.emplace(opp_weapon->specials_context(opp, u, opp_loc, u_loc, !attacking, weapon));
}
slows = weapon->get_special_bool("slow");
drains = !opp.get_state("undrainable") && weapon->get_special_bool("drains");
petrifies = weapon->get_special_bool("petrifies");
poisons = !opp.get_state("unpoisonable") && weapon->get_special_bool("poison") && !opp.get_state(unit::STATE_POISONED);
backstab_pos = is_attacker && backstab_check(u_loc, opp_loc, units, resources::gameboard->teams());
rounds = weapon->get_specials("berserk").highest("value", 1).first;
firststrike = weapon->get_special_bool("firststrike");
{
const int distance = distance_between(u_loc, opp_loc);
const bool out_of_range = distance > weapon->max_range() || distance < weapon->min_range();
disable = weapon->get_special_bool("disable") || out_of_range;
}
// Handle plague.
unit_ability_list plague_specials = weapon->get_specials("plague");
plagues = !opp.get_state("unplagueable") && !plague_specials.empty() &&
opp.undead_variation() != "null" && !resources::gameboard->map().is_village(opp_loc);
if(plagues) {
plague_type = (*plague_specials.front().first)["type"].str();
if(plague_type.empty()) {
plague_type = u.type().base_id();
}
}
// Compute chance to hit.
chance_to_hit = opp.defense_modifier(resources::gameboard->map().get_terrain(opp_loc)) + weapon->accuracy()
- (opp_weapon ? opp_weapon->parry() : 0);
if(chance_to_hit > 100) {
chance_to_hit = 100;
}
unit_ability_list cth_specials = weapon->get_specials("chance_to_hit");
unit_abilities::effect cth_effects(cth_specials, chance_to_hit, backstab_pos);
chance_to_hit = cth_effects.get_composite_value();
if(opp.get_state("invulnerable")) {
chance_to_hit = 0;
}
// Compute base damage done with the weapon.
int base_damage = weapon->modified_damage(backstab_pos);
// Get the damage multiplier applied to the base damage of the weapon.
int damage_multiplier = 100;
// Time of day bonus.
damage_multiplier += combat_modifier(
resources::gameboard->units(), resources::gameboard->map(), u_loc, u.alignment(), u.is_fearless());
// Leadership bonus.
int leader_bonus = under_leadership(units, u_loc).first;
if(leader_bonus != 0) {
damage_multiplier += leader_bonus;
}
// Resistance modifier.
damage_multiplier *= opp.damage_from(*weapon, !attacking, opp_loc);
// Compute both the normal and slowed damage.
damage = round_damage(base_damage, damage_multiplier, 10000);
slow_damage = round_damage(base_damage, damage_multiplier, 20000);
if(is_slowed) {
damage = slow_damage;
}
// Compute drain amounts only if draining is possible.
if(drains) {
unit_ability_list drain_specials = weapon->get_specials("drains");
// Compute the drain percent (with 50% as the base for backward compatibility)
unit_abilities::effect drain_percent_effects(drain_specials, 50, backstab_pos);
drain_percent = drain_percent_effects.get_composite_value();
}
// Add heal_on_hit (the drain constant)
unit_ability_list heal_on_hit_specials = weapon->get_specials("heal_on_hit");
unit_abilities::effect heal_on_hit_effects(heal_on_hit_specials, 0, backstab_pos);
drain_constant += heal_on_hit_effects.get_composite_value();
drains = drain_constant || drain_percent;
// Compute the number of blows and handle swarm.
weapon->modified_attacks(backstab_pos, swarm_min, swarm_max);
swarm = swarm_min != swarm_max;
num_blows = calc_blows(hp);
}
battle_context_unit_stats::battle_context_unit_stats(const unit_type* u_type,
const_attack_ptr att_weapon,
bool attacking,
const unit_type* opp_type,
const_attack_ptr opp_weapon,
unsigned int opp_terrain_defense,
int lawful_bonus)
: weapon(att_weapon)
, attack_num(-2) // This is and stays invalid. Always use weapon when using this constructor.
, is_attacker(attacking)
, is_poisoned(false)
, is_slowed(false)
, slows(false)
, drains(false)
, petrifies(false)
, plagues(false)
, poisons(false)
, backstab_pos(false)
, swarm(false)
, firststrike(false)
, disable(false)
, experience(0)
, max_experience(0)
, level(0)
, rounds(1)
, hp(0)
, max_hp(0)
, chance_to_hit(0)
, damage(0)
, slow_damage(0)
, drain_percent(0)
, drain_constant(0)
, num_blows(0)
, swarm_min(0)
, swarm_max(0)
, plague_type()
{
if(!u_type || !opp_type) {
return;
}
// Get the current state of the unit.
if(u_type->hitpoints() < 0) {
hp = 0;
} else {
hp = u_type->hitpoints();
}
max_experience = u_type->experience_needed();
level = (u_type->level());
max_hp = (u_type->hitpoints());
// Exit if no weapon.
if(!weapon) {
return;
}
// Get the weapon characteristics as appropriate.
auto ctx = weapon->specials_context(*u_type, map_location::null_location(), attacking);
boost::optional<decltype(ctx)> opp_ctx;
if(opp_weapon) {
opp_ctx.emplace(opp_weapon->specials_context(*opp_type, map_location::null_location(), !attacking));
}
slows = weapon->get_special_bool("slow");
drains = !opp_type->musthave_status("undrainable") && weapon->get_special_bool("drains");
petrifies = weapon->get_special_bool("petrifies");
poisons = !opp_type->musthave_status("unpoisonable") && weapon->get_special_bool("poison");
rounds = weapon->get_specials("berserk").highest("value", 1).first;
firststrike = weapon->get_special_bool("firststrike");
disable = weapon->get_special_bool("disable");
unit_ability_list plague_specials = weapon->get_specials("plague");
plagues = !opp_type->musthave_status("unplagueable") && !plague_specials.empty() &&
opp_type->undead_variation() != "null";
if(plagues) {
plague_type = (*plague_specials.front().first)["type"].str();
if(plague_type.empty()) {
plague_type = u_type->base_id();
}
}
signed int cth = 100 - opp_terrain_defense + weapon->accuracy() - (opp_weapon ? opp_weapon->parry() : 0);
cth = std::min(100, cth);
cth = std::max(0, cth);
chance_to_hit = cth;
unit_ability_list cth_specials = weapon->get_specials("chance_to_hit");
unit_abilities::effect cth_effects(cth_specials, chance_to_hit, backstab_pos);
chance_to_hit = cth_effects.get_composite_value();
int base_damage = weapon->modified_damage(backstab_pos);
int damage_multiplier = 100;
damage_multiplier
+= generic_combat_modifier(lawful_bonus, u_type->alignment(), u_type->musthave_status("fearless"));
damage_multiplier *= opp_type->resistance_against(weapon->type(), !attacking);
damage = round_damage(base_damage, damage_multiplier, 10000);
slow_damage = round_damage(base_damage, damage_multiplier, 20000);
if(drains) {
unit_ability_list drain_specials = weapon->get_specials("drains");
// Compute the drain percent (with 50% as the base for backward compatibility)
unit_abilities::effect drain_percent_effects(drain_specials, 50, backstab_pos);
drain_percent = drain_percent_effects.get_composite_value();
}
// Add heal_on_hit (the drain constant)
unit_ability_list heal_on_hit_specials = weapon->get_specials("heal_on_hit");
unit_abilities::effect heal_on_hit_effects(heal_on_hit_specials, 0, backstab_pos);
drain_constant += heal_on_hit_effects.get_composite_value();
drains = drain_constant || drain_percent;
// Compute the number of blows and handle swarm.
weapon->modified_attacks(backstab_pos, swarm_min, swarm_max);
swarm = swarm_min != swarm_max;
num_blows = calc_blows(hp);
}
// ==================================================================================
// BATTLE CONTEXT
// ==================================================================================
battle_context::battle_context(const unit_map& units,
const map_location& attacker_loc,
const map_location& defender_loc,
int attacker_weapon,
int defender_weapon,
double aggression,
const combatant* prev_def,
const unit* attacker_ptr)
: attacker_stats_(nullptr)
, defender_stats_(nullptr)
, attacker_combatant_(nullptr)
, defender_combatant_(nullptr)
{
const unit& attacker = attacker_ptr ? *attacker_ptr : *units.find(attacker_loc);
const unit& defender = *units.find(defender_loc);
const double harm_weight = 1.0 - aggression;
if(attacker_weapon == -1 &&
attacker.attacks().size() == 1 &&
attacker.attacks()[0].attack_weight() > 0 &&
!attacker.attacks()[0].get_special_bool("disable", true)
) {
attacker_weapon = 0;
}
if(attacker_weapon == -1) {
attacker_weapon = choose_attacker_weapon(
attacker, defender, units, attacker_loc, defender_loc, harm_weight, &defender_weapon, prev_def
);
} else if(defender_weapon == -1) {
defender_weapon = choose_defender_weapon(
attacker, defender, attacker_weapon, units, attacker_loc, defender_loc, prev_def
);
}
// If those didn't have to generate statistics, do so now.
if(!attacker_stats_) {
const_attack_ptr adef = nullptr;
const_attack_ptr ddef = nullptr;
if(attacker_weapon >= 0) {
VALIDATE(attacker_weapon < static_cast<int>(attacker.attacks().size()),
_("An invalid attacker weapon got selected."));
adef = attacker.attacks()[attacker_weapon].shared_from_this();
}
if(defender_weapon >= 0) {
VALIDATE(defender_weapon < static_cast<int>(defender.attacks().size()),
_("An invalid defender weapon got selected."));
ddef = defender.attacks()[defender_weapon].shared_from_this();
}
assert(!defender_stats_ && !attacker_combatant_ && !defender_combatant_);
attacker_stats_.reset(new battle_context_unit_stats(
attacker, attacker_loc, attacker_weapon, true, defender, defender_loc, ddef, units));
defender_stats_.reset(new battle_context_unit_stats(
defender, defender_loc, defender_weapon, false, attacker, attacker_loc, adef, units));
}
// There have been various bugs where only one of these was set
assert(attacker_stats_);
assert(defender_stats_);
}
battle_context::battle_context(const battle_context_unit_stats& att, const battle_context_unit_stats& def)
: attacker_stats_(new battle_context_unit_stats(att))
, defender_stats_(new battle_context_unit_stats(def))
, attacker_combatant_(nullptr)
, defender_combatant_(nullptr)
{
}
battle_context::battle_context(const battle_context& other)
: attacker_stats_(nullptr)
, defender_stats_(nullptr)
, attacker_combatant_(nullptr)
, defender_combatant_(nullptr)
{
*this = other;
}
battle_context& battle_context::operator=(const battle_context& other)
{
if(&other != this) {
attacker_stats_.reset(new battle_context_unit_stats(*other.attacker_stats_));
defender_stats_.reset(new battle_context_unit_stats(*other.defender_stats_));
attacker_combatant_.reset(other.attacker_combatant_
? new combatant(*other.attacker_combatant_, *attacker_stats_) : nullptr);
defender_combatant_.reset(other.defender_combatant_
? new combatant(*other.defender_combatant_, *defender_stats_) : nullptr);
}
return *this;
}
/** @todo FIXME: better to initialize combatant initially (move into
battle_context_unit_stats?), just do fight() when required. */
const combatant& battle_context::get_attacker_combatant(const combatant* prev_def)
{
// We calculate this lazily, since AI doesn't always need it.
if(!attacker_combatant_) {
assert(!defender_combatant_);
attacker_combatant_.reset(new combatant(*attacker_stats_));
defender_combatant_.reset(new combatant(*defender_stats_, prev_def));
attacker_combatant_->fight(*defender_combatant_);
}
return *attacker_combatant_;
}
const combatant& battle_context::get_defender_combatant(const combatant* prev_def)
{
// We calculate this lazily, since AI doesn't always need it.
if(!defender_combatant_) {
assert(!attacker_combatant_);
attacker_combatant_.reset(new combatant(*attacker_stats_));
defender_combatant_.reset(new combatant(*defender_stats_, prev_def));
attacker_combatant_->fight(*defender_combatant_);
}
return *defender_combatant_;
}
// Given this harm_weight, are we better than this other context?
bool battle_context::better_attack(class battle_context& that, double harm_weight)
{
return better_combat(
get_attacker_combatant(),
get_defender_combatant(),
that.get_attacker_combatant(),
that.get_defender_combatant(),
harm_weight
);
}
// Does combat A give us a better result than combat B?
bool battle_context::better_combat(const combatant& us_a,
const combatant& them_a,
const combatant& us_b,
const combatant& them_b,
double harm_weight)
{
double a, b;
// Compare: P(we kill them) - P(they kill us).
a = them_a.hp_dist[0] - us_a.hp_dist[0] * harm_weight;
b = them_b.hp_dist[0] - us_b.hp_dist[0] * harm_weight;
if(a - b < -0.01) {
return false;
}
if(a - b > 0.01) {
return true;
}
// Add poison to calculations
double poison_a_us = (us_a.poisoned) * game_config::poison_amount;
double poison_a_them = (them_a.poisoned) * game_config::poison_amount;
double poison_b_us = (us_b.poisoned) * game_config::poison_amount;
double poison_b_them = (them_b.poisoned) * game_config::poison_amount;
// Compare: damage to them - damage to us (average_hp replaces -damage)
a = (us_a.average_hp() - poison_a_us) * harm_weight - (them_a.average_hp() - poison_a_them);
b = (us_b.average_hp() - poison_b_us) * harm_weight - (them_b.average_hp() - poison_b_them);
if(a - b < -0.01) {
return false;
}
if(a - b > 0.01) {
return true;
}
// All else equal: go for most damage.
return them_a.average_hp() < them_b.average_hp();
}
int battle_context::choose_attacker_weapon(const unit& attacker,
const unit& defender,
const unit_map& units,
const map_location& attacker_loc,
const map_location& defender_loc,
double harm_weight,
int* defender_weapon,
const combatant* prev_def)
{
std::vector<unsigned int> choices;
// What options does attacker have?
unsigned int i;
for(i = 0; i < attacker.attacks().size(); ++i) {
const attack_type& att = attacker.attacks()[i];
if(att.attack_weight() > 0) {
choices.push_back(i);
}
}
if(choices.empty()) {
return -1;
}
if(choices.size() == 1) {
*defender_weapon
= choose_defender_weapon(attacker, defender, choices[0], units, attacker_loc, defender_loc, prev_def);
const_attack_ptr def_weapon
= *defender_weapon >= 0 ? defender.attacks()[*defender_weapon].shared_from_this() : nullptr;
attacker_stats_.reset(new battle_context_unit_stats(
attacker, attacker_loc, choices[0], true, defender, defender_loc, def_weapon, units));
if(attacker_stats_->disable) {
return -1;
}
const attack_type& att = attacker.attacks()[choices[0]];
defender_stats_.reset(new battle_context_unit_stats(
defender, defender_loc, *defender_weapon, false, attacker, attacker_loc, att.shared_from_this(), units));
return choices[0];
}
// Multiple options: simulate them, save best.
std::unique_ptr<battle_context_unit_stats> best_att_stats(nullptr);
std::unique_ptr<battle_context_unit_stats> best_def_stats(nullptr);
std::unique_ptr<combatant> best_att_comb(nullptr);
std::unique_ptr<combatant> best_def_comb(nullptr);
for(i = 0; i < choices.size(); ++i) {
const attack_type& att = attacker.attacks()[choices[i]];
int def_weapon =
choose_defender_weapon(attacker, defender, choices[i], units, attacker_loc, defender_loc, prev_def);
// If that didn't simulate, do so now.
if(!attacker_combatant_) {
const_attack_ptr def = nullptr;
if(def_weapon >= 0) {
def = defender.attacks()[def_weapon].shared_from_this();
}
attacker_stats_.reset(new battle_context_unit_stats(
attacker, attacker_loc, choices[i], true, defender, defender_loc, def, units));
if(attacker_stats_->disable) {
continue;
}
defender_stats_.reset(new battle_context_unit_stats(
defender, defender_loc, def_weapon, false, attacker, attacker_loc, att.shared_from_this(), units));
attacker_combatant_.reset(new combatant(*attacker_stats_));
defender_combatant_.reset(new combatant(*defender_stats_, prev_def));
attacker_combatant_->fight(*defender_combatant_);
} else {
if(attacker_stats_ != nullptr && attacker_stats_->disable) {
continue;
}
}
if(!best_att_comb ||
better_combat(*attacker_combatant_, *defender_combatant_, *best_att_comb, *best_def_comb, harm_weight)
) {
best_att_comb = std::move(attacker_combatant_);
best_def_comb = std::move(defender_combatant_);
best_att_stats = std::move(attacker_stats_);
best_def_stats = std::move(defender_stats_);
}
attacker_combatant_.reset();
defender_combatant_.reset();
attacker_stats_.reset();
defender_stats_.reset();
}
attacker_combatant_ = std::move(best_att_comb);
defender_combatant_ = std::move(best_def_comb);
attacker_stats_ = std::move(best_att_stats);
defender_stats_ = std::move(best_def_stats);
// These currently mean the same thing, but assumptions like that have been broken before
if(!defender_stats_ || !attacker_stats_) {
return -1;
}
*defender_weapon = defender_stats_->attack_num;
return attacker_stats_->attack_num;
}
/** @todo FIXME: Hand previous defender unit in here. */
int battle_context::choose_defender_weapon(const unit& attacker,
const unit& defender,
unsigned attacker_weapon,
const unit_map& units,
const map_location& attacker_loc,
const map_location& defender_loc,
const combatant* prev_def)
{
VALIDATE(attacker_weapon < attacker.attacks().size(), _("An invalid attacker weapon got selected."));
const attack_type& att = attacker.attacks()[attacker_weapon];
std::vector<unsigned int> choices;
// What options does defender have?
unsigned int i;
for(i = 0; i < defender.attacks().size(); ++i) {
const attack_type& def = defender.attacks()[i];
if(def.range() == att.range() && def.defense_weight() > 0) {
choices.push_back(i);
}
}
if(choices.empty()) {
return -1;
}
if(choices.size() == 1) {
const battle_context_unit_stats def_stats(
defender, defender_loc, choices[0], false, attacker, attacker_loc, att.shared_from_this(), units);
return (def_stats.disable) ? -1 : choices[0];
}
// Multiple options:
// First pass : get the best weight and the minimum simple rating for this weight.
// simple rating = number of blows * damage per blows (resistance taken in account) * cth * weight
// Eligible attacks for defense should have a simple rating greater or equal to this weight.
int min_rating = 0;
{
double max_weight = 0.0;
for(i = 0; i < choices.size(); ++i) {
const attack_type& def = defender.attacks()[choices[i]];
if(def.defense_weight() >= max_weight) {
const battle_context_unit_stats def_stats(defender, defender_loc, choices[i], false, attacker,
attacker_loc, att.shared_from_this(), units);
if(def_stats.disable) {
continue;
}
max_weight = def.defense_weight();
int rating = static_cast<int>(
def_stats.num_blows * def_stats.damage * def_stats.chance_to_hit * def.defense_weight());
if(def.defense_weight() > max_weight || rating < min_rating) {
min_rating = rating;
}
}
}
}
// Multiple options: simulate them, save best.
for(i = 0; i < choices.size(); ++i) {
const attack_type& def = defender.attacks()[choices[i]];
std::unique_ptr<battle_context_unit_stats> att_stats(new battle_context_unit_stats(
attacker, attacker_loc, attacker_weapon, true, defender, defender_loc, def.shared_from_this(), units));
std::unique_ptr<battle_context_unit_stats> def_stats(new battle_context_unit_stats(
defender, defender_loc, choices[i], false, attacker, attacker_loc, att.shared_from_this(), units));
if(def_stats->disable) {
continue;
}
std::unique_ptr<combatant> att_comb(new combatant(*att_stats));
std::unique_ptr<combatant> def_comb(new combatant(*def_stats, prev_def));
att_comb->fight(*def_comb);
int simple_rating = static_cast<int>(
def_stats->num_blows * def_stats->damage * def_stats->chance_to_hit * def.defense_weight());
if(simple_rating >= min_rating &&
(!attacker_combatant_ || better_combat(*def_comb, *att_comb, *defender_combatant_, *attacker_combatant_, 1.0))
) {
attacker_combatant_ = std::move(att_comb);
defender_combatant_ = std::move(def_comb);
attacker_stats_ = std::move(att_stats);
defender_stats_ = std::move(def_stats);
}
}
return defender_stats_ ? defender_stats_->attack_num : -1;
}
// ==================================================================================
// HELPERS
// ==================================================================================
namespace
{
void refresh_weapon_index(int& weap_index, const std::string& weap_id, attack_itors attacks)
{
// No attacks to choose from.
if(attacks.empty()) {
weap_index = -1;
return;
}
// The currently selected attack fits.
if(weap_index >= 0 && weap_index < static_cast<int>(attacks.size()) && attacks[weap_index].id() == weap_id) {
return;
}
// Look up the weapon by id.
if(!weap_id.empty()) {
for(int i = 0; i < static_cast<int>(attacks.size()); ++i) {
if(attacks[i].id() == weap_id) {
weap_index = i;
return;
}
}
}
// Lookup has failed.
weap_index = -1;
return;
}
/** Helper class for performing an attack. */
class attack
{
public:
attack(const map_location& attacker,
const map_location& defender,
int attack_with,
int defend_with,
bool update_display = true);
void perform();
private:
class attack_end_exception
{
};
bool perform_hit(bool, statistics::attack_context&);
void fire_event(const std::string& n);
void refresh_bc();
/** Structure holding unit info used in the attack action. */
struct unit_info
{
const map_location loc_;
int weapon_;
unit_map& units_;
size_t id_; /**< unit.underlying_id() */
std::string weap_id_;
int orig_attacks_;
int n_attacks_; /**< Number of attacks left. */
int cth_;
int damage_;
int xp_;
unit_info(const map_location& loc, int weapon, unit_map& units);
unit& get_unit();
bool valid();
std::string dump();
};
/**
* Used in perform_hit to confirm a replay is in sync.
* Check OOS_error_ after this method, true if error detected.
*/
void check_replay_attack_result(bool&, int, int&, config, unit_info&);
void unit_killed(
unit_info&, unit_info&, const battle_context_unit_stats*&, const battle_context_unit_stats*&, bool);
std::unique_ptr<battle_context> bc_;
const battle_context_unit_stats* a_stats_;
const battle_context_unit_stats* d_stats_;
int abs_n_attack_, abs_n_defend_;
// update_att_fog_ is not used, other than making some code simpler.
bool update_att_fog_, update_def_fog_, update_minimap_;
unit_info a_, d_;
unit_map& units_;
std::ostringstream errbuf_;
bool update_display_;
bool OOS_error_;
};
attack::unit_info::unit_info(const map_location& loc, int weapon, unit_map& units)
: loc_(loc)
, weapon_(weapon)
, units_(units)
, id_()
, weap_id_()
, orig_attacks_(0)
, n_attacks_(0)
, cth_(0)
, damage_(0)
, xp_(0)
{
unit_map::iterator i = units_.find(loc_);
if(!i.valid()) {
return;
}
id_ = i->underlying_id();
}
unit& attack::unit_info::get_unit()
{
unit_map::iterator i = units_.find(loc_);
assert(i.valid() && i->underlying_id() == id_);
return *i;
}
bool attack::unit_info::valid()
{
unit_map::iterator i = units_.find(loc_);
return i.valid() && i->underlying_id() == id_;
}
std::string attack::unit_info::dump()
{
std::stringstream s;
s << get_unit().type_id() << " (" << loc_.wml_x() << ',' << loc_.wml_y() << ')';
return s.str();
}
attack::attack(const map_location& attacker,
const map_location& defender,
int attack_with,
int defend_with,
bool update_display)
: bc_(nullptr)
, a_stats_(nullptr)
, d_stats_(nullptr)
, abs_n_attack_(0)
, abs_n_defend_(0)
, update_att_fog_(false)
, update_def_fog_(false)
, update_minimap_(false)
, a_(attacker, attack_with, resources::gameboard->units())
, d_(defender, defend_with, resources::gameboard->units())
, units_(resources::gameboard->units())
, errbuf_()
, update_display_(update_display)
, OOS_error_(false)
{
}
void attack::fire_event(const std::string& n)
{
LOG_NG << "firing " << n << " event\n";
// prepare the event data for weapon filtering
config ev_data;
config& a_weapon_cfg = ev_data.add_child("first");
config& d_weapon_cfg = ev_data.add_child("second");
// Need these to ensure weapon filters work correctly
boost::optional<attack_type::specials_context_t> a_ctx, d_ctx;
if(a_stats_->weapon != nullptr && a_.valid()) {
if(d_stats_->weapon != nullptr && d_.valid()) {
a_ctx.emplace(a_stats_->weapon->specials_context(a_.get_unit(), d_.get_unit(), a_.loc_, d_.loc_, true, d_stats_->weapon));
} else {
a_ctx.emplace(a_stats_->weapon->specials_context(a_.get_unit(), a_.loc_, true));
}
a_stats_->weapon->write(a_weapon_cfg);
}
if(d_stats_->weapon != nullptr && d_.valid()) {
if(a_stats_->weapon != nullptr && a_.valid()) {
d_ctx.emplace(d_stats_->weapon->specials_context(d_.get_unit(), a_.get_unit(), d_.loc_, a_.loc_, false, a_stats_->weapon));
} else {
d_ctx.emplace(d_stats_->weapon->specials_context(d_.get_unit(), d_.loc_, false));
}
d_stats_->weapon->write(d_weapon_cfg);
}
if(a_weapon_cfg["name"].empty()) {
a_weapon_cfg["name"] = "none";
}
if(d_weapon_cfg["name"].empty()) {
d_weapon_cfg["name"] = "none";
}
if(n == "attack_end") {
// We want to fire attack_end event in any case! Even if one of units was removed by WML.
resources::game_events->pump().fire(n, a_.loc_, d_.loc_, ev_data);
return;
}
// damage_inflicted is set in these two events.
// TODO: should we set this value from unit_info::damage, or continue using the WML variable?
if(n == "attacker_hits" || n == "defender_hits") {
ev_data["damage_inflicted"] = resources::gamedata->get_variable("damage_inflicted");
}
const int defender_side = d_.get_unit().side();
resources::game_events->pump().fire(n,
game_events::entity_location(a_.loc_, a_.id_),
game_events::entity_location(d_.loc_, d_.id_), ev_data);
// The event could have killed either the attacker or
// defender, so we have to make sure they still exist.
refresh_bc();
if(!a_.valid() || !d_.valid()
|| !resources::gameboard->get_team(a_.get_unit().side()).is_enemy(d_.get_unit().side())
) {
actions::recalculate_fog(defender_side);
if(update_display_) {
display::get_singleton()->redraw_minimap();
}
fire_event("attack_end");
throw attack_end_exception();
}
}
void attack::refresh_bc()
{
// Fix index of weapons.
if(a_.valid()) {
refresh_weapon_index(a_.weapon_, a_.weap_id_, a_.get_unit().attacks());
}