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