The Battle for Wesnoth  1.15.3+dev
attack.cpp
Go to the documentation of this file.
1 /*
2  Copyright (C) 2003 - 2018 by David White <dave@whitevine.net>
3  Part of the Battle for Wesnoth Project https://www.wesnoth.org/
4 
5  This program is free software; you can redistribute it and/or modify
6  it under the terms of the GNU General Public License as published by
7  the Free Software Foundation; either version 2 of the License, or
8  (at your option) any later version.
9  This program is distributed in the hope that it will be useful,
10  but WITHOUT ANY WARRANTY.
11 
12  See the COPYING file for more details.
13 */
14 
15 /**
16  * @file
17  * Fighting.
18  */
19 
20 #include "actions/attack.hpp"
21 
22 #include "actions/advancement.hpp"
23 #include "actions/vision.hpp"
24 
26 #include "formula/callable_objects.hpp"
27 #include "formula/formula.hpp"
28 #include "game_config.hpp"
29 #include "game_data.hpp"
30 #include "game_events/pump.hpp"
31 #include "gettext.hpp"
32 #include "log.hpp"
33 #include "map/map.hpp"
34 #include "mouse_handler_base.hpp"
35 #include "play_controller.hpp"
36 #include "preferences/game.hpp"
37 #include "random.hpp"
38 #include "replay.hpp"
39 #include "resources.hpp"
40 #include "statistics.hpp"
41 #include "synced_checkup.hpp"
42 #include "synced_user_choice.hpp"
43 #include "team.hpp"
44 #include "tod_manager.hpp"
45 #include "units/abilities.hpp"
47 #include "units/helper.hpp"
48 #include "units/filter.hpp"
49 #include "units/map.hpp"
50 #include "units/udisplay.hpp"
51 #include "units/unit.hpp"
52 #include "units/types.hpp"
53 #include "whiteboard/manager.hpp"
54 #include "wml_exception.hpp"
55 
56 static lg::log_domain log_engine("engine");
57 #define DBG_NG LOG_STREAM(debug, log_engine)
58 #define LOG_NG LOG_STREAM(info, log_engine)
59 #define WRN_NG LOG_STREAM(err, log_engine)
60 #define ERR_NG LOG_STREAM(err, log_engine)
61 
62 static lg::log_domain log_attack("engine/attack");
63 #define DBG_AT LOG_STREAM(debug, log_attack)
64 #define LOG_AT LOG_STREAM(info, log_attack)
65 #define WRN_AT LOG_STREAM(err, log_attack)
66 #define ERR_AT LOG_STREAM(err, log_attack)
67 
68 static lg::log_domain log_config("config");
69 #define LOG_CF LOG_STREAM(info, log_config)
70 
71 // ==================================================================================
72 // BATTLE CONTEXT UNIT STATS
73 // ==================================================================================
74 
76  const map_location& u_loc,
77  int u_attack_num,
78  bool attacking,
79  const unit& opp,
80  const map_location& opp_loc,
81  const_attack_ptr opp_weapon,
82  const unit_map& units)
83  : weapon(nullptr)
84  , attack_num(u_attack_num)
85  , is_attacker(attacking)
86  , is_poisoned(u.get_state(unit::STATE_POISONED))
87  , is_slowed(u.get_state(unit::STATE_SLOWED))
88  , slows(false)
89  , drains(false)
90  , petrifies(false)
91  , plagues(false)
92  , poisons(false)
93  , backstab_pos(false)
94  , swarm(false)
95  , firststrike(false)
96  , disable(false)
97  , experience(u.experience())
98  , max_experience(u.max_experience())
99  , level(u.level())
100  , rounds(1)
101  , hp(0)
102  , max_hp(u.max_hitpoints())
103  , chance_to_hit(0)
104  , damage(0)
105  , slow_damage(0)
106  , drain_percent(0)
107  , drain_constant(0)
108  , num_blows(0)
109  , swarm_min(0)
110  , swarm_max(0)
111  , plague_type()
112 {
113  // Get the current state of the unit.
114  if(attack_num >= 0) {
115  weapon = u.attacks()[attack_num].shared_from_this();
116  }
117 
118  if(u.hitpoints() < 0) {
119  LOG_CF << "Unit with " << u.hitpoints() << " hitpoints found, set to 0 for damage calculations\n";
120  hp = 0;
121  } else if(u.hitpoints() > u.max_hitpoints()) {
122  // If a unit has more hp than its maximum, the engine will fail with an
123  // assertion failure due to accessing the prob_matrix out of bounds.
124  hp = u.max_hitpoints();
125  } else {
126  hp = u.hitpoints();
127  }
128 
129  // Exit if no weapon.
130  if(!weapon) {
131  return;
132  }
133 
134  // Get the weapon characteristics as appropriate.
135  auto ctx = weapon->specials_context(&u, &opp, u_loc, opp_loc, attacking, opp_weapon);
136  boost::optional<decltype(ctx)> opp_ctx;
137 
138  if(opp_weapon) {
139  opp_ctx.emplace(opp_weapon->specials_context(&opp, &u, opp_loc, u_loc, !attacking, weapon));
140  }
141 
142  slows = weapon->bool_ability("slow");
143  drains = !opp.get_state("undrainable") && weapon->bool_ability("drains");
144  petrifies = weapon->bool_ability("petrifies");
145  poisons = !opp.get_state("unpoisonable") && weapon->bool_ability("poison") && !opp.get_state(unit::STATE_POISONED);
146  backstab_pos = is_attacker && backstab_check(u_loc, opp_loc, units, resources::gameboard->teams());
147  rounds = weapon->get_special_ability("berserk").highest("value", 1).first;
148 
149  firststrike = weapon->bool_ability("firststrike");
150 
151  {
152  const int distance = distance_between(u_loc, opp_loc);
153  const bool out_of_range = distance > weapon->max_range() || distance < weapon->min_range();
154  disable = weapon->get_special_bool("disable") || out_of_range;
155  }
156 
157  // Handle plague.
158  unit_ability_list plague_specials = weapon->get_specials("plague");
159  unit_ability_list alt_plague_specials = weapon->get_special_ability("plague");
160  if(!alt_plague_specials.empty() && plague_specials.empty()){
161  plague_specials = alt_plague_specials;
162  }
163  plagues = !opp.get_state("unplagueable") && !plague_specials.empty() &&
164  opp.undead_variation() != "null" && !resources::gameboard->map().is_village(opp_loc);
165 
166  if(plagues) {
167  plague_type = (*plague_specials.front().ability_cfg)["type"].str();
168 
169  if(plague_type.empty()) {
170  plague_type = u.type().parent_id();
171  }
172  }
173 
174  // Compute chance to hit.
175  signed int cth = opp.defense_modifier(resources::gameboard->map().get_terrain(opp_loc)) + weapon->accuracy()
176  - (opp_weapon ? opp_weapon->parry() : 0);
177 
178  cth = utils::clamp(cth, 0, 100);
179 
180  unit_ability_list cth_specials = weapon->get_special_ability("chance_to_hit");
181  unit_abilities::effect cth_effects(cth_specials, cth, backstab_pos, weapon);
182  cth = cth_effects.get_composite_value();
183 
184 
185  if(opp.get_state("invulnerable")) {
186  cth = 0;
187  }
188 
189  chance_to_hit = utils::clamp(cth, 0, 100);
190 
191  // Compute base damage done with the weapon.
192  int base_damage = weapon->modified_damage(backstab_pos);
193 
194  // Get the damage multiplier applied to the base damage of the weapon.
195  int damage_multiplier = 100;
196 
197  // Time of day bonus.
198  damage_multiplier += combat_modifier(
199  resources::gameboard->units(), resources::gameboard->map(), u_loc, u.alignment(), u.is_fearless());
200 
201  // Leadership bonus.
202  int leader_bonus = under_leadership(u, u_loc, weapon, opp_weapon);
203  if(leader_bonus != 0) {
204  damage_multiplier += leader_bonus;
205  }
206 
207  // Resistance modifier.
208  damage_multiplier *= opp.damage_from(*weapon, !attacking, opp_loc, opp_weapon);
209 
210  // Compute both the normal and slowed damage.
211  damage = round_damage(base_damage, damage_multiplier, 10000);
212  slow_damage = round_damage(base_damage, damage_multiplier, 20000);
213 
214  if(is_slowed) {
216  }
217 
218  // Compute drain amounts only if draining is possible.
219  if(drains) {
220  unit_ability_list drain_specials = weapon->get_special_ability("drains");
221  // Compute the drain percent (with 50% as the base for backward compatibility)
222  unit_abilities::effect drain_percent_effects(drain_specials, 50, backstab_pos, weapon);
223  drain_percent = drain_percent_effects.get_composite_value();
224  }
225 
226  // Add heal_on_hit (the drain constant)
227  unit_ability_list heal_on_hit_specials = weapon->get_special_ability("heal_on_hit");
228  unit_abilities::effect heal_on_hit_effects(heal_on_hit_specials, 0, backstab_pos, weapon);
229  drain_constant += heal_on_hit_effects.get_composite_value();
230 
232 
233  // Compute the number of blows and handle swarm.
234  weapon->modified_attacks(backstab_pos, swarm_min, swarm_max);
237 }
238 
240  const_attack_ptr att_weapon,
241  bool attacking,
242  const unit_type* opp_type,
243  const_attack_ptr opp_weapon,
244  unsigned int opp_terrain_defense,
245  int lawful_bonus)
246  : weapon(att_weapon)
247  , attack_num(-2) // This is and stays invalid. Always use weapon when using this constructor.
248  , is_attacker(attacking)
249  , is_poisoned(false)
250  , is_slowed(false)
251  , slows(false)
252  , drains(false)
253  , petrifies(false)
254  , plagues(false)
255  , poisons(false)
256  , backstab_pos(false)
257  , swarm(false)
258  , firststrike(false)
259  , disable(false)
260  , experience(0)
261  , max_experience(0)
262  , level(0)
263  , rounds(1)
264  , hp(0)
265  , max_hp(0)
266  , chance_to_hit(0)
267  , damage(0)
268  , slow_damage(0)
269  , drain_percent(0)
270  , drain_constant(0)
271  , num_blows(0)
272  , swarm_min(0)
273  , swarm_max(0)
274  , plague_type()
275 {
276  if(!u_type || !opp_type) {
277  return;
278  }
279 
280  // Get the current state of the unit.
281  if(u_type->hitpoints() < 0) {
282  hp = 0;
283  } else {
284  hp = u_type->hitpoints();
285  }
286 
287  max_experience = u_type->experience_needed();
288  level = (u_type->level());
289  max_hp = (u_type->hitpoints());
290 
291  // Exit if no weapon.
292  if(!weapon) {
293  return;
294  }
295 
296  // Get the weapon characteristics as appropriate.
297  auto ctx = weapon->specials_context(*u_type, map_location::null_location(), attacking);
298  boost::optional<decltype(ctx)> opp_ctx;
299 
300  if(opp_weapon) {
301  opp_ctx.emplace(opp_weapon->specials_context(*opp_type, map_location::null_location(), !attacking));
302  }
303 
304  slows = weapon->get_special_bool("slow");
305  drains = !opp_type->musthave_status("undrainable") && weapon->get_special_bool("drains");
306  petrifies = weapon->get_special_bool("petrifies");
307  poisons = !opp_type->musthave_status("unpoisonable") && weapon->get_special_bool("poison");
308  rounds = weapon->get_specials("berserk").highest("value", 1).first;
309  firststrike = weapon->get_special_bool("firststrike");
310  disable = weapon->get_special_bool("disable");
311 
312  unit_ability_list plague_specials = weapon->get_specials("plague");
313  plagues = !opp_type->musthave_status("unplagueable") && !plague_specials.empty() &&
314  opp_type->undead_variation() != "null";
315 
316  if(plagues) {
317  plague_type = (*plague_specials.front().ability_cfg)["type"].str();
318  if(plague_type.empty()) {
319  plague_type = u_type->parent_id();
320  }
321  }
322 
323  signed int cth = 100 - opp_terrain_defense + weapon->accuracy() - (opp_weapon ? opp_weapon->parry() : 0);
324  cth = utils::clamp(cth, 0, 100);
325 
326  unit_ability_list cth_specials = weapon->get_specials("chance_to_hit");
327  unit_abilities::effect cth_effects(cth_specials, cth, backstab_pos, weapon);
328  cth = cth_effects.get_composite_value();
329 
330  chance_to_hit = utils::clamp(cth, 0, 100);
331 
332  int base_damage = weapon->modified_damage(backstab_pos);
333  int damage_multiplier = 100;
334  damage_multiplier
335  += generic_combat_modifier(lawful_bonus, u_type->alignment(), u_type->musthave_status("fearless"), 0);
336  damage_multiplier *= opp_type->resistance_against(weapon->type(), !attacking);
337 
338  damage = round_damage(base_damage, damage_multiplier, 10000);
339  slow_damage = round_damage(base_damage, damage_multiplier, 20000);
340 
341  if(drains) {
342  unit_ability_list drain_specials = weapon->get_specials("drains");
343 
344  // Compute the drain percent (with 50% as the base for backward compatibility)
345  unit_abilities::effect drain_percent_effects(drain_specials, 50, backstab_pos, weapon);
346  drain_percent = drain_percent_effects.get_composite_value();
347  }
348 
349  // Add heal_on_hit (the drain constant)
350  unit_ability_list heal_on_hit_specials = weapon->get_specials("heal_on_hit");
351  unit_abilities::effect heal_on_hit_effects(heal_on_hit_specials, 0, backstab_pos, weapon);
352  drain_constant += heal_on_hit_effects.get_composite_value();
353 
355 
356  // Compute the number of blows and handle swarm.
357  weapon->modified_attacks(backstab_pos, swarm_min, swarm_max);
360 }
361 
362 
363 // ==================================================================================
364 // BATTLE CONTEXT
365 // ==================================================================================
366 
368  const unit& attacker,
369  const map_location& a_loc,
370  int a_wep_index,
371  const unit& defender,
372  const map_location& d_loc,
373  int d_wep_index,
374  const unit_map& units)
375  : attacker_stats_()
376  , defender_stats_()
377  , attacker_combatant_()
378  , defender_combatant_()
379 {
380  size_t a_wep_uindex = static_cast<size_t>(a_wep_index);
381  size_t d_wep_uindex = static_cast<size_t>(d_wep_index);
382 
383  const_attack_ptr a_wep(a_wep_uindex < attacker.attacks().size() ? attacker.attacks()[a_wep_index].shared_from_this() : nullptr);
384  const_attack_ptr d_wep(d_wep_uindex < defender.attacks().size() ? defender.attacks()[d_wep_index].shared_from_this() : nullptr);
385 
386  attacker_stats_.reset(new battle_context_unit_stats(attacker, a_loc, a_wep_index, true , defender, d_loc, d_wep, units));
387  defender_stats_.reset(new battle_context_unit_stats(defender, d_loc, d_wep_index, false, attacker, a_loc, a_wep, units));
388 }
389 
390 void battle_context::simulate(const combatant* prev_def)
391 {
392  assert((attacker_combatant_.get() != nullptr) == (defender_combatant_.get() != nullptr));
393  assert(attacker_stats_);
394  assert(defender_stats_);
395  if(!attacker_combatant_) {
397  defender_combatant_.reset(new combatant(*defender_stats_, prev_def));
399  }
400 }
401 
402 // more like a factory method than a constructor, always calls one of the other constructors.
404  const map_location& attacker_loc,
405  const map_location& defender_loc,
406  int attacker_weapon,
407  int defender_weapon,
408  double aggression,
409  const combatant* prev_def,
410  const unit* attacker_ptr,
411  const unit* defender_ptr)
412  : attacker_stats_(nullptr)
413  , defender_stats_(nullptr)
414  , attacker_combatant_(nullptr)
415  , defender_combatant_(nullptr)
416 {
417  //TODO: maybe check before dereferencing units.find(attacker_loc),units.find(defender_loc) ?
418  const unit& attacker = attacker_ptr ? *attacker_ptr : *units.find(attacker_loc);
419  const unit& defender = defender_ptr ? *defender_ptr : *units.find(defender_loc);
420  const double harm_weight = 1.0 - aggression;
421 
422  if(attacker_weapon == -1) {
423  *this = choose_attacker_weapon(
424  attacker, defender, units, attacker_loc, defender_loc, harm_weight, prev_def
425  );
426  }
427  else if(defender_weapon == -1) {
428  *this = choose_defender_weapon(
429  attacker, defender, attacker_weapon, units, attacker_loc, defender_loc, prev_def
430  );
431  }
432  else {
433  *this = battle_context(attacker, attacker_loc, attacker_weapon, defender, defender_loc, defender_weapon, units);
434  }
435 
436  assert(attacker_stats_);
437  assert(defender_stats_);
438 }
439 
443  , attacker_combatant_(nullptr)
444  , defender_combatant_(nullptr)
445 {
446 }
447 
448 
449 /** @todo FIXME: better to initialize combatant initially (move into
450  battle_context_unit_stats?), just do fight() when required. */
452 {
453  // We calculate this lazily, since AI doesn't always need it.
454  simulate(prev_def);
455  return *attacker_combatant_;
456 }
457 
459 {
460  // We calculate this lazily, since AI doesn't always need it.
461  simulate(prev_def);
462  return *defender_combatant_;
463 }
464 
465 // Given this harm_weight, are we better than that other context?
466 bool battle_context::better_attack(class battle_context& that, double harm_weight)
467 {
468  return better_combat(
471  that.get_attacker_combatant(),
472  that.get_defender_combatant(),
473  harm_weight
474  );
475 }
476 
477 // Given this harm_weight, are we better than that other context?
478 bool battle_context::better_defense(class battle_context& that, double harm_weight)
479 {
480  return better_combat(
483  that.get_defender_combatant(),
484  that.get_attacker_combatant(),
485  harm_weight
486  );
487 }
488 
489 // Does combat A give us a better result than combat B?
491  const combatant& them_a,
492  const combatant& us_b,
493  const combatant& them_b,
494  double harm_weight)
495 {
496  double a, b;
497 
498  // Compare: P(we kill them) - P(they kill us).
499  a = them_a.hp_dist[0] - us_a.hp_dist[0] * harm_weight;
500  b = them_b.hp_dist[0] - us_b.hp_dist[0] * harm_weight;
501 
502  if(a - b < -0.01) {
503  return false;
504  }
505 
506  if(a - b > 0.01) {
507  return true;
508  }
509 
510  // Add poison to calculations
511  double poison_a_us = (us_a.poisoned) * game_config::poison_amount;
512  double poison_a_them = (them_a.poisoned) * game_config::poison_amount;
513  double poison_b_us = (us_b.poisoned) * game_config::poison_amount;
514  double poison_b_them = (them_b.poisoned) * game_config::poison_amount;
515 
516  // Compare: damage to them - damage to us (average_hp replaces -damage)
517  a = (us_a.average_hp() - poison_a_us) * harm_weight - (them_a.average_hp() - poison_a_them);
518  b = (us_b.average_hp() - poison_b_us) * harm_weight - (them_b.average_hp() - poison_b_them);
519 
520  if(a - b < -0.01) {
521  return false;
522  }
523 
524  if(a - b > 0.01) {
525  return true;
526  }
527 
528  // All else equal: go for most damage.
529  return them_a.average_hp() < them_b.average_hp();
530 }
531 
533  const unit& defender,
534  const unit_map& units,
535  const map_location& attacker_loc,
536  const map_location& defender_loc,
537  double harm_weight,
538  const combatant* prev_def)
539 {
540  log_scope2(log_attack, "choose_attacker_weapon");
541  std::vector<battle_context> choices;
542 
543  // What options does attacker have?
544  for(size_t i = 0; i < attacker.attacks().size(); ++i) {
545  const attack_type& att = attacker.attacks()[i];
546 
547  if(att.attack_weight() <= 0) {
548  continue;
549  }
550  battle_context bc = choose_defender_weapon(attacker, defender, i, units, attacker_loc, defender_loc, prev_def);
551  //choose_defender_weapon will always choose the weapon that disabels the attackers weapon if possible.
552  if(bc.attacker_stats_->disable) {
553  continue;
554  }
555  choices.emplace_back(std::move(bc));
556  }
557 
558  if(choices.empty()) {
559  return battle_context(attacker, attacker_loc, -1, defender, defender_loc, -1, units);
560  }
561 
562  if(choices.size() == 1) {
563  return std::move(choices[0]);
564  }
565 
566  // Multiple options: simulate them, save best.
567  battle_context* best_choice = nullptr;
568  for(auto& choice : choices) {
569  // If choose_defender_weapon didn't simulate, do so now.
570  choice.simulate(prev_def);
571 
572  if(!best_choice || choice.better_attack(*best_choice, harm_weight)) {
573  best_choice = &choice;
574  }
575  }
576 
577  if(best_choice) {
578  return std::move(*best_choice);
579  }
580  else {
581  return battle_context(attacker, attacker_loc, -1, defender, defender_loc, -1, units);
582  }
583 }
584 
585 /** @todo FIXME: Hand previous defender unit in here. */
587  const unit& defender,
588  unsigned attacker_weapon,
589  const unit_map& units,
590  const map_location& attacker_loc,
591  const map_location& defender_loc,
592  const combatant* prev_def)
593 {
594  log_scope2(log_attack, "choose_defender_weapon");
595  VALIDATE(attacker_weapon < attacker.attacks().size(), _("An invalid attacker weapon got selected."));
596 
597  const attack_type& att = attacker.attacks()[attacker_weapon];
598  auto no_weapon = [&]() { return battle_context(attacker, attacker_loc, attacker_weapon, defender, defender_loc, -1, units); };
599  std::vector<battle_context> choices;
600 
601  // What options does defender have?
602  for(size_t i = 0; i < defender.attacks().size(); ++i) {
603  const attack_type& def = defender.attacks()[i];
604  if(def.range() != att.range() || def.defense_weight() <= 0) {
605  //no need to calculate the battle_context here.
606  continue;
607  }
608  battle_context bc(attacker, attacker_loc, attacker_weapon, defender, defender_loc, i, units);
609 
610  if(bc.defender_stats_->disable) {
611  continue;
612  }
613  if(bc.attacker_stats_->disable) {
614  //the defenders attack disables the attakers attack: always choose this one.
615  return bc;
616  }
617  choices.emplace_back(std::move(bc));
618  }
619 
620  if(choices.empty()) {
621  return no_weapon();
622  }
623 
624  if(choices.size() == 1) {
625  //only one usable weapon, don't simulate
626  return std::move(choices[0]);
627  }
628 
629  // Multiple options:
630  // First pass : get the best weight and the minimum simple rating for this weight.
631  // simple rating = number of blows * damage per blows (resistance taken in account) * cth * weight
632  // Eligible attacks for defense should have a simple rating greater or equal to this weight.
633 
634  int min_rating = 0;
635  {
636  double max_weight = 0.0;
637 
638  for(const auto& choice : choices) {
639  const attack_type& def = defender.attacks()[choice.defender_stats_->attack_num];
640 
641  if(def.defense_weight() >= max_weight) {
642  const battle_context_unit_stats& def_stats = *choice.defender_stats_;
643 
644  max_weight = def.defense_weight();
645  int rating = static_cast<int>(
646  def_stats.num_blows * def_stats.damage * def_stats.chance_to_hit * def.defense_weight());
647 
648  if(def.defense_weight() > max_weight || rating < min_rating) {
649  min_rating = rating;
650  }
651  }
652  }
653  }
654 
655  battle_context* best_choice = nullptr;
656  // Multiple options: simulate them, save best.
657  for(auto& choice : choices) {
658  const attack_type& def = defender.attacks()[choice.defender_stats_->attack_num];
659 
660  choice.simulate(prev_def);
661 
662 
663  int simple_rating = static_cast<int>(
664  choice.defender_stats_->num_blows * choice.defender_stats_->damage * choice.defender_stats_->chance_to_hit * def.defense_weight());
665 
666  //FIXME: make sure there is no mostake in the better_combat call-
667  if(simple_rating >= min_rating && (!best_choice || choice.better_defense(*best_choice, 1.0))) {
668  best_choice = &choice;
669  }
670  }
671 
672  return best_choice ? std::move(*best_choice) : no_weapon();
673 }
674 
675 
676 // ==================================================================================
677 // HELPERS
678 // ==================================================================================
679 
680 namespace
681 {
682 void refresh_weapon_index(int& weap_index, const std::string& weap_id, attack_itors attacks)
683 {
684  // No attacks to choose from.
685  if(attacks.empty()) {
686  weap_index = -1;
687  return;
688  }
689 
690  // The currently selected attack fits.
691  if(weap_index >= 0 && weap_index < static_cast<int>(attacks.size()) && attacks[weap_index].id() == weap_id) {
692  return;
693  }
694 
695  // Look up the weapon by id.
696  if(!weap_id.empty()) {
697  for(int i = 0; i < static_cast<int>(attacks.size()); ++i) {
698  if(attacks[i].id() == weap_id) {
699  weap_index = i;
700  return;
701  }
702  }
703  }
704 
705  // Lookup has failed.
706  weap_index = -1;
707  return;
708 }
709 
710 /** Helper class for performing an attack. */
711 class attack
712 {
713 public:
714  attack(const map_location& attacker,
715  const map_location& defender,
716  int attack_with,
717  int defend_with,
718  bool update_display = true);
719 
720  void perform();
721 
722 private:
723  class attack_end_exception
724  {
725  };
726 
727  bool perform_hit(bool, statistics::attack_context&);
728  void fire_event(const std::string& n);
729  void refresh_bc();
730 
731  /** Structure holding unit info used in the attack action. */
732  struct unit_info
733  {
734  const map_location loc_;
735  int weapon_;
736  unit_map& units_;
737  std::size_t id_; /**< unit.underlying_id() */
738  std::string weap_id_;
739  int orig_attacks_;
740  int n_attacks_; /**< Number of attacks left. */
741  int cth_;
742  int damage_;
743  int xp_;
744 
745  unit_info(const map_location& loc, int weapon, unit_map& units);
746  unit& get_unit();
747  bool valid();
748 
749  std::string dump();
750  };
751 
752  /**
753  * Used in perform_hit to confirm a replay is in sync.
754  * Check OOS_error_ after this method, true if error detected.
755  */
756  void check_replay_attack_result(bool&, int, int&, config, unit_info&);
757 
758  void unit_killed(
759  unit_info&, unit_info&, const battle_context_unit_stats*&, const battle_context_unit_stats*&, bool);
760 
761  std::unique_ptr<battle_context> bc_;
762 
763  const battle_context_unit_stats* a_stats_;
764  const battle_context_unit_stats* d_stats_;
765 
766  int abs_n_attack_, abs_n_defend_;
767  // update_att_fog_ is not used, other than making some code simpler.
768  bool update_att_fog_, update_def_fog_, update_minimap_;
769 
770  unit_info a_, d_;
771  unit_map& units_;
772  std::ostringstream errbuf_;
773 
774  bool update_display_;
775  bool OOS_error_;
776 
777  bool use_prng_;
778 
779  std::vector<bool> prng_attacker_;
780  std::vector<bool> prng_defender_;
781 };
782 
783 attack::unit_info::unit_info(const map_location& loc, int weapon, unit_map& units)
784  : loc_(loc)
785  , weapon_(weapon)
786  , units_(units)
787  , id_()
788  , weap_id_()
789  , orig_attacks_(0)
790  , n_attacks_(0)
791  , cth_(0)
792  , damage_(0)
793  , xp_(0)
794 {
795  unit_map::iterator i = units_.find(loc_);
796  if(!i.valid()) {
797  return;
798  }
799 
800  id_ = i->underlying_id();
801 }
802 
803 unit& attack::unit_info::get_unit()
804 {
805  unit_map::iterator i = units_.find(loc_);
806  assert(i.valid() && i->underlying_id() == id_);
807  return *i;
808 }
809 
810 bool attack::unit_info::valid()
811 {
812  unit_map::iterator i = units_.find(loc_);
813  return i.valid() && i->underlying_id() == id_;
814 }
815 
816 std::string attack::unit_info::dump()
817 {
818  std::stringstream s;
819  s << get_unit().type_id() << " (" << loc_.wml_x() << ',' << loc_.wml_y() << ')';
820  return s.str();
821 }
822 
823 attack::attack(const map_location& attacker,
824  const map_location& defender,
825  int attack_with,
826  int defend_with,
827  bool update_display)
828  : bc_(nullptr)
829  , a_stats_(nullptr)
830  , d_stats_(nullptr)
831  , abs_n_attack_(0)
832  , abs_n_defend_(0)
833  , update_att_fog_(false)
834  , update_def_fog_(false)
835  , update_minimap_(false)
836  , a_(attacker, attack_with, resources::gameboard->units())
837  , d_(defender, defend_with, resources::gameboard->units())
838  , units_(resources::gameboard->units())
839  , errbuf_()
840  , update_display_(update_display)
841  , OOS_error_(false)
842 
843  //new experimental prng mode.
844  , use_prng_(preferences::get("use_prng") == "yes" && randomness::generator->is_networked() == false)
845 {
846  if(use_prng_) {
847  std::cerr << "Using experimental PRNG for combat\n";
848  }
849 }
850 
851 void attack::fire_event(const std::string& n)
852 {
853  LOG_NG << "attack: firing '" << n << "' event\n";
854 
855  // prepare the event data for weapon filtering
856  config ev_data;
857  config& a_weapon_cfg = ev_data.add_child("first");
858  config& d_weapon_cfg = ev_data.add_child("second");
859 
860  // Need these to ensure weapon filters work correctly
861  boost::optional<attack_type::specials_context_t> a_ctx, d_ctx;
862 
863  if(a_stats_->weapon != nullptr && a_.valid()) {
864  if(d_stats_->weapon != nullptr && d_.valid()) {
865  a_ctx.emplace(a_stats_->weapon->specials_context(nullptr, nullptr, a_.loc_, d_.loc_, true, d_stats_->weapon));
866  } else {
867  a_ctx.emplace(a_stats_->weapon->specials_context(nullptr, a_.loc_, true));
868  }
869  a_stats_->weapon->write(a_weapon_cfg);
870  }
871 
872  if(d_stats_->weapon != nullptr && d_.valid()) {
873  if(a_stats_->weapon != nullptr && a_.valid()) {
874  d_ctx.emplace(d_stats_->weapon->specials_context(nullptr, nullptr, d_.loc_, a_.loc_, false, a_stats_->weapon));
875  } else {
876  d_ctx.emplace(d_stats_->weapon->specials_context(nullptr, d_.loc_, false));
877  }
878  d_stats_->weapon->write(d_weapon_cfg);
879  }
880 
881  if(a_weapon_cfg["name"].empty()) {
882  a_weapon_cfg["name"] = "none";
883  }
884 
885  if(d_weapon_cfg["name"].empty()) {
886  d_weapon_cfg["name"] = "none";
887  }
888 
889  if(n == "attack_end") {
890  // We want to fire attack_end event in any case! Even if one of units was removed by WML.
891  resources::game_events->pump().fire(n, a_.loc_, d_.loc_, ev_data);
892  return;
893  }
894 
895  // damage_inflicted is set in these two events.
896  // TODO: should we set this value from unit_info::damage, or continue using the WML variable?
897  if(n == "attacker_hits" || n == "defender_hits") {
898  ev_data["damage_inflicted"] = resources::gamedata->get_variable("damage_inflicted");
899  }
900 
901  const int defender_side = d_.get_unit().side();
902 
903  bool wml_aborted;
904  std::tie(std::ignore, wml_aborted) = resources::game_events->pump().fire(n,
906  game_events::entity_location(d_.loc_, d_.id_), ev_data);
907 
908  // The event could have killed either the attacker or
909  // defender, so we have to make sure they still exist.
910  refresh_bc();
911 
912  if(wml_aborted || !a_.valid() || !d_.valid()
913  || !resources::gameboard->get_team(a_.get_unit().side()).is_enemy(d_.get_unit().side())
914  ) {
915  actions::recalculate_fog(defender_side);
916 
917  if(update_display_) {
919  }
920 
921  fire_event("attack_end");
922  throw attack_end_exception();
923  }
924 }
925 
926 void attack::refresh_bc()
927 {
928  // Fix index of weapons.
929  if(a_.valid()) {
930  refresh_weapon_index(a_.weapon_, a_.weap_id_, a_.get_unit().attacks());
931  }
932 
933  if(d_.valid()) {
934  refresh_weapon_index(d_.weapon_, d_.weap_id_, d_.get_unit().attacks());
935  }
936 
937  if(!a_.valid() || !d_.valid()) {
938  // Fix pointer to weapons.
939  const_cast<battle_context_unit_stats*>(a_stats_)->weapon
940  = a_.valid() && a_.weapon_ >= 0 ? a_.get_unit().attacks()[a_.weapon_].shared_from_this() : nullptr;
941 
942  const_cast<battle_context_unit_stats*>(d_stats_)->weapon
943  = d_.valid() && d_.weapon_ >= 0 ? d_.get_unit().attacks()[d_.weapon_].shared_from_this() : nullptr;
944 
945  return;
946  }
947 
948  bc_.reset(new battle_context(units_, a_.loc_, d_.loc_, a_.weapon_, d_.weapon_));
949 
950  a_stats_ = &bc_->get_attacker_stats();
951  d_stats_ = &bc_->get_defender_stats();
952 
953  a_.cth_ = a_stats_->chance_to_hit;
954  d_.cth_ = d_stats_->chance_to_hit;
955  a_.damage_ = a_stats_->damage;
956  d_.damage_ = d_stats_->damage;
957 }
958 
959 bool attack::perform_hit(bool attacker_turn, statistics::attack_context& stats)
960 {
961  unit_info& attacker = attacker_turn ? a_ : d_;
962  unit_info& defender = attacker_turn ? d_ : a_;
963 
964  // NOTE: we need to use a reference-to-pointer here so a_stats_ and d_stats_ can be
965  // modified without. Using a pointer directly would render them invalid when that happened.
966  const battle_context_unit_stats*& attacker_stats = attacker_turn ? a_stats_ : d_stats_;
967  const battle_context_unit_stats*& defender_stats = attacker_turn ? d_stats_ : a_stats_;
968 
969  int& abs_n = attacker_turn ? abs_n_attack_ : abs_n_defend_;
970  bool& update_fog = attacker_turn ? update_def_fog_ : update_att_fog_;
971 
972  int ran_num;
973 
974  if(use_prng_) {
975 
976  std::vector<bool>& prng_seq = attacker_turn ? prng_attacker_ : prng_defender_;
977 
978  if(prng_seq.empty()) {
979  const int ntotal = attacker.cth_*attacker.n_attacks_;
980  int num_hits = ntotal/100;
981  const int additional_hit_chance = ntotal%100;
982  if(additional_hit_chance > 0 && randomness::generator->get_random_int(0, 99) < additional_hit_chance) {
983  ++num_hits;
984  }
985 
986  std::vector<int> indexes;
987  for(int i = 0; i != attacker.n_attacks_; ++i) {
988  prng_seq.push_back(false);
989  indexes.push_back(i);
990  }
991 
992  for(int i = 0; i != num_hits; ++i) {
993  int n = randomness::generator->get_random_int(0, static_cast<int>(indexes.size())-1);
994  prng_seq[indexes[n]] = true;
995  indexes.erase(indexes.begin() + n);
996  }
997  }
998 
999  bool does_hit = prng_seq.back();
1000  prng_seq.pop_back();
1001  ran_num = does_hit ? 0 : 99;
1002  } else {
1003  ran_num = randomness::generator->get_random_int(0, 99);
1004  }
1005  bool hits = (ran_num < attacker.cth_);
1006 
1007  int damage = 0;
1008  if(hits) {
1009  damage = attacker.damage_;
1010  resources::gamedata->get_variable("damage_inflicted") = damage;
1011  }
1012 
1013  // Make sure that if we're serializing a game here,
1014  // we got the same results as the game did originally.
1015  const config local_results {"chance", attacker.cth_, "hits", hits, "damage", damage};
1016 
1017  config replay_results;
1018  bool equals_replay = checkup_instance->local_checkup(local_results, replay_results);
1019 
1020  if(!equals_replay) {
1021  check_replay_attack_result(hits, ran_num, damage, replay_results, attacker);
1022  }
1023 
1024  // can do no more damage than the defender has hitpoints
1025  int damage_done = std::min<int>(defender.get_unit().hitpoints(), attacker.damage_);
1026 
1027  // expected damage = damage potential * chance to hit (as a percentage)
1028  double expected_damage = damage_done * attacker.cth_ * 0.01;
1029 
1030  if(attacker_turn) {
1031  stats.attack_expected_damage(expected_damage, 0);
1032  } else {
1033  stats.attack_expected_damage(0, expected_damage);
1034  }
1035 
1036  int drains_damage = 0;
1037  if(hits && attacker_stats->drains) {
1038  drains_damage = damage_done * attacker_stats->drain_percent / 100 + attacker_stats->drain_constant;
1039 
1040  // don't drain so much that the attacker gets more than his maximum hitpoints
1041  drains_damage =
1042  std::min<int>(drains_damage, attacker.get_unit().max_hitpoints() - attacker.get_unit().hitpoints());
1043 
1044  // if drain is negative, don't allow drain to kill the attacker
1045  drains_damage = std::max<int>(drains_damage, 1 - attacker.get_unit().hitpoints());
1046  }
1047 
1048  if(update_display_) {
1049  std::ostringstream float_text;
1050  std::vector<std::string> extra_hit_sounds;
1051 
1052  if(hits) {
1053  const unit& defender_unit = defender.get_unit();
1054  if(attacker_stats->poisons && !defender_unit.get_state(unit::STATE_POISONED)) {
1055  float_text << (defender_unit.gender() == unit_race::FEMALE ? _("female^poisoned") : _("poisoned"))
1056  << '\n';
1057 
1058  extra_hit_sounds.push_back(game_config::sounds::status::poisoned);
1059  }
1060 
1061  if(attacker_stats->slows && !defender_unit.get_state(unit::STATE_SLOWED)) {
1062  float_text << (defender_unit.gender() == unit_race::FEMALE ? _("female^slowed") : _("slowed")) << '\n';
1063 
1064  extra_hit_sounds.push_back(game_config::sounds::status::slowed);
1065  }
1066 
1067  if(attacker_stats->petrifies) {
1068  float_text << (defender_unit.gender() == unit_race::FEMALE ? _("female^petrified") : _("petrified"))
1069  << '\n';
1070 
1071  extra_hit_sounds.push_back(game_config::sounds::status::petrified);
1072  }
1073  }
1074 
1078  attacker.loc_, defender.loc_,
1079  damage,
1080  *attacker_stats->weapon, defender_stats->weapon,
1081  abs_n, float_text.str(), drains_damage, "",
1082  &extra_hit_sounds
1083  );
1084  }
1085 
1086  bool dies = defender.get_unit().take_hit(damage);
1087  LOG_NG << "defender took " << damage << (dies ? " and died\n" : "\n");
1088 
1089  if(attacker_turn) {
1090  stats.attack_result(hits
1091  ? (dies
1095  attacker.cth_, damage_done, drains_damage
1096  );
1097  } else {
1098  stats.defend_result(hits
1099  ? (dies
1103  attacker.cth_, damage_done, drains_damage
1104  );
1105  }
1106 
1107  replay_results.clear();
1108 
1109  // There was also a attribute cfg["unit_hit"] which was never used so i deleted.
1110  equals_replay = checkup_instance->local_checkup(config{"dies", dies}, replay_results);
1111 
1112  if(!equals_replay) {
1113  bool results_dies = replay_results["dies"].to_bool();
1114 
1115  errbuf_ << "SYNC: In attack " << a_.dump() << " vs " << d_.dump() << ": the data source says the "
1116  << (attacker_turn ? "defender" : "attacker") << ' ' << (results_dies ? "perished" : "survived")
1117  << " while in-game calculations show it " << (dies ? "perished" : "survived")
1118  << " (over-riding game calculations with data source results)\n";
1119 
1120  dies = results_dies;
1121 
1122  // Set hitpoints to 0 so later checks don't invalidate the death.
1123  if(results_dies) {
1124  defender.get_unit().set_hitpoints(0);
1125  }
1126 
1127  OOS_error_ = true;
1128  }
1129 
1130  if(hits) {
1131  try {
1132  fire_event(attacker_turn ? "attacker_hits" : "defender_hits");
1133  } catch(const attack_end_exception&) {
1134  refresh_bc();
1135  return false;
1136  }
1137  } else {
1138  try {
1139  fire_event(attacker_turn ? "attacker_misses" : "defender_misses");
1140  } catch(const attack_end_exception&) {
1141  refresh_bc();
1142  return false;
1143  }
1144  }
1145 
1146  refresh_bc();
1147 
1148  bool attacker_dies = false;
1149 
1150  if(drains_damage > 0) {
1151  attacker.get_unit().heal(drains_damage);
1152  } else if(drains_damage < 0) {
1153  attacker_dies = attacker.get_unit().take_hit(-drains_damage);
1154  }
1155 
1156  if(dies) {
1157  unit_killed(attacker, defender, attacker_stats, defender_stats, false);
1158  update_fog = true;
1159  }
1160 
1161  if(attacker_dies) {
1162  unit_killed(defender, attacker, defender_stats, attacker_stats, true);
1163  (attacker_turn ? update_att_fog_ : update_def_fog_) = true;
1164  }
1165 
1166  if(dies) {
1167  update_minimap_ = true;
1168  return false;
1169  }
1170 
1171  if(hits) {
1172  unit& defender_unit = defender.get_unit();
1173 
1174  if(attacker_stats->poisons && !defender_unit.get_state(unit::STATE_POISONED)) {
1175  defender_unit.set_state(unit::STATE_POISONED, true);
1176  LOG_NG << "defender poisoned\n";
1177  }
1178 
1179  if(attacker_stats->slows && !defender_unit.get_state(unit::STATE_SLOWED)) {
1180  defender_unit.set_state(unit::STATE_SLOWED, true);
1181  update_fog = true;
1182  defender.damage_ = defender_stats->slow_damage;
1183  LOG_NG << "defender slowed\n";
1184  }
1185 
1186  // If the defender is petrified, the fight stops immediately
1187  if(attacker_stats->petrifies) {
1188  defender_unit.set_state(unit::STATE_PETRIFIED, true);
1189  update_fog = true;
1190  attacker.n_attacks_ = 0;
1191  defender.n_attacks_ = -1; // Petrified.
1192  resources::game_events->pump().fire("petrified", defender.loc_, attacker.loc_);
1193  refresh_bc();
1194  }
1195  }
1196 
1197  // Delay until here so that poison and slow go through
1198  if(attacker_dies) {
1199  update_minimap_ = true;
1200  return false;
1201  }
1202 
1203  --attacker.n_attacks_;
1204  return true;
1205 }
1206 
1207 void attack::unit_killed(unit_info& attacker,
1208  unit_info& defender,
1209  const battle_context_unit_stats*& attacker_stats,
1210  const battle_context_unit_stats*& defender_stats,
1211  bool drain_killed)
1212 {
1213  attacker.xp_ = game_config::kill_xp(defender.get_unit().level());
1214  defender.xp_ = 0;
1215 
1216  display::get_singleton()->invalidate(attacker.loc_);
1217 
1218  game_events::entity_location death_loc(defender.loc_, defender.id_);
1219  game_events::entity_location attacker_loc(attacker.loc_, attacker.id_);
1220 
1221  std::string undead_variation = defender.get_unit().undead_variation();
1222 
1223  fire_event("attack_end");
1224  refresh_bc();
1225 
1226  // Get weapon info for last_breath and die events.
1227  config dat;
1228  config a_weapon_cfg = attacker_stats->weapon && attacker.valid() ? attacker_stats->weapon->to_config() : config();
1229  config d_weapon_cfg = defender_stats->weapon && defender.valid() ? defender_stats->weapon->to_config() : config();
1230 
1231  if(a_weapon_cfg["name"].empty()) {
1232  a_weapon_cfg["name"] = "none";
1233  }
1234 
1235  if(d_weapon_cfg["name"].empty()) {
1236  d_weapon_cfg["name"] = "none";
1237  }
1238 
1239  dat.add_child("first", d_weapon_cfg);
1240  dat.add_child("second", a_weapon_cfg);
1241 
1242  resources::game_events->pump().fire("last_breath", death_loc, attacker_loc, dat);
1243  refresh_bc();
1244 
1245  // WML has invalidated the dying unit, abort.
1246  if(!defender.valid() || defender.get_unit().hitpoints() > 0) {
1247  return;
1248  }
1249 
1250  if(!attacker.valid()) {
1252  defender.loc_,
1253  defender.get_unit(),
1254  nullptr,
1255  defender_stats->weapon
1256  );
1257  } else {
1259  defender.loc_,
1260  defender.get_unit(),
1261  attacker_stats->weapon,
1262  defender_stats->weapon,
1263  attacker.loc_,
1264  &attacker.get_unit()
1265  );
1266  }
1267 
1268  resources::game_events->pump().fire("die", death_loc, attacker_loc, dat);
1269  refresh_bc();
1270 
1271  if(!defender.valid() || defender.get_unit().hitpoints() > 0) {
1272  // WML has invalidated the dying unit, abort
1273  return;
1274  }
1275 
1276  units_.erase(defender.loc_);
1277  resources::whiteboard->on_kill_unit();
1278 
1279  // Plague units make new units on the target hex.
1280  if(attacker.valid() && attacker_stats->plagues && !drain_killed) {
1281  LOG_NG << "trying to reanimate " << attacker_stats->plague_type << '\n';
1282 
1283  if(const unit_type* reanimator = unit_types.find(attacker_stats->plague_type)) {
1284  LOG_NG << "found unit type:" << reanimator->id() << '\n';
1285 
1286  unit_ptr newunit = unit::create(*reanimator, attacker.get_unit().side(), true, unit_race::MALE);
1287  newunit->set_attacks(0);
1288  newunit->set_movement(0, true);
1289  newunit->set_facing(map_location::get_opposite_dir(attacker.get_unit().facing()));
1290 
1291  // Apply variation
1292  if(undead_variation != "null") {
1293  config mod;
1294  config& variation = mod.add_child("effect");
1295  variation["apply_to"] = "variation";
1296  variation["name"] = undead_variation;
1297  newunit->add_modification("variation", mod);
1298  newunit->heal_fully();
1299  }
1300 
1301  newunit->set_location(death_loc);
1302  units_.insert(newunit);
1303 
1304  game_events::entity_location reanim_loc(defender.loc_, newunit->underlying_id());
1305  resources::game_events->pump().fire("unit_placed", reanim_loc);
1306 
1307  preferences::encountered_units().insert(newunit->type_id());
1308 
1309  if(update_display_) {
1310  display::get_singleton()->invalidate(death_loc);
1311  }
1312  }
1313  } else {
1314  LOG_NG << "unit not reanimated\n";
1315  }
1316 }
1317 
1318 void attack::perform()
1319 {
1320  // Stop the user from issuing any commands while the units are fighting.
1321  const events::command_disabler disable_commands;
1322 
1323  if(!a_.valid() || !d_.valid()) {
1324  return;
1325  }
1326 
1327  // no attack weapon => stop here and don't attack
1328  if(a_.weapon_ < 0) {
1329  a_.get_unit().set_attacks(a_.get_unit().attacks_left() - 1);
1330  a_.get_unit().set_movement(-1, true);
1331  return;
1332  }
1333 
1334  if(a_.get_unit().attacks_left() <= 0) {
1335  LOG_NG << "attack::perform(): not enough ap.\n";
1336  return;
1337  }
1338 
1339  a_.get_unit().set_facing(a_.loc_.get_relative_dir(d_.loc_));
1340  d_.get_unit().set_facing(d_.loc_.get_relative_dir(a_.loc_));
1341 
1342  a_.get_unit().set_attacks(a_.get_unit().attacks_left() - 1);
1343 
1344  VALIDATE(a_.weapon_ < static_cast<int>(a_.get_unit().attacks().size()),
1345  _("An invalid attacker weapon got selected."));
1346 
1347  a_.get_unit().set_movement(a_.get_unit().movement_left() - a_.get_unit().attacks()[a_.weapon_].movement_used(), true);
1348  a_.get_unit().set_state(unit::STATE_NOT_MOVED, false);
1349  a_.get_unit().set_resting(false);
1350  d_.get_unit().set_resting(false);
1351 
1352  // If the attacker was invisible, she isn't anymore!
1353  a_.get_unit().set_state(unit::STATE_UNCOVERED, true);
1354 
1355  bc_.reset(new battle_context(units_, a_.loc_, d_.loc_, a_.weapon_, d_.weapon_));
1356 
1357  a_stats_ = &bc_->get_attacker_stats();
1358  d_stats_ = &bc_->get_defender_stats();
1359 
1360  if(a_stats_->disable) {
1361  LOG_NG << "attack::perform(): tried to attack with a disabled attack.\n";
1362  return;
1363  }
1364 
1365  if(a_stats_->weapon) {
1366  a_.weap_id_ = a_stats_->weapon->id();
1367  }
1368 
1369  if(d_stats_->weapon) {
1370  d_.weap_id_ = d_stats_->weapon->id();
1371  }
1372 
1373  try {
1374  fire_event("attack");
1375  } catch(const attack_end_exception&) {
1376  return;
1377  }
1378 
1379  refresh_bc();
1380 
1381  DBG_NG << "getting attack statistics\n";
1382  statistics::attack_context attack_stats(
1383  a_.get_unit(), d_.get_unit(), a_stats_->chance_to_hit, d_stats_->chance_to_hit);
1384 
1385  a_.orig_attacks_ = a_stats_->num_blows;
1386  d_.orig_attacks_ = d_stats_->num_blows;
1387  a_.n_attacks_ = a_.orig_attacks_;
1388  d_.n_attacks_ = d_.orig_attacks_;
1389  a_.xp_ = game_config::combat_xp(d_.get_unit().level());
1390  d_.xp_ = game_config::combat_xp(a_.get_unit().level());
1391 
1392  bool defender_strikes_first = (d_stats_->firststrike && !a_stats_->firststrike);
1393  unsigned int rounds = std::max<unsigned int>(a_stats_->rounds, d_stats_->rounds) - 1;
1394  const int defender_side = d_.get_unit().side();
1395 
1396  LOG_NG << "Fight: (" << a_.loc_ << ") vs (" << d_.loc_ << ") ATT: " << a_stats_->weapon->name() << " "
1397  << a_stats_->damage << "-" << a_stats_->num_blows << "(" << a_stats_->chance_to_hit
1398  << "%) vs DEF: " << (d_stats_->weapon ? d_stats_->weapon->name() : "none") << " " << d_stats_->damage << "-"
1399  << d_stats_->num_blows << "(" << d_stats_->chance_to_hit << "%)"
1400  << (defender_strikes_first ? " defender first-strike" : "") << "\n";
1401 
1402  // Play the pre-fight animation
1403  unit_display::unit_draw_weapon(a_.loc_, a_.get_unit(), a_stats_->weapon, d_stats_->weapon, d_.loc_, &d_.get_unit());
1404 
1405  for(;;) {
1406  DBG_NG << "start of attack loop...\n";
1407  ++abs_n_attack_;
1408 
1409  if(a_.n_attacks_ > 0 && !defender_strikes_first) {
1410  if(!perform_hit(true, attack_stats)) {
1411  DBG_NG << "broke from attack loop on attacker turn\n";
1412  break;
1413  }
1414  }
1415 
1416  // If the defender got to strike first, they use it up here.
1417  defender_strikes_first = false;
1418  ++abs_n_defend_;
1419 
1420  if(d_.n_attacks_ > 0) {
1421  if(!perform_hit(false, attack_stats)) {
1422  DBG_NG << "broke from attack loop on defender turn\n";
1423  break;
1424  }
1425  }
1426 
1427  // Continue the fight to death; if one of the units got petrified,
1428  // either n_attacks or n_defends is -1
1429  if(rounds > 0 && d_.n_attacks_ == 0 && a_.n_attacks_ == 0) {
1430  a_.n_attacks_ = a_.orig_attacks_;
1431  d_.n_attacks_ = d_.orig_attacks_;
1432  --rounds;
1433  defender_strikes_first = (d_stats_->firststrike && !a_stats_->firststrike);
1434  }
1435 
1436  if(a_.n_attacks_ <= 0 && d_.n_attacks_ <= 0) {
1437  fire_event("attack_end");
1438  refresh_bc();
1439  break;
1440  }
1441  }
1442 
1443  // Set by attacker_hits and defender_hits events.
1444  resources::gamedata->clear_variable("damage_inflicted");
1445 
1446  if(update_def_fog_) {
1447  actions::recalculate_fog(defender_side);
1448  }
1449 
1450  // TODO: if we knew the viewing team, we could skip this display update
1451  if(update_minimap_ && update_display_) {
1453  }
1454 
1455  if(a_.valid()) {
1456  unit& u = a_.get_unit();
1457  u.anim_comp().set_standing();
1458  u.set_experience(u.experience() + a_.xp_);
1459  }
1460 
1461  if(d_.valid()) {
1462  unit& u = d_.get_unit();
1463  u.anim_comp().set_standing();
1464  u.set_experience(u.experience() + d_.xp_);
1465  }
1466 
1467  unit_display::unit_sheath_weapon(a_.loc_, a_.valid() ? &a_.get_unit() : nullptr, a_stats_->weapon, d_stats_->weapon,
1468  d_.loc_, d_.valid() ? &d_.get_unit() : nullptr);
1469 
1470  if(update_display_) {
1473  display::get_singleton()->invalidate(d_.loc_);
1474  }
1475 
1476  if(OOS_error_) {
1477  replay::process_error(errbuf_.str());
1478  }
1479 }
1480 
1481 void attack::check_replay_attack_result(
1482  bool& hits, int ran_num, int& damage, config replay_results, unit_info& attacker)
1483 {
1484  int results_chance = replay_results["chance"];
1485  bool results_hits = replay_results["hits"].to_bool();
1486  int results_damage = replay_results["damage"];
1487 
1488 #if 0
1489  errbuf_ << "SYNC: In attack " << a_.dump() << " vs " << d_.dump()
1490  << " replay data differs from local calculated data:"
1491  << " chance to hit in data source: " << results_chance
1492  << " chance to hit in calculated: " << attacker.cth_
1493  << " chance to hit in data source: " << results_chance
1494  << " chance to hit in calculated: " << attacker.cth_
1495  ;
1496 
1497  attacker.cth_ = results_chance;
1498  hits = results_hits;
1499  damage = results_damage;
1500 
1501  OOS_error_ = true;
1502 #endif
1503 
1504  if(results_chance != attacker.cth_) {
1505  errbuf_ << "SYNC: In attack " << a_.dump() << " vs " << d_.dump()
1506  << ": chance to hit is inconsistent. Data source: " << results_chance
1507  << "; Calculation: " << attacker.cth_ << " (over-riding game calculations with data source results)\n";
1508  attacker.cth_ = results_chance;
1509  OOS_error_ = true;
1510  }
1511 
1512  if(results_hits != hits) {
1513  errbuf_ << "SYNC: In attack " << a_.dump() << " vs " << d_.dump() << ": the data source says the hit was "
1514  << (results_hits ? "successful" : "unsuccessful") << ", while in-game calculations say the hit was "
1515  << (hits ? "successful" : "unsuccessful") << " random number: " << ran_num << " = " << (ran_num % 100)
1516  << "/" << results_chance << " (over-riding game calculations with data source results)\n";
1517  hits = results_hits;
1518  OOS_error_ = true;
1519  }
1520 
1521  if(results_damage != damage) {
1522  errbuf_ << "SYNC: In attack " << a_.dump() << " vs " << d_.dump() << ": the data source says the hit did "
1523  << results_damage << " damage, while in-game calculations show the hit doing " << damage
1524  << " damage (over-riding game calculations with data source results)\n";
1525  damage = results_damage;
1526  OOS_error_ = true;
1527  }
1528 }
1529 } // end anonymous namespace
1530 
1531 
1532 // ==================================================================================
1533 // FREE-STANDING FUNCTIONS
1534 // ==================================================================================
1535 
1536 void attack_unit(const map_location& attacker,
1537  const map_location& defender,
1538  int attack_with,
1539  int defend_with,
1540  bool update_display)
1541 {
1542  attack dummy(attacker, defender, attack_with, defend_with, update_display);
1543  dummy.perform();
1544 }
1545 
1547  const map_location& defender,
1548  int attack_with,
1549  int defend_with,
1550  bool update_display)
1551 {
1552  attack_unit(attacker, defender, attack_with, defend_with, update_display);
1553 
1555  if(atku != resources::gameboard->units().end()) {
1557  }
1558 
1560  if(defu != resources::gameboard->units().end()) {
1562  }
1563 }
1564 
1565 int under_leadership(const unit &u, const map_location& loc, const_attack_ptr weapon, const_attack_ptr opp_weapon)
1566 {
1567  unit_ability_list abil = u.get_abilities_weapons("leadership", loc, weapon, opp_weapon);
1568  unit_abilities::effect leader_effect(abil, 0, false);
1569  return leader_effect.get_composite_value();
1570 }
1571 
1572 int combat_modifier(const unit_map& units,
1573  const gamemap& map,
1574  const map_location& loc,
1575  unit_type::ALIGNMENT alignment,
1576  bool is_fearless)
1577 {
1578  const tod_manager& tod_m = *resources::tod_manager;
1579  const time_of_day& effective_tod = tod_m.get_illuminated_time_of_day(units, map, loc);
1580  return combat_modifier(effective_tod, alignment, is_fearless);
1581 }
1582 
1583 int combat_modifier(const time_of_day& effective_tod,
1584  unit_type::ALIGNMENT alignment,
1585  bool is_fearless)
1586 {
1587  const tod_manager& tod_m = *resources::tod_manager;
1588  const int lawful_bonus = effective_tod.lawful_bonus;
1589  return generic_combat_modifier(lawful_bonus, alignment, is_fearless, tod_m.get_max_liminal_bonus());
1590 }
1591 
1592 int generic_combat_modifier(int lawful_bonus, unit_type::ALIGNMENT alignment, bool is_fearless, int max_liminal_bonus)
1593 {
1594  int bonus;
1595 
1596  switch(alignment.v) {
1597  case unit_type::ALIGNMENT::LAWFUL:
1598  bonus = lawful_bonus;
1599  break;
1600  case unit_type::ALIGNMENT::NEUTRAL:
1601  bonus = 0;
1602  break;
1603  case unit_type::ALIGNMENT::CHAOTIC:
1604  bonus = -lawful_bonus;
1605  break;
1606  case unit_type::ALIGNMENT::LIMINAL:
1607  bonus = std::max(0, max_liminal_bonus-std::abs(lawful_bonus));
1608  break;
1609  default:
1610  bonus = 0;
1611  }
1612 
1613  if(is_fearless) {
1614  bonus = std::max<int>(bonus, 0);
1615  }
1616 
1617  return bonus;
1618 }
1619 
1620 bool backstab_check(const map_location& attacker_loc,
1621  const map_location& defender_loc,
1622  const unit_map& units,
1623  const std::vector<team>& teams)
1624 {
1625  const unit_map::const_iterator defender = units.find(defender_loc);
1626  if(defender == units.end()) {
1627  return false; // No defender
1628  }
1629 
1631  get_adjacent_tiles(defender_loc, adj.data());
1632 
1633  unsigned i;
1634 
1635  for(i = 0; i < adj.size(); ++i) {
1636  if(adj[i] == attacker_loc) {
1637  break;
1638  }
1639  }
1640 
1641  if(i >= 6) {
1642  return false; // Attack not from adjacent location
1643  }
1644 
1645  const unit_map::const_iterator opp = units.find(adj[(i + 3) % 6]);
1646 
1647  // No opposite unit.
1648  if(opp == units.end()) {
1649  return false;
1650  }
1651 
1652  if(opp->incapacitated()) {
1653  return false;
1654  }
1655 
1656  // If sides aren't valid teams, then they are enemies.
1657  if(std::size_t(defender->side() - 1) >= teams.size() || std::size_t(opp->side() - 1) >= teams.size()) {
1658  return true;
1659  }
1660 
1661  // Defender and opposite are enemies.
1662  if(teams[defender->side() - 1].is_enemy(opp->side())) {
1663  return true;
1664  }
1665 
1666  // Defender and opposite are friends.
1667  return false;
1668 }
const_attack_ptr weapon
The weapon used by the unit to attack the opponent, or nullptr if there is none.
Definition: attack.hpp:51
constexpr const T & clamp(const T &value, const T &min, const T &max)
Definition: general.hpp:31
int kill_xp(int level)
Definition: game_config.hpp:46
void set_experience(int xp)
Sets the current experience point amount.
Definition: unit.hpp:547
std::unique_ptr< combatant > attacker_combatant_
Outcome of simulated fight.
Definition: attack.hpp:257
unsigned int calc_blows(unsigned new_hp) const
Calculates the number of blows we would have if we had new_hp.
Definition: attack.hpp:109
const std::string & parent_id() const
The id of the original type from which this (variation) descended.
Definition: types.hpp:143
int combat_xp(int level)
Definition: game_config.hpp:51
UNIT_ALIGNMENT ALIGNMENT
Definition: types.hpp:182
#define LOG_NG
Definition: attack.cpp:58
bool empty() const
Definition: unit.hpp:101
static lg::log_domain log_attack("engine/attack")
::tod_manager * tod_manager
Definition: resources.cpp:29
int get_max_liminal_bonus() const
unit_iterator end()
Definition: map.hpp:429
std::vector< double > hp_dist
Resulting probability distribution (might be not as large as max_hp)
static display * get_singleton()
Returns the display object if a display object exists.
Definition: display.hpp:88
const unit_type * find(const std::string &key, unit_type::BUILD_STATUS status=unit_type::FULL) const
Finds a unit_type by its id() and makes sure it is built to the specified level.
Definition: types.cpp:1157
const config * ability_cfg
The contents of the ability tag, never nullptr.
Definition: unit.hpp:70
void get_adjacent_tiles(const map_location &a, map_location *res)
Function which, given a location, will place all adjacent locations in res.
Definition: location.cpp:474
virtual const unit_map & units() const override
Definition: game_board.hpp:114
bool invalidate(const map_location &loc)
Function to invalidate a specific tile for redrawing.
Definition: display.cpp:3025
void unit_draw_weapon(const map_location &loc, unit &attacker, const_attack_ptr attack, const_attack_ptr secondary_attack, const map_location &defender_loc, unit *defender)
Play a pre-fight animation First unit is the attacker, second unit the defender.
Definition: udisplay.cpp:524
std::string plague_type
The plague type used by the attack, if any.
Definition: attack.hpp:83
static lg::log_domain log_config("config")
This class represents a single unit of a specific type.
Definition: unit.hpp:129
int dummy
Definition: lstrlib.cpp:1125
boost::iterator_range< boost::indirect_iterator< attack_list::iterator > > attack_itors
unsigned int hp
Hitpoints of the unit at the beginning of the battle.
Definition: attack.hpp:72
Various functions implementing vision (through fog of war and shroud).
The unit is uncovered - it was hiding but has been spotted.
Definition: unit.hpp:857
Various functions that implement attacks and attack calculations.
bool get_state(const std::string &state) const
Check if the unit is affected by a status effect.
Definition: unit.cpp:1353
Add a special kind of assert to validate whether the input from WML doesn&#39;t contain any problems that...
static bool better_combat(const combatant &us_a, const combatant &them_a, const combatant &us_b, const combatant &them_b, double harm_weight)
Definition: attack.cpp:490
unit_race::GENDER gender() const
The gender of this unit.
Definition: unit.hpp:459
const combatant & get_attacker_combatant(const combatant *prev_def=nullptr)
Get the simulation results.
Definition: attack.cpp:451
#define a
int hitpoints() const
The current number of hitpoints this unit has.
Definition: unit.hpp:493
double average_hp(unsigned int healing=0) const
What&#39;s the average hp (weighted average of hp_dist).
int under_leadership(const unit &u, const map_location &loc, const_attack_ptr weapon, const_attack_ptr opp_weapon)
Tests if the unit at loc is currently affected by leadership.
Definition: attack.cpp:1565
void invalidate_unit()
Function to invalidate that unit status displayed on the sidebar.
virtual const gamemap & map() const override
Definition: game_board.hpp:109
int lawful_bonus
The % bonus lawful units receive.
Definition: time_of_day.hpp:84
int wml_x() const
Definition: location.hpp:157
The unit is poisoned - it loses health each turn.
Definition: unit.hpp:855
int experience_needed(bool with_acceleration=true) const
Definition: types.cpp:545
unit_type_data unit_types
Definition: types.cpp:1376
The unit is petrified - it cannot move or be attacked.
Definition: unit.hpp:856
int resistance_against(const std::string &damage_name, bool attacker) const
Gets resistance while considering custom WML abilities.
Definition: types.cpp:741
bool is_slowed
True if the unit is slowed at the beginning of the battle.
Definition: attack.hpp:55
void insert(config_key_type key, T &&value)
Returns a reference to the first child with the given key.
Definition: config.hpp:437
Replay control code.
bool slows
Attack slows opponent when it hits.
Definition: attack.hpp:56
void clear()
Definition: config.cpp:863
int generic_combat_modifier(int lawful_bonus, unit_type::ALIGNMENT alignment, bool is_fearless, int max_liminal_bonus)
Returns the amount that a unit&#39;s damage should be multiplied by due to a given lawful_bonus.
Definition: attack.cpp:1592
int drain_constant
Base HP drained regardless of damage dealt.
Definition: attack.hpp:78
-file sdl_utils.hpp
unit_ability & front()
Definition: unit.hpp:102
void redraw_minimap()
Schedule the minimap to be redrawn.
Definition: display.hpp:622
unsigned int chance_to_hit
Effective chance to hit as a percentage (all factors accounted for).
Definition: attack.hpp:74
static unit_ptr create(const config &cfg, bool use_traits=false, const vconfig *vcfg=nullptr)
Initializes a unit from a config.
Definition: unit.hpp:185
A single unit type that the player may recruit.
Definition: types.hpp:44
game_data * gamedata
Definition: resources.cpp:22
config::attribute_value & get_variable(const std::string &varname)
throws invalid_variablename_exception if varname is no valid variable name.
Definition: game_data.cpp:62
map_location loc_
#define b
const unit_type & type() const
This unit&#39;s type, accounting for gender and variation.
Definition: unit.hpp:346
bool poisons
Attack poisons opponent when it hits.
Definition: attack.hpp:60
const combatant & get_defender_combatant(const combatant *prev_def=nullptr)
Definition: attack.cpp:458
Object which defines a time of day with associated bonuses, image, sounds etc.
Definition: time_of_day.hpp:57
bool backstab_pos
True if the attacker is in position to backstab the defender (this is used to determine whether to ap...
Definition: attack.hpp:61
int defense_modifier(const t_translation::terrain_code &terrain) const
The unit&#39;s defense on a given terrain.
Definition: unit.cpp:1647
bool musthave_status(const std::string &status) const
Definition: types.cpp:640
static UNUSEDNOWARN std::string _(const char *str)
Definition: gettext.hpp:91
team & get_team(int i)
Definition: game_board.hpp:104
std::string get(const std::string &key)
Definition: general.cpp:229
int damage
Effective damage of the weapon (all factors accounted for).
Definition: attack.hpp:75
Various functions that implement advancements of units.
int damage_from(const attack_type &attack, bool attacker, const map_location &loc, const_attack_ptr weapon=nullptr) const
Calculates the damage this unit would take from a certain attack.
Definition: unit.hpp:963
void set_state(const std::string &state, bool value)
Set whether the unit is affected by a status effect.
Definition: unit.cpp:1401
#define VALIDATE(cond, message)
The macro to use for the validation of WML.
bool better_defense(class battle_context &that, double harm_weight)
Given this harm_weight, is this attack better than that?
Definition: attack.cpp:478
unsigned int level
Definition: attack.hpp:69
void attack_result(hit_result res, int cth, int damage, int drain)
Definition: statistics.cpp:574
The unit is slowed - it moves slower and does less damage.
Definition: unit.hpp:854
unsigned int rounds
Berserk special can force us to fight more than one round.
Definition: attack.hpp:71
unsigned int swarm_min
Minimum number of blows with swarm (equal to num_blows if swarm isn&#39;t used).
Definition: attack.hpp:80
int wml_y() const
Definition: location.hpp:158
static 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, const combatant *prev_def)
Definition: attack.cpp:532
game_board * gameboard
Definition: resources.cpp:20
std::unique_ptr< battle_context_unit_stats > defender_stats_
Definition: attack.hpp:254
bool plagues
Attack turns opponent into a zombie when fatal.
Definition: attack.hpp:59
void unit_die(const map_location &loc, unit &loser, const_attack_ptr attack, const_attack_ptr secondary_attack, const map_location &winner_loc, unit *winner)
Show a unit fading out.
Definition: udisplay.cpp:572
bool better_attack(class battle_context &that, double harm_weight)
Given this harm_weight, is this attack better than that?
Definition: attack.cpp:466
Encapsulates the map of the game.
Definition: map.hpp:36
void recalculate_fog(int side)
Function that recalculates the fog of war.
Definition: vision.cpp:705
Computes the statistics of a battle between an attacker and a defender unit.
Definition: attack.hpp:172
const std::string & range() const
Definition: attack_type.hpp:46
checkup * checkup_instance
#define log_scope2(domain, description)
Definition: log.hpp:187
int attack_num
Index into unit->attacks() or -1 for none.
Definition: attack.hpp:52
Structure describing the statistics of a unit involved in the battle.
Definition: attack.hpp:49
The unit has not moved.
Definition: unit.hpp:858
std::array< map_location, 6 > adjacent_loc_array_t
Definition: location.hpp:170
std::unique_ptr< battle_context_unit_stats > attacker_stats_
Statistics of the units.
Definition: attack.hpp:253
game_events::manager * game_events
Definition: resources.cpp:24
advances the unit at loc if it has enough experience, maximum 20 times.
Definition: advancement.hpp:41
Encapsulates the map of the game.
Definition: location.hpp:42
int round_damage(int base_damage, int bonus, int divisor)
round (base_damage * bonus / divisor) to the closest integer, but up or down towards base_damage ...
Definition: math.hpp:79
unit_iterator find(std::size_t id)
Definition: map.cpp:311
std::shared_ptr< wb::manager > whiteboard
Definition: resources.cpp:33
static void process_error(const std::string &msg)
Definition: replay.cpp:195
All combat-related info.
const std::string & undead_variation() const
Info on the type of unit that the unit reanimates as.
Definition: types.hpp:131
const time_of_day get_illuminated_time_of_day(const unit_map &units, const gamemap &map, const map_location &loc, int for_turn=0) const
Returns time of day object for the passed turn at a location.
bool backstab_check(const map_location &attacker_loc, const map_location &defender_loc, const unit_map &units, const std::vector< team > &teams)
Function to check if an attack will satisfy the requirements for backstab.
Definition: attack.cpp:1620
bool fire_event(const ui_event event, std::vector< std::pair< widget *, ui_event >> &event_chain, widget *dispatcher, widget *w, F &&... params)
Helper function for fire_event.
bool swarm
Attack has swarm special.
Definition: attack.hpp:65
int slow_damage
Effective damage if unit becomes slowed (== damage, if already slowed)
Definition: attack.hpp:76
std::size_t i
Definition: function.cpp:933
unit_animation_component & anim_comp() const
Definition: unit.hpp:1523
std::unique_ptr< combatant > defender_combatant_
Definition: attack.hpp:258
void unit_sheath_weapon(const map_location &primary_loc, unit *primary_unit, const_attack_ptr primary_attack, const_attack_ptr secondary_attack, const map_location &secondary_loc, unit *secondary_unit)
Play a post-fight animation Both unit can be set to null, only valid units will play their animation...
Definition: udisplay.cpp:542
int max_hitpoints() const
The max number of hitpoints this unit can have.
Definition: unit.hpp:499
void attack_unit_and_advance(const map_location &attacker, const map_location &defender, int attack_with, int defend_with, bool update_display)
Performs an attack, and advanced the units afterwards.
Definition: attack.cpp:1546
#define LOG_CF
Definition: attack.cpp:69
static map_location::DIRECTION s
unsigned int experience
Definition: attack.hpp:68
double attack_weight() const
Definition: attack_type.hpp:54
Define the game&#39;s event mechanism.
attack_itors attacks()
Gets an iterator over this unit&#39;s attacks.
Definition: unit.hpp:919
bool disable
Attack has disable special.
Definition: attack.hpp:67
bool firststrike
Attack has firststrike special.
Definition: attack.hpp:66
int get_composite_value() const
Definition: abilities.hpp:48
double defense_weight() const
Definition: attack_type.hpp:55
bool is_poisoned
True if the unit is poisoned at the beginning of the battle.
Definition: attack.hpp:54
int level() const
Definition: types.hpp:154
std::set< std::string > & encountered_units()
Definition: game.cpp:954
int get_random_int(int min, int max)
This helper method provides a random int from the underlying generator, using results of next_random...
Definition: random.hpp:51
battle_context(const unit_map &units, const map_location &attacker_loc, const map_location &defender_loc, int attacker_weapon=-1, int defender_weapon=-1, double aggression=0.0, const combatant *prev_def=nullptr, const unit *attacker_ptr=nullptr, const unit *defender_ptr=nullptr)
If no attacker_weapon is given, we select the best one, based on harm_weight (1.0 means 1 hp lost cou...
Definition: attack.cpp:403
void advance_unit_at(const advance_unit_params &params)
int hitpoints() const
Definition: types.hpp:151
variant a_
Definition: function.cpp:722
rng * generator
This generator is automatically synced during synced context.
Definition: random.cpp:60
config & add_child(config_key_type key)
Definition: config.cpp:476
pump_result_t fire(const std::string &event, const entity_location &loc1=entity_location::null_entity, const entity_location &loc2=entity_location::null_entity, const config &data=config())
Function to fire an event.
Definition: pump.cpp:486
int drain_percent
Percentage of damage recovered as health.
Definition: attack.hpp:77
const std::string & undead_variation() const
Definition: unit.hpp:577
static DIRECTION get_opposite_dir(DIRECTION d)
Definition: location.hpp:59
bool is_village(const map_location &loc) const
Definition: map.cpp:65
std::size_t distance_between(const map_location &a, const map_location &b)
Function which gives the number of hexes between two tiles (i.e.
Definition: location.cpp:557
static 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)
Definition: attack.cpp:586
boost::intrusive_ptr< unit > unit_ptr
Definition: ptr.hpp:29
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)
Definition: attack.cpp:75
bool is_fearless() const
Gets whether this unit is fearless - ie, unaffected by time of day.
Definition: unit.hpp:1226
int experience() const
The current number of experience points this unit has.
Definition: unit.hpp:517
UNIT_ALIGNMENT alignment() const
The alignment of this unit.
Definition: unit.hpp:469
void attack_expected_damage(double attacker_inflict, double defender_inflict)
Definition: statistics.cpp:558
void attack_unit(const map_location &attacker, const map_location &defender, int attack_with, int defend_with, bool update_display)
Performs an attack.
Definition: attack.cpp:1536
void defend_result(hit_result res, int cth, int damage, int drain)
Definition: statistics.cpp:609
Standard logging facilities (interface).
static const map_location & null_location()
Definition: location.hpp:85
Container associating units to locations.
Definition: map.hpp:99
unsigned int num_blows
Effective number of blows, takes swarm into account.
Definition: attack.hpp:79
unsigned int max_hp
Maximum hitpoints of the unit.
Definition: attack.hpp:73
bool is_attacker
True if the unit is the attacker.
Definition: attack.hpp:53
game_events::wml_event_pump & pump()
Definition: manager.cpp:229
void set_standing(bool with_bars=true)
Sets the animation state to standing.
unsigned int max_experience
Definition: attack.hpp:68
void clear_variable(const std::string &varname)
Clears attributes config children does nothing if varname is no valid variable name.
Definition: game_data.cpp:114
virtual bool local_checkup(const config &expected_data, config &real_data)=0
Compares data to the results calculated during the original game.
#define DBG_NG
Definition: attack.cpp:57
unit_ability_list get_abilities_weapons(const std::string &tag_name, const map_location &loc, const_attack_ptr weapon=nullptr, const_attack_ptr opp_weapon=nullptr) const
Definition: abilities.cpp:226
void unit_attack(display *disp, game_board &board, const map_location &a, const map_location &b, int damage, const attack_type &attack, const_attack_ptr secondary_attack, int swing, const std::string &hit_text, int drain_amount, const std::string &att_text, const std::vector< std::string > *extra_hit_sounds)
Make the unit on tile &#39;a&#39; attack the unit on tile &#39;b&#39;.
Definition: udisplay.cpp:596
void simulate(const combatant *prev_def)
Definition: attack.cpp:390
bool petrifies
Attack petrifies opponent when it hits.
Definition: attack.hpp:58
static lg::log_domain log_engine("engine")
A config object defines a single node in a WML file, with access to child nodes.
Definition: config.hpp:68
bool valid() const
Definition: map.hpp:276
std::shared_ptr< const attack_type > const_attack_ptr
Definition: ptr.hpp:37
ALIGNMENT alignment() const
Definition: types.hpp:184
static map_location::DIRECTION n
bool drains
Attack drains opponent when it hits.
Definition: attack.hpp:57
Display units performing various actions: moving, attacking, and dying.
double poisoned
Resulting chance we are poisoned.
unsigned int swarm_max
Maximum number of blows with swarm (equal to num_blows if swarm isn&#39;t used).
Definition: attack.hpp:81
static game_display * get_singleton()
int combat_modifier(const unit_map &units, const gamemap &map, const map_location &loc, unit_type::ALIGNMENT alignment, bool is_fearless)
Returns the amount that a unit&#39;s damage should be multiplied by due to the current time of day...
Definition: attack.cpp:1572