The Battle for Wesnoth  1.15.5+dev
unit.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  * Routines to manage units.
18  */
19 
20 #include "units/unit.hpp"
21 
22 #include "color.hpp"
23 #include "deprecation.hpp"
24 #include "display.hpp"
25 #include "formatter.hpp"
26 #include "formula/string_utils.hpp" // for VGETTEXT
27 #include "game_board.hpp" // for game_board
28 #include "game_config.hpp" // for add_color_info, etc
29 #include "game_data.hpp"
30 #include "game_errors.hpp" // for game_error
31 #include "game_events/manager.hpp" // for add_events
32 #include "preferences/game.hpp" // for encountered_units
33 #include "gettext.hpp" // for N_
34 #include "lexical_cast.hpp"
35 #include "log.hpp" // for LOG_STREAM, logger, etc
36 #include "map/map.hpp" // for gamemap
37 #include "random.hpp" // for generator, rng
38 #include "resources.hpp" // for units, gameboard, teams, etc
39 #include "scripting/game_lua_kernel.hpp" // for game_lua_kernel
40 #include "side_filter.hpp" // for side_filter
41 #include "synced_context.hpp"
42 #include "team.hpp" // for team, get_teams, etc
43 #include "terrain/filter.hpp" // for terrain_filter
44 #include "units/abilities.hpp" // for effect, filter_base_matches
45 #include "units/animation.hpp" // for unit_animation
46 #include "units/animation_component.hpp" // for unit_animation_component
47 #include "units/filter.hpp"
48 #include "units/formula_manager.hpp" // for unit_formula_manager
49 #include "units/id.hpp"
50 #include "units/types.hpp"
51 #include "units/map.hpp" // for unit_map, etc
52 #include "variable.hpp" // for vconfig, etc
53 #include "game_version.hpp"
54 
55 #include "utils/functional.hpp"
56 #include <boost/dynamic_bitset.hpp>
57 #include <boost/function_output_iterator.hpp>
58 
59 #ifdef _MSC_VER
60 #pragma warning (push)
61 #pragma warning (disable: 4510 4610)
62 #endif
63 #include <boost/range/algorithm.hpp>
64 #ifdef _MSC_VER
65 #pragma warning (pop)
66 #endif
67 
68 #include <array>
69 #include <cassert> // for assert
70 #include <cstdlib> // for rand
71 #include <exception> // for exception
72 #include <iterator> // for back_insert_iterator, etc
73 #include <new> // for operator new
74 #include <ostream> // for operator<<, basic_ostream, etc
75 
76 namespace t_translation { struct terrain_code; }
77 
78 static lg::log_domain log_unit("unit");
79 #define DBG_UT LOG_STREAM(debug, log_unit)
80 #define LOG_UT LOG_STREAM(info, log_unit)
81 #define WRN_UT LOG_STREAM(warn, log_unit)
82 #define ERR_UT LOG_STREAM(err, log_unit)
83 
84 namespace
85 {
86  // "advance" only kept around for backwards compatibility; only "advancement" should be used
87  const std::array<std::string, 4> ModificationTypes {{ "advancement", "advance", "trait", "object" }};
88 
89  /**
90  * Pointers to units which have data in their internal caches. The
91  * destructor of an unit removes itself from the cache, so the pointers are
92  * always valid.
93  */
94  static std::vector<const unit*> units_with_cache;
95 
96  static const std::string leader_crown_path = "misc/leader-crown.png";
97  static std::array<std::string, 60> internalized_attrs {{
98  "type",
99  "id",
100  "name",
101  "gender",
102  "random_gender",
103  "variation",
104  "role",
105  "ai_special",
106  "side",
107  "underlying_id",
108  "overlays",
109  "facing",
110  "race",
111  "level",
112  "recall_cost",
113  "undead_variation",
114  "max_attacks",
115  "attacks_left",
116  "alpha",
117  "zoc",
118  "flying",
119  "cost",
120  "max_hitpoints",
121  "max_moves",
122  "vision",
123  "jamming",
124  "max_experience",
125  "advances_to",
126  "hitpoints",
127  "goto_x",
128  "goto_y",
129  "moves",
130  "experience",
131  "resting",
132  "unrenamable",
133  "alignment",
134  "canrecruit",
135  "extra_recruit",
136  "x",
137  "y",
138  "placement",
139  "parent_type",
140  "description",
141  "usage",
142  "halo",
143  "ellipse",
144  "upkeep",
145  "random_traits",
146  "generate_name",
147  "profile",
148  "small_profile",
149  "fire_event",
150  "passable",
151  "overwrite",
152  "location_id",
153  "hidden",
154  // Useless attributes created when saving units to WML:
155  "flag_rgb",
156  "language_name",
157  "image",
158  "image_icon"
159  }};
160 
161  struct internalized_attrs_sorter
162  {
163  internalized_attrs_sorter()
164  {
165  std::sort(std::begin(internalized_attrs), std::end(internalized_attrs));
166  }
167  };
168 
169  // Sort the array to make set_difference below work.
170  internalized_attrs_sorter sorter;
171 
172  void warn_unknown_attribute(const config::const_attr_itors& cfg)
173  {
174  config::const_attribute_iterator cur = cfg.begin();
175  config::const_attribute_iterator end = cfg.end();
176 
177  auto cur_known = internalized_attrs.begin();
178  auto end_known = internalized_attrs.end();
179 
180  while(cur_known != end_known) {
181  if(cur == end) {
182  return;
183  }
184  int comp = cur->first.compare(*cur_known);
185  if(comp < 0) {
186  WRN_UT << "Unknown attribute '" << cur->first << "' discarded." << std::endl;
187  ++cur;
188  }
189  else if(comp == 0) {
190  ++cur;
191  ++cur_known;
192  }
193  else {
194  ++cur_known;
195  }
196  }
197 
198  while(cur != end) {
199  WRN_UT << "Unknown attribute '" << cur->first << "' discarded." << std::endl;
200  ++cur;
201  }
202  }
203 
204  template<typename T>
205  T* copy_or_null(const std::unique_ptr<T>& ptr)
206  {
207  return ptr ? new T(*ptr) : nullptr;
208  }
209 } // end anon namespace
210 
211 /**
212  * Converts a string ID to a unit_type.
213  * Throws a game_error exception if the string does not correspond to a type.
214  */
215 static const unit_type& get_unit_type(const std::string& type_id)
216 {
217  if(type_id.empty()) {
218  throw unit_type::error("creating unit with an empty type field");
219  }
220  std::string new_id = type_id;
221  unit_type::check_id(new_id);
222  const unit_type* i = unit_types.find(new_id);
223  if(!i) throw unit_type::error("unknown unit type: " + type_id);
224  return *i;
225 }
226 
227 static unit_race::GENDER generate_gender(const unit_type& type, bool random_gender)
228 {
229  const std::vector<unit_race::GENDER>& genders = type.genders();
230  assert(genders.size() > 0);
231 
232  if(random_gender == false || genders.size() == 1) {
233  return genders.front();
234  } else {
235  return genders[randomness::generator->get_random_int(0,genders.size()-1)];
236  // Note: genders is guaranteed to be non-empty, so this is not a
237  // potential division by zero.
238  // Note: Whoever wrote this code, you should have used an assertion, to save others hours of work...
239  // If the assertion size>0 is failing for you, one possible cause is that you are constructing a unit
240  // from a unit type which has not been ``built'' using the unit_type_data methods.
241  }
242 }
243 
244 static unit_race::GENDER generate_gender(const unit_type& u_type, const config& cfg)
245 {
246  const std::string& gender = cfg["gender"];
247  if(!gender.empty()) {
248  return string_gender(gender);
249  }
250 
251  return generate_gender(u_type, cfg["random_gender"].to_bool());
252 }
253 
255 {
256  ptr_vector_pushback(boost::ptr_vector<config>& vec) : vec_(&vec) {}
257 
258  void operator()(const config& cfg)
259  {
260  vec_->push_back(new config(cfg));
261  }
262 
263  //Don't use reference to be copyable.
264  boost::ptr_vector<config>* vec_;
265 };
266 
267 // Copy constructor
268 unit::unit(const unit& o)
269  : std::enable_shared_from_this<unit>()
270  , loc_(o.loc_)
271  , advances_to_(o.advances_to_)
272  , type_(o.type_)
273  , type_name_(o.type_name_)
274  , race_(o.race_)
275  , id_(o.id_)
276  , name_(o.name_)
277  , underlying_id_(o.underlying_id_)
278  , undead_variation_(o.undead_variation_)
279  , variation_(o.variation_)
280  , hit_points_(o.hit_points_)
281  , max_hit_points_(o.max_hit_points_)
282  , experience_(o.experience_)
283  , max_experience_(o.max_experience_)
284  , level_(o.level_)
285  , recall_cost_(o.recall_cost_)
286  , canrecruit_(o.canrecruit_)
287  , recruit_list_(o.recruit_list_)
288  , alignment_(o.alignment_)
289  , flag_rgb_(o.flag_rgb_)
290  , image_mods_(o.image_mods_)
291  , unrenamable_(o.unrenamable_)
292  , side_(o.side_)
293  , gender_(o.gender_)
294  , formula_man_(new unit_formula_manager(o.formula_manager()))
295  , movement_(o.movement_)
296  , max_movement_(o.max_movement_)
297  , vision_(o.vision_)
298  , jamming_(o.jamming_)
299  , movement_type_(o.movement_type_)
300  , hold_position_(o.hold_position_)
301  , end_turn_(o.end_turn_)
302  , resting_(o.resting_)
303  , attacks_left_(o.attacks_left_)
304  , max_attacks_(o.max_attacks_)
305  , states_(o.states_)
306  , known_boolean_states_(o.known_boolean_states_)
307  , variables_(o.variables_)
308  , events_(o.events_)
309  , filter_recall_(o.filter_recall_)
310  , emit_zoc_(o.emit_zoc_)
311  , overlays_(o.overlays_)
312  , role_(o.role_)
313  , attacks_(o.attacks_)
314  , facing_(o.facing_)
315  , trait_names_(o.trait_names_)
316  , trait_descriptions_(o.trait_descriptions_)
317  , unit_value_(o.unit_value_)
318  , goto_(o.goto_)
319  , interrupted_move_(o.interrupted_move_)
320  , is_fearless_(o.is_fearless_)
321  , is_healthy_(o.is_healthy_)
322  , modification_descriptions_(o.modification_descriptions_)
323  , anim_comp_(new unit_animation_component(*this, *o.anim_comp_))
324  , hidden_(o.hidden_)
325  , hp_bar_scaling_(o.hp_bar_scaling_)
326  , xp_bar_scaling_(o.xp_bar_scaling_)
327  , modifications_(o.modifications_)
328  , abilities_(o.abilities_)
329  , advancements_(o.advancements_)
330  , description_(o.description_)
331  , special_notes_(o.special_notes_)
332  , usage_(copy_or_null(o.usage_))
333  , halo_(copy_or_null(o.halo_))
334  , ellipse_(copy_or_null(o.ellipse_))
335  , random_traits_(o.random_traits_)
336  , generate_name_(o.generate_name_)
337  , upkeep_(o.upkeep_)
338  , profile_(o.profile_)
339  , small_profile_(o.small_profile_)
340  , changed_attributes_(o.changed_attributes_)
341  , invisibility_cache_()
342 {
343  // Copy the attacks rather than just copying references
344  for(auto& a : attacks_) {
345  a.reset(new attack_type(*a));
346  }
347 }
348 
350  : std::enable_shared_from_this<unit>()
351  , loc_()
352  , advances_to_()
353  , type_(nullptr)
354  , type_name_()
355  , race_(&unit_race::null_race)
356  , id_()
357  , name_()
358  , underlying_id_(0)
360  , variation_()
361  , hit_points_(1)
362  , max_hit_points_(1)
363  , experience_(0)
364  , max_experience_(1)
365  , level_(0)
366  , recall_cost_(-1)
367  , canrecruit_(false)
368  , recruit_list_()
369  , alignment_()
370  , flag_rgb_()
371  , image_mods_()
372  , unrenamable_(false)
373  , side_(0)
374  , gender_(unit_race::NUM_GENDERS)
376  , movement_(0)
377  , max_movement_(0)
378  , vision_(-1)
379  , jamming_(0)
380  , movement_type_()
381  , hold_position_(false)
382  , end_turn_(false)
383  , resting_(false)
384  , attacks_left_(0)
385  , max_attacks_(0)
386  , states_()
388  , variables_()
389  , events_()
390  , filter_recall_()
391  , emit_zoc_(0)
392  , overlays_()
393  , role_()
394  , attacks_()
395  , facing_(map_location::NDIRECTIONS)
396  , trait_names_()
398  , unit_value_()
399  , goto_()
401  , is_fearless_(false)
402  , is_healthy_(false)
405  , hidden_(false)
406  , hp_bar_scaling_(0)
407  , xp_bar_scaling_(0)
408  , modifications_()
409  , abilities_()
410  , advancements_()
411  , description_()
412  , special_notes_()
413  , usage_()
414  , halo_()
415  , ellipse_()
416  , random_traits_(true)
417  , generate_name_(true)
418  , upkeep_(upkeep_full())
421 {
422 
423 }
424 
425 void unit::init(const config& cfg, bool use_traits, const vconfig* vcfg)
426 {
427  loc_ = map_location(cfg["x"], cfg["y"], wml_loc());
428  type_ = &get_unit_type(cfg["parent_type"].blank() ? cfg["type"].str() : cfg["parent_type"].str());
430  id_ = cfg["id"].str();
431  name_ = cfg["name"].t_str();
432  variation_ = cfg["variation"].empty() ? type_->default_variation() : cfg["variation"].str();
433  canrecruit_ = cfg["canrecruit"].to_bool();
434  gender_ = generate_gender(*type_, cfg);
435  role_ = cfg["role"].str();
436  //, facing_(map_location::NDIRECTIONS)
437  //, anim_comp_(new unit_animation_component(*this))
438  hidden_ = cfg["hidden"].to_bool(false);
439  hp_bar_scaling_ = cfg["hp_bar_scaling"].blank() ? type_->hp_bar_scaling() : cfg["hp_bar_scaling"];
440  xp_bar_scaling_ = cfg["xp_bar_scaling"].blank() ? type_->xp_bar_scaling() : cfg["xp_bar_scaling"];
441  random_traits_ = true;
442  generate_name_ = true;
443  side_ = cfg["side"].to_int();
444 
445  if(side_ <= 0) {
446  side_ = 1;
447  }
448 
450  underlying_id_ = n_unit::unit_id(cfg["underlying_id"].to_size_t());
452 
453  if(vcfg) {
454  const vconfig& filter_recall = vcfg->child("filter_recall");
455  if(!filter_recall.null())
456  filter_recall_ = filter_recall.get_config();
457 
458  const vconfig::child_list& events = vcfg->get_children("event");
459  for(const vconfig& e : events) {
460  events_.add_child("event", e.get_config());
461  }
462  } else {
463  filter_recall_ = cfg.child_or_empty("filter_recall");
464 
465  for(const config& unit_event : cfg.child_range("event")) {
466  events_.add_child("event", unit_event);
467  }
468  }
469 
472  }
473 
474  random_traits_ = cfg["random_traits"].to_bool(true);
475  facing_ = map_location::parse_direction(cfg["facing"]);
477 
478  if(const config& mods = cfg.child("modifications")) {
479  modifications_ = mods;
480  }
481 
482  generate_name_ = cfg["generate_name"].to_bool(true);
483 
484  // Apply the unit type's data to this unit.
485  advance_to(*type_, use_traits);
486 
487  if(const config::attribute_value* v = cfg.get("overlays")) {
488  auto overlays = utils::parenthetical_split(v->str(), ',');
489  if(overlays.size() > 0) {
490  deprecated_message("[unit]overlays", DEP_LEVEL::PREEMPTIVE, {1, 17, 0}, "This warning is only triggered by the cases that *do* still work: setting [unit]overlays= works, but the [unit]overlays attribute will always be empty if WML tries to read it.");
491  config effect;
492  config o;
493  effect["apply_to"] = "overlay";
494  effect["add"] = v->str();
495  o.add_child("effect", effect);
496  add_modification("object", o);
497  }
498  }
499 
500  if(const config& variables = cfg.child("variables")) {
502  }
503 
504  if(const config::attribute_value* v = cfg.get("race")) {
505  if(const unit_race *r = unit_types.find_race(*v)) {
506  race_ = r;
507  } else {
509  }
510  }
511 
512  if(const config::attribute_value* v = cfg.get("level")) {
513  set_level(v->to_int(level_));
514  }
515 
516  if(const config::attribute_value* v = cfg.get("undead_variation")) {
517  set_undead_variation(v->str());
518  }
519 
520  if(const config::attribute_value* v = cfg.get("max_attacks")) {
521  set_max_attacks(std::max(0, v->to_int(1)));
522  }
523 
524  if(const config::attribute_value* v = cfg.get("zoc")) {
525  set_emit_zoc(v->to_bool(level_ > 0));
526  }
527 
528  if(const config::attribute_value* v = cfg.get("description")) {
529  description_ = *v;
530  }
531 
532  if(const config::attribute_value* v = cfg.get("cost")) {
533  unit_value_ = *v;
534  }
535 
536  if(const config::attribute_value* v = cfg.get("ellipse")) {
537  set_image_ellipse(*v);
538  }
539 
540  if(const config::attribute_value* v = cfg.get("halo")) {
541  set_image_halo(*v);
542  }
543 
544  if(const config::attribute_value* v = cfg.get("usage")) {
545  set_usage(*v);
546  }
547 
548  if(const config::attribute_value* v = cfg.get("profile")) {
549  set_big_profile(v->str());
550  }
551 
552  if(const config::attribute_value* v = cfg.get("small_profile")) {
553  set_small_profile(v->str());
554  }
555 
556  if(const config::attribute_value* v = cfg.get("max_hitpoints")) {
557  set_max_hitpoints(std::max(1, v->to_int(max_hit_points_)));
558  }
559  if(const config::attribute_value* v = cfg.get("max_moves")) {
560  set_total_movement(std::max(1, v->to_int(max_movement_)));
561  }
562  if(const config::attribute_value* v = cfg.get("max_experience")) {
563  set_max_experience(std::max(1, v->to_int(max_experience_)));
564  }
565 
566  vision_ = cfg["vision"].to_int(vision_);
567  jamming_ = cfg["jamming"].to_int(jamming_);
568 
569  advances_to_t temp_advances = utils::split(cfg["advances_to"]);
570  if(temp_advances.size() == 1 && temp_advances.front() == "null") {
572  } else if(temp_advances.size() >= 1 && !temp_advances.front().empty()) {
573  set_advances_to(temp_advances);
574  }
575 
576  if(const config& ai = cfg.child("ai")) {
577  formula_man_->read(ai);
578  }
579 
580  // Don't use the unit_type's attacks if this config has its own defined
581  if(config::const_child_itors cfg_range = cfg.child_range("attack")) {
583  attacks_.clear();
584  for(const config& c : cfg_range) {
585  attacks_.emplace_back(new attack_type(c));
586  }
587  }
588 
589  // Don't use the unit_type's special notes if this config has its own defined
590  if(config::const_child_itors cfg_range = cfg.child_range("special_note")) {
592  special_notes_.clear();
593  for(const config& c : cfg_range) {
594  special_notes_.emplace_back(c["note"].t_str());
595  }
596  }
597 
598  // If cfg specifies [advancement]s, replace this [advancement]s with them.
599  if(cfg.has_child("advancement")) {
601  this->advancements_.clear();
602  boost::copy(cfg.child_range("advancement"), boost::make_function_output_iterator(ptr_vector_pushback(advancements_)));
603  }
604 
605  // Don't use the unit_type's abilities if this config has its own defined
606  // Why do we allow multiple [abilities] tags?
607  if(config::const_child_itors cfg_range = cfg.child_range("abilities")) {
609  abilities_.clear();
610  for(const config& abilities : cfg_range) {
611  this->abilities_.append(abilities);
612  }
613  }
614 
615  if(const config::attribute_value* v = cfg.get("alignment")) {
617  alignment_.parse(v->str());
618  }
619 
620  // Adjust the unit's defense, movement, vision, jamming, resistances, and
621  // flying status if this config has its own defined.
622  if(cfg.has_child("movement_costs")
623  || cfg.has_child("vision_costs")
624  || cfg.has_child("jamming_costs")
625  || cfg.has_child("defense")
626  || cfg.has_child("resistance")
627  || cfg.has_attribute("flying"))
628  {
630  }
631 
632  movement_type_.merge(cfg);
633 
634  if(const config& status_flags = cfg.child("status")) {
635  for(const config::attribute &st : status_flags.attribute_range()) {
636  if(st.second.to_bool()) {
637  set_state(st.first, true);
638  }
639  }
640  }
641 
642  if(cfg["ai_special"] == "guardian") {
643  set_state(STATE_GUARDIAN, true);
644  }
645 
646  if(const config::attribute_value* v = cfg.get("invulnerable")) {
647  set_state("invulnerable", v->to_bool());
648  }
649 
650  goto_.set_wml_x(cfg["goto_x"].to_int());
651  goto_.set_wml_y(cfg["goto_y"].to_int());
652 
653  attacks_left_ = std::max(0, cfg["attacks_left"].to_int(max_attacks_));
654 
655  movement_ = std::max(0, cfg["moves"].to_int(max_movement_));
656  // we allow negative hitpoints, one of the reasons is that a unit
657  // might be stored+unstored during a attack related event before it
658  // dies when it has negative hp and when dont want the event to
659  // change the unit hp when it was not intended.
660  hit_points_ = cfg["hitpoints"].to_int(max_hit_points_);
661 
662  experience_ = cfg["experience"];
663  resting_ = cfg["resting"].to_bool();
664  unrenamable_ = cfg["unrenamable"].to_bool();
665 
666  // We need to check to make sure that the cfg is not blank and if it
667  // isn't pull that value otherwise it goes with the default of -1.
668  if(!cfg["recall_cost"].blank()) {
669  recall_cost_ = cfg["recall_cost"].to_int(recall_cost_);
670  }
671 
672  generate_name();
673 
674  parse_upkeep(cfg["upkeep"]);
675 
676  set_recruits(utils::split(cfg["extra_recruit"]));
677 
678  warn_unknown_attribute(cfg.attribute_range());
679 
680 #if 0
681  // Debug unit animations for units as they appear in game
682  for(const auto& anim : anim_comp_->animations_) {
683  std::cout << anim.debug() << std::endl;
684  }
685 #endif
686 }
687 
689 {
690  for(auto& u : units_with_cache) {
691  u->clear_visibility_cache();
692  }
693 
694  units_with_cache.clear();
695 }
696 
697 void unit::init(const unit_type& u_type, int side, bool real_unit, unit_race::GENDER gender, const std::string& variation)
698 {
699  type_ = &u_type;
701  variation_ = variation.empty() ? type_->default_variation() : variation;
702  side_ = side;
703  gender_ = gender != unit_race::NUM_GENDERS ? gender : generate_gender(u_type, real_unit);
705  upkeep_ = upkeep_full();
706 
707  // Apply the unit type's data to this unit.
708  advance_to(u_type, real_unit);
709 
710  if(real_unit) {
711  generate_name();
712  }
713 
715 
716  // Set these after traits and modifications have set the maximums.
720 }
721 
723 {
724  try {
725  anim_comp_->clear_haloes();
726 
727  // Remove us from the status cache
728  auto itor = std::find(units_with_cache.begin(), units_with_cache.end(), this);
729 
730  if(itor != units_with_cache.end()) {
731  units_with_cache.erase(itor);
732  }
733  } catch(const std::exception & e) {
734  ERR_UT << "Caught exception when destroying unit: " << e.what() << std::endl;
735  } catch(...) {}
736 }
737 
738 /**
739  * Swap, for copy and swap idiom
740  */
741 void unit::swap(unit & o)
742 {
743  using std::swap;
744 
745  // Don't swap reference count, or it will be incorrect...
746  swap(loc_, o.loc_);
748  swap(type_, o.type_);
750  swap(race_, o.race_);
751  swap(id_, o.id_);
752  swap(name_, o.name_);
760  swap(level_, o.level_);
768  swap(side_, o.side_);
769  swap(gender_, o.gender_);
773  swap(vision_, o.vision_);
774  swap(jamming_, o.jamming_);
778  swap(resting_, o.resting_);
781  swap(states_, o.states_);
784  swap(events_, o.events_);
788  swap(role_, o.role_);
789  swap(attacks_, o.attacks_);
790  swap(facing_, o.facing_);
794  swap(goto_, o.goto_);
800  swap(hidden_, o.hidden_);
803 }
804 
806 {
807  if(!name_.empty() || !generate_name_) {
808  return;
809  }
811  generate_name_ = false;
812 }
813 
814 void unit::generate_traits(bool must_have_only)
815 {
816  LOG_UT << "Generating a trait for unit type " << type().log_id() << " with must_have_only " << must_have_only << std::endl;
817  const unit_type& u_type = type();
818 
819  // Calculate the unit's traits
820  config::const_child_itors current_traits = modifications_.child_range("trait");
821  std::vector<const config*> candidate_traits;
822 
823  for(const config& t : u_type.possible_traits()) {
824  // Skip the trait if the unit already has it.
825  const std::string& tid = t["id"];
826  bool already = false;
827  for(const config& mod : current_traits) {
828  if(mod["id"] == tid) {
829  already = true;
830  break;
831  }
832  }
833 
834  if(already) {
835  continue;
836  }
837 
838  // Add the trait if it is mandatory.
839  const std::string& avl = t["availability"];
840  if(avl == "musthave") {
841  modifications_.add_child("trait", t);
842  current_traits = modifications_.child_range("trait");
843  continue;
844  }
845 
846  // The trait is still available, mark it as a candidate for randomizing.
847  // For leaders, only traits with availability "any" are considered.
848  if(!must_have_only && (!can_recruit() || avl == "any")) {
849  candidate_traits.push_back(&t);
850  }
851  }
852 
853  if(must_have_only) return;
854 
855  // Now randomly fill out to the number of traits required or until
856  // there aren't any more traits.
857  int nb_traits = current_traits.size();
858  int max_traits = u_type.num_traits();
859  for(; nb_traits < max_traits && !candidate_traits.empty(); ++nb_traits)
860  {
861  int num = randomness::generator->get_random_int(0,candidate_traits.size()-1);
862  modifications_.add_child("trait", *candidate_traits[num]);
863  candidate_traits.erase(candidate_traits.begin() + num);
864  }
865 
866  // Once random traits are added, don't do it again.
867  // Such as when restoring a saved character.
868  random_traits_ = false;
869 }
870 
871 std::vector<std::string> unit::get_traits_list() const
872 {
873  std::vector<std::string> res;
874 
875  for(const config& mod : modifications_.child_range("trait"))
876  {
877  // Make sure to return empty id trait strings as otherwise
878  // names will not match in length (Bug #21967)
879  res.push_back(mod["id"]);
880  }
881  return res;
882 }
883 
884 
885 /**
886  * Advances this unit to the specified type.
887  * Experience is left unchanged.
888  * Current hit point total is left unchanged unless it would violate max HP.
889  * Assumes gender_ and variation_ are set to their correct values.
890  */
891 void unit::advance_to(const unit_type& u_type, bool use_traits)
892 {
893  appearance_changed_ = true;
894  // For reference, the type before this advancement.
895  const unit_type& old_type = type();
896  // Adjust the new type for gender and variation.
898  // In cast u_type was already a variation, make sure our variation is set correctly.
899  variation_ = new_type.variation_id();
900 
901  // Reset the scalar values first
902  trait_names_.clear();
903  trait_descriptions_.clear();
904  is_fearless_ = false;
905  is_healthy_ = false;
906  image_mods_.clear();
907  overlays_.clear();
908  ellipse_.reset();
909 
910  // Clear modification-related caches
912 
913 
914  if(!new_type.usage().empty()) {
915  set_usage(new_type.usage());
916  }
917 
918  set_image_halo(new_type.halo());
919  if(!new_type.ellipse().empty()) {
920  set_image_ellipse(new_type.ellipse());
921  }
922 
923  generate_name_ &= new_type.generate_name();
924  abilities_ = new_type.abilities_cfg();
925  advancements_.clear();
926 
927  for(const config& advancement : new_type.advancements()) {
928  advancements_.push_back(new config(advancement));
929  }
930 
931  // If unit has specific profile, remember it and keep it after advancing
932  if(small_profile_.empty() || small_profile_ == old_type.small_profile()) {
933  small_profile_ = new_type.small_profile();
934  }
935 
936  if(profile_.empty() || profile_ == old_type.big_profile()) {
937  profile_ = new_type.big_profile();
938  }
939  // NOTE: There should be no need to access old_cfg (or new_cfg) after this
940  // line. Particularly since the swap might have affected old_cfg.
941 
942  advances_to_ = new_type.advances_to();
943 
944  race_ = new_type.race();
945  type_ = &new_type;
946  type_name_ = new_type.type_name();
947  description_ = new_type.unit_description();
948  special_notes_ = new_type.special_notes();
949  undead_variation_ = new_type.undead_variation();
950  max_experience_ = new_type.experience_needed(true);
951  level_ = new_type.level();
952  recall_cost_ = new_type.recall_cost();
953  alignment_ = new_type.alignment();
954  max_hit_points_ = new_type.hitpoints();
955  hp_bar_scaling_ = new_type.hp_bar_scaling();
956  xp_bar_scaling_ = new_type.xp_bar_scaling();
957  max_movement_ = new_type.movement();
958  vision_ = new_type.vision(true);
959  jamming_ = new_type.jamming();
960  movement_type_ = new_type.movement_type();
961  emit_zoc_ = new_type.has_zoc();
962  attacks_.clear();
963  std::transform(new_type.attacks().begin(), new_type.attacks().end(), std::back_inserter(attacks_), [](const attack_type& atk) {
964  return std::make_shared<attack_type>(atk);
965  });
966  unit_value_ = new_type.cost();
967 
968  max_attacks_ = new_type.max_attacks();
969 
970  flag_rgb_ = new_type.flag_rgb();
971 
972  upkeep_ = upkeep_full();
973  parse_upkeep(new_type.get_cfg()["upkeep"]);
974 
975  anim_comp_->reset_after_advance(&new_type);
976 
977  if(random_traits_) {
978  generate_traits(!use_traits);
979  } else {
980  // This will add any "musthave" traits to the new unit that it doesn't already have.
981  // This covers the Dark Sorcerer advancing to Lich and gaining the "undead" trait,
982  // but random and/or optional traits are not added,
983  // and neither are inappropriate traits removed.
984  generate_traits(true);
985  }
986 
987  // Apply modifications etc, refresh the unit.
988  // This needs to be after type and gender are fixed,
989  // since there can be filters on the modifications
990  // that may result in different effects after the advancement.
992 
993  // Now that modifications are done modifying traits, check if poison should
994  // be cleared.
995  if(get_state("unpoisonable")) {
996  set_state(STATE_POISONED, false);
997  }
998 
999  // Now that modifications are done modifying the maximum hit points,
1000  // enforce this maximum.
1003  }
1004 
1005  // In case the unit carries EventWML, apply it now
1007  resources::game_events->add_events(new_type.events(), new_type.id());
1008  }
1009  bool bool_small_profile = get_attr_changed(UA_SMALL_PROFILE);
1010  bool bool_profile = get_attr_changed(UA_PROFILE);
1012  if(bool_small_profile && small_profile_ != new_type.small_profile()) {
1014  }
1015 
1016  if(bool_profile && profile_ != new_type.big_profile()) {
1018  }
1019 }
1020 
1022 {
1023  if(!profile_.empty() && profile_ != "unit_image") {
1024  return profile_;
1025  }
1026 
1027  return absolute_image();
1028 }
1029 
1031 {
1032  if(!small_profile_.empty() && small_profile_ != "unit_image") {
1033  return small_profile_;
1034  }
1035 
1036  if(!profile_.empty() && small_profile_ != "unit_image" && profile_ != "unit_image") {
1037  return profile_;
1038  }
1039 
1040  return absolute_image();
1041 }
1042 
1044 {
1045  return leader_crown_path;
1046 }
1047 
1049 {
1050  return flag_rgb_.empty() ? game_config::unit_rgb : flag_rgb_;
1051 }
1052 
1054 {
1055  double unit_energy = 0.0;
1056  color_t energy_color {0,0,0,255};
1057 
1058  if(max_hitpoints > 0) {
1059  unit_energy = static_cast<double>(hitpoints)/static_cast<double>(max_hitpoints);
1060  }
1061 
1062  if(1.0 == unit_energy) {
1063  energy_color.r = 33;
1064  energy_color.g = 225;
1065  energy_color.b = 0;
1066  } else if(unit_energy > 1.0) {
1067  energy_color.r = 100;
1068  energy_color.g = 255;
1069  energy_color.b = 100;
1070  } else if(unit_energy >= 0.75) {
1071  energy_color.r = 170;
1072  energy_color.g = 255;
1073  energy_color.b = 0;
1074  } else if(unit_energy >= 0.5) {
1075  energy_color.r = 255;
1076  energy_color.g = 175;
1077  energy_color.b = 0;
1078  } else if(unit_energy >= 0.25) {
1079  energy_color.r = 255;
1080  energy_color.g = 155;
1081  energy_color.b = 0;
1082  } else {
1083  energy_color.r = 255;
1084  energy_color.g = 0;
1085  energy_color.b = 0;
1086  }
1087 
1088  return energy_color;
1089 }
1090 
1092 {
1093  return hp_color_impl(hitpoints(), max_hitpoints());
1094 }
1095 
1096 color_t unit::hp_color(int new_hitpoints) const
1097 {
1098  return hp_color_impl(new_hitpoints, hitpoints());
1099 }
1100 
1102 {
1103  return hp_color_impl(1, 1);
1104 }
1105 
1107 {
1108  const color_t near_advance_color {255,255,255,255};
1109  const color_t mid_advance_color {150,255,255,255};
1110  const color_t far_advance_color {0,205,205,255};
1111  const color_t normal_color {0,160,225,255};
1112  const color_t near_amla_color {225,0,255,255};
1113  const color_t mid_amla_color {169,30,255,255};
1114  const color_t far_amla_color {139,0,237,255};
1115  const color_t amla_color {170,0,255,255};
1116 
1117  const bool near_advance = static_cast<int>(xp_to_advance) <= game_config::kill_experience;
1118  const bool mid_advance = static_cast<int>(xp_to_advance) <= game_config::kill_experience*2;
1119  const bool far_advance = static_cast<int>(xp_to_advance) <= game_config::kill_experience*3;
1120 
1121  color_t color = normal_color;
1122  if(can_advance){
1123  if(near_advance){
1124  color=near_advance_color;
1125  } else if(mid_advance){
1126  color=mid_advance_color;
1127  } else if(far_advance){
1128  color=far_advance_color;
1129  }
1130  } else if(has_amla){
1131  if(near_advance){
1132  color=near_amla_color;
1133  } else if(mid_advance){
1134  color=mid_amla_color;
1135  } else if(far_advance){
1136  color=far_amla_color;
1137  } else {
1138  color=amla_color;
1139  }
1140  }
1141 
1142  return(color);
1143 }
1144 
1146 {
1147  bool major_amla = false;
1148  bool has_amla = false;
1149  for(const config& adv:get_modification_advances()){
1150  major_amla |= adv["major_amla"].to_bool();
1151  has_amla = true;
1152  }
1153  //TODO: calculating has_amla and major_amla can be a quite slow operation, we should cache these two values somehow.
1154  return xp_color(experience_to_advance(), !advances_to().empty() || major_amla, has_amla);
1155 }
1156 
1157 void unit::set_recruits(const std::vector<std::string>& recruits)
1158 {
1159  unit_types.check_types(recruits);
1161  //TODO crab
1162  //info_.minimum_recruit_price = 0;
1163  //ai::manager::get_singleton().raise_recruit_list_changed();
1164 }
1165 
1166 const std::vector<std::string> unit::advances_to_translated() const
1167 {
1168  std::vector<std::string> result;
1169  for(const std::string& adv_type_id : advances_to_) {
1170  if(const unit_type* adv_type = unit_types.find(adv_type_id)) {
1171  result.push_back(adv_type->type_name());
1172  } else {
1173  WRN_UT << "unknown unit in advances_to list of type "
1174  << type().log_id() << ": " << adv_type_id << std::endl;
1175  }
1176  }
1177 
1178  return result;
1179 }
1180 
1181 void unit::set_advances_to(const std::vector<std::string>& advances_to)
1182 {
1184  unit_types.check_types(advances_to);
1186 }
1187 
1188 void unit::set_movement(int moves, bool unit_action)
1189 {
1190  // If this was because the unit acted, clear its "not acting" flags.
1191  if(unit_action) {
1192  end_turn_ = hold_position_ = false;
1193  }
1194 
1195  movement_ = std::max<int>(0, moves);
1196 }
1197 
1198 /**
1199  * Determines if @a mod_dur "matches" @a goal_dur.
1200  * If goal_dur is not empty, they match if they are equal.
1201  * If goal_dur is empty, they match if mod_dur is neither empty nor "forever".
1202  * Helper function for expire_modifications().
1203  */
1204 inline bool mod_duration_match(const std::string& mod_dur, const std::string& goal_dur)
1205 {
1206  if(goal_dur.empty()) {
1207  // Default is all temporary modifications.
1208  return !mod_dur.empty() && mod_dur != "forever";
1209  }
1210 
1211  return mod_dur == goal_dur;
1212 }
1213 
1215 {
1216  // If any modifications expire, then we will need to rebuild the unit.
1217  const unit_type* rebuild_from = nullptr;
1218  int hp = hit_points_;
1219  int mp = movement_;
1220  // Loop through all types of modifications.
1221  for(const auto& mod_name : ModificationTypes) {
1222  // Loop through all modifications of this type.
1223  // Looping in reverse since we may delete the current modification.
1224  for(int j = modifications_.child_count(mod_name)-1; j >= 0; --j)
1225  {
1226  const config& mod = modifications_.child(mod_name, j);
1227 
1228  if(mod_duration_match(mod["duration"], duration)) {
1229  // If removing this mod means reverting the unit's type:
1230  if(const config::attribute_value* v = mod.get("prev_type")) {
1231  rebuild_from = &get_unit_type(v->str());
1232  }
1233  // Else, if we have not already specified a type to build from:
1234  else if(rebuild_from == nullptr) {
1235  rebuild_from = &type();
1236  }
1237 
1238  modifications_.remove_child(mod_name, j);
1239  }
1240  }
1241  }
1242 
1243  if(rebuild_from != nullptr) {
1244  anim_comp_->clear_haloes();
1245  advance_to(*rebuild_from);
1246  hit_points_ = hp;
1247  movement_ = std::min(mp, max_movement_);
1248  }
1249 }
1250 
1252 {
1253  expire_modifications("turn");
1254 
1258  set_state(STATE_UNCOVERED, false);
1259 }
1260 
1262 {
1263  expire_modifications("turn end");
1264 
1265  set_state(STATE_SLOWED,false);
1267  resting_ = false;
1268  }
1269 
1270  set_state(STATE_NOT_MOVED,false);
1271  // Clear interrupted move
1273 }
1274 
1276 {
1277  // Set the goto-command to be going to no-where
1278  goto_ = map_location();
1279 
1280  // Expire all temporary modifications.
1282 
1283  heal_fully();
1284  set_state(STATE_SLOWED, false);
1285  set_state(STATE_POISONED, false);
1286  set_state(STATE_PETRIFIED, false);
1287  set_state(STATE_GUARDIAN, false);
1288 }
1289 
1290 void unit::heal(int amount)
1291 {
1292  int max_hp = max_hitpoints();
1293  if(hit_points_ < max_hp) {
1294  hit_points_ += amount;
1295 
1296  if(hit_points_ > max_hp) {
1297  hit_points_ = max_hp;
1298  }
1299  }
1300 
1301  if(hit_points_<1) {
1302  hit_points_ = 1;
1303  }
1304 }
1305 
1306 const std::set<std::string> unit::get_states() const
1307 {
1308  std::set<std::string> all_states = states_;
1309  for(const auto& state : known_boolean_state_names_) {
1310  if(get_state(state.second)) {
1311  all_states.insert(state.first);
1312  }
1313  }
1314 
1315  // Backwards compatibility for not_living. Don't remove before 1.12
1316  if(all_states.count("undrainable") && all_states.count("unpoisonable") && all_states.count("unplagueable")) {
1317  all_states.insert("not_living");
1318  }
1319 
1320  return all_states;
1321 }
1322 
1323 bool unit::get_state(const std::string& state) const
1324 {
1325  state_t known_boolean_state_id = get_known_boolean_state_id(state);
1326  if(known_boolean_state_id!=STATE_UNKNOWN){
1327  return get_state(known_boolean_state_id);
1328  }
1329 
1330  // Backwards compatibility for not_living. Don't remove before 1.12
1331  if(state == "not_living") {
1332  return
1333  get_state("undrainable") &&
1334  get_state("unpoisonable") &&
1335  get_state("unplagueable");
1336  }
1337 
1338  return states_.find(state) != states_.end();
1339 }
1340 
1341 void unit::set_state(state_t state, bool value)
1342 {
1343  known_boolean_states_[state] = value;
1344 }
1345 
1346 bool unit::get_state(state_t state) const
1347 {
1348  return known_boolean_states_[state];
1349 }
1350 
1352 {
1353  auto i = known_boolean_state_names_.find(state);
1354  if(i != known_boolean_state_names_.end()) {
1355  return i->second;
1356  }
1357 
1358  return STATE_UNKNOWN;
1359 }
1360 
1361 std::map<std::string, unit::state_t> unit::known_boolean_state_names_ {
1362  {"slowed", STATE_SLOWED},
1363  {"poisoned", STATE_POISONED},
1364  {"petrified", STATE_PETRIFIED},
1365  {"uncovered", STATE_UNCOVERED},
1366  {"not_moved", STATE_NOT_MOVED},
1367  {"unhealable", STATE_UNHEALABLE},
1368  {"guardian", STATE_GUARDIAN},
1369 };
1370 
1371 void unit::set_state(const std::string& state, bool value)
1372 {
1373  appearance_changed_ = true;
1374  state_t known_boolean_state_id = get_known_boolean_state_id(state);
1375  if(known_boolean_state_id != STATE_UNKNOWN) {
1376  set_state(known_boolean_state_id, value);
1377  return;
1378  }
1379 
1380  // Backwards compatibility for not_living. Don't remove before 1.12
1381  if(state == "not_living") {
1382  set_state("undrainable", value);
1383  set_state("unpoisonable", value);
1384  set_state("unplagueable", value);
1385  }
1386 
1387  if(value) {
1388  states_.insert(state);
1389  } else {
1390  states_.erase(state);
1391  }
1392 }
1393 
1394 bool unit::has_ability_by_id(const std::string& ability) const
1395 {
1396  for(const config::any_child &ab : this->abilities_.all_children_range()) {
1397  if(ab.cfg["id"] == ability) {
1398  return true;
1399  }
1400  }
1401 
1402  return false;
1403 }
1404 
1406 {
1409  while (i != this->abilities_.ordered_end()) {
1410  if(i->cfg["id"] == ability) {
1411  i = this->abilities_.erase(i);
1412  } else {
1413  ++i;
1414  }
1415  }
1416 }
1417 
1419 {
1420  for(const auto& a_ptr : attacks_) {
1421  if(a_ptr->get_changed()) {
1422  return true;
1423  }
1424 
1425  }
1426  return false;
1427 }
1428 void unit::write(config& cfg, bool write_all) const
1429 {
1430  config back;
1431  auto write_subtag = [&](const std::string& key, const config& child)
1432  {
1433  cfg.clear_children(key);
1434 
1435  if(!child.empty()) {
1436  cfg.add_child(key, child);
1437  } else {
1438  back.add_child(key, child);
1439  }
1440  };
1441 
1442  if(write_all || get_attr_changed(UA_MOVEMENT_TYPE)) {
1443  movement_type_.write(cfg);
1444  }
1445  if(write_all || get_attr_changed(UA_SMALL_PROFILE)) {
1446  cfg["small_profile"] = small_profile_;
1447  }
1448  if(write_all || get_attr_changed(UA_PROFILE)) {
1449  cfg["profile"] = profile_;
1450  }
1451  if(description_ != type().unit_description()) {
1452  cfg["description"] = description_;
1453  }
1454  if(write_all || get_attr_changed(UA_NOTES)) {
1455  for(const t_string& note : special_notes_) {
1456  cfg.add_child("special_note")["note"] = note;
1457  }
1458  }
1459 
1460  if(halo_.get()) {
1461  cfg["halo"] = *halo_;
1462  }
1463 
1464  if(ellipse_.get()) {
1465  cfg["ellipse"] = *ellipse_;
1466  }
1467 
1468  if(usage_.get()) {
1469  cfg["usage"] = *usage_;
1470  }
1471 
1472  write_upkeep(cfg["upkeep"]);
1473 
1474  cfg["hitpoints"] = hit_points_;
1475  if(write_all || get_attr_changed(UA_MAX_HP)) {
1476  cfg["max_hitpoints"] = max_hit_points_;
1477  }
1478  cfg["image_icon"] = type().icon();
1479  cfg["image"] = type().image();
1480  cfg["random_traits"] = random_traits_;
1481  cfg["generate_name"] = generate_name_;
1482  cfg["experience"] = experience_;
1483  if(write_all || get_attr_changed(UA_MAX_XP)) {
1484  cfg["max_experience"] = max_experience_;
1485  }
1486  cfg["recall_cost"] = recall_cost_;
1487 
1488  cfg["side"] = side_;
1489 
1490  cfg["type"] = type_id();
1491 
1492  if(type_id() != type().parent_id()) {
1493  cfg["parent_type"] = type().parent_id();
1494  }
1495 
1496  // Support for unit formulas in [ai] and unit-specific variables in [ai] [vars]
1497  formula_man_->write(cfg);
1498 
1499  cfg["gender"] = gender_string(gender_);
1500  cfg["variation"] = variation_;
1501  cfg["role"] = role_;
1502 
1503  config status_flags;
1504  for(const std::string& state : get_states()) {
1505  status_flags[state] = true;
1506  }
1507 
1508  write_subtag("variables", variables_);
1509  write_subtag("filter_recall", filter_recall_);
1510  write_subtag("status", status_flags);
1511 
1512  cfg.clear_children("events");
1513  cfg.append(events_);
1514 
1515  // Overlays are exported as the modifications that add them, not as an overlays= value,
1516  // however removing the key breaks the Gui Debug Tools.
1517  // \todo does anything depend on the key's value, other than the re-import code in unit::init?
1518  cfg["overlays"] = "";
1519 
1520  cfg["name"] = name_;
1521  cfg["id"] = id_;
1522  cfg["underlying_id"] = underlying_id_.value;
1523 
1524  if(can_recruit()) {
1525  cfg["canrecruit"] = true;
1526  }
1527 
1528  cfg["extra_recruit"] = utils::join(recruit_list_);
1529 
1530  cfg["facing"] = map_location::write_direction(facing_);
1531 
1532  cfg["goto_x"] = goto_.wml_x();
1533  cfg["goto_y"] = goto_.wml_y();
1534 
1535  cfg["moves"] = movement_;
1536  if(write_all || get_attr_changed(UA_MAX_MP)) {
1537  cfg["max_moves"] = max_movement_;
1538  }
1539  cfg["vision"] = vision_;
1540  cfg["jamming"] = jamming_;
1541 
1542  cfg["resting"] = resting_;
1543 
1544  if(write_all || get_attr_changed(UA_ADVANCE_TO)) {
1545  cfg["advances_to"] = utils::join(advances_to_);
1546  }
1547 
1548  cfg["race"] = race_->id();
1549  cfg["language_name"] = type_name_;
1550  cfg["undead_variation"] = undead_variation_;
1551  if(write_all || get_attr_changed(UA_LEVEL)) {
1552  cfg["level"] = level_;
1553  }
1554  if(write_all || get_attr_changed(UA_ALIGNMENT)) {
1555  cfg["alignment"] = alignment_.to_string();
1556  }
1557  cfg["flag_rgb"] = flag_rgb_;
1558  cfg["unrenamable"] = unrenamable_;
1559 
1560  cfg["attacks_left"] = attacks_left_;
1561  if(write_all || get_attr_changed(UA_MAX_AP)) {
1562  cfg["max_attacks"] = max_attacks_;
1563  }
1564  if(write_all || get_attr_changed(UA_ZOC)) {
1565  cfg["zoc"] = emit_zoc_;
1566  }
1567  cfg["hidden"] = hidden_;
1568 
1569  if(write_all || get_attr_changed(UA_ATTACKS) || get_attacks_changed()) {
1570  cfg.clear_children("attack");
1571  for(attack_ptr i : attacks_) {
1572  i->write(cfg.add_child("attack"));
1573  }
1574  }
1575 
1576  cfg["cost"] = unit_value_;
1577 
1578  write_subtag("modifications", modifications_);
1579  if(write_all || get_attr_changed(UA_ABILITIES)) {
1580  write_subtag("abilities", abilities_);
1581  }
1582  if(write_all || get_attr_changed(UA_ADVANCEMENTS)) {
1583  cfg.clear_children("advancement");
1584  for(const config& advancement : this->advancements_) {
1585  if(!advancement.empty()) {
1586  cfg.add_child("advancement", advancement);
1587  }
1588  }
1589  }
1590  cfg.append(back);
1591 }
1592 
1594 {
1595  if(dir != map_location::NDIRECTIONS && dir != facing_) {
1596  appearance_changed_ = true;
1597  facing_ = dir;
1598  }
1599  // Else look at yourself (not available so continue to face the same direction)
1600 }
1601 
1602 int unit::upkeep() const
1603 {
1604  // Leaders do not incur upkeep.
1605  if(can_recruit()) {
1606  return 0;
1607  }
1608 
1610 }
1611 
1612 bool unit::loyal() const
1613 {
1614  return boost::get<upkeep_loyal>(&upkeep_) != nullptr;
1615 }
1616 
1618 {
1619  int def = movement_type_.defense_modifier(terrain);
1620 #if 0
1621  // A [defense] ability is too costly and doesn't take into account target locations.
1622  // Left as a comment in case someone ever wonders why it isn't a good idea.
1623  unit_ability_list defense_abilities = get_abilities("defense");
1624  if(!defense_abilities.empty()) {
1625  unit_abilities::effect defense_effect(defense_abilities, def, false);
1626  def = defense_effect.get_composite_value();
1627  }
1628 #endif
1629  return def;
1630 }
1631 
1632 bool unit::resistance_filter_matches(const config& cfg, bool attacker, const std::string& damage_name, int res) const
1633 {
1634  if(!(cfg["active_on"].empty() || (attacker && cfg["active_on"] == "offense") || (!attacker && cfg["active_on"] == "defense"))) {
1635  return false;
1636  }
1637 
1638  const std::string& apply_to = cfg["apply_to"];
1639  if(!apply_to.empty()) {
1640  if(damage_name != apply_to) {
1641  if(apply_to.find(',') != std::string::npos &&
1642  apply_to.find(damage_name) != std::string::npos) {
1643  const std::vector<std::string>& vals = utils::split(apply_to);
1644  if(std::find(vals.begin(),vals.end(),damage_name) == vals.end()) {
1645  return false;
1646  }
1647  } else {
1648  return false;
1649  }
1650  }
1651  }
1652 
1653  if(!unit_abilities::filter_base_matches(cfg, res)) {
1654  return false;
1655  }
1656 
1657  return true;
1658 }
1659 
1660 int unit::resistance_against(const std::string& damage_name,bool attacker,const map_location& loc, const_attack_ptr weapon, const_attack_ptr opp_weapon) const
1661 {
1662  int res = movement_type_.resistance_against(damage_name);
1663 
1664  unit_ability_list resistance_abilities = get_abilities_weapons("resistance",loc, weapon, opp_weapon);
1665  for(unit_ability_list::iterator i = resistance_abilities.begin(); i != resistance_abilities.end();) {
1666  if(!resistance_filter_matches(*i->ability_cfg, attacker, damage_name, 100-res)) {
1667  i = resistance_abilities.erase(i);
1668  } else {
1669  ++i;
1670  }
1671  }
1672 
1673  if(!resistance_abilities.empty()) {
1674  unit_abilities::effect resist_effect(resistance_abilities, 100-res, false);
1675 
1676  res = 100 - std::min<int>(
1677  resist_effect.get_composite_value(),
1678  resistance_abilities.highest("max_value").first
1679  );
1680  }
1681 
1682  return res;
1683 }
1684 
1685 std::map<std::string, std::string> unit::advancement_icons() const
1686 {
1687  std::map<std::string,std::string> temp;
1688  if(!can_advance()) {
1689  return temp;
1690  }
1691 
1692  if(!advances_to_.empty()) {
1693  std::ostringstream tooltip;
1695 
1696  for(const std::string& s : advances_to()) {
1697  if(!s.empty()) {
1698  tooltip << s << std::endl;
1699  }
1700  }
1701 
1702  temp[image] = tooltip.str();
1703  }
1704 
1705  for(const config& adv : get_modification_advances()) {
1706  const std::string& image = adv["image"];
1707  if(image.empty()) {
1708  continue;
1709  }
1710 
1711  std::ostringstream tooltip;
1712  tooltip << temp[image];
1713 
1714  const std::string& tt = adv["description"];
1715  if(!tt.empty()) {
1716  tooltip << tt << std::endl;
1717  }
1718 
1719  temp[image] = tooltip.str();
1720  }
1721 
1722  return(temp);
1723 }
1724 
1725 std::vector<std::pair<std::string, std::string>> unit::amla_icons() const
1726 {
1727  std::vector<std::pair<std::string, std::string>> temp;
1728  std::pair<std::string, std::string> icon; // <image,tooltip>
1729 
1730  for(const config& adv : get_modification_advances()) {
1731  icon.first = adv["icon"].str();
1732  icon.second = adv["description"].str();
1733 
1734  for(unsigned j = 0, j_count = modification_count("advancement", adv["id"]); j < j_count; ++j) {
1735  temp.push_back(icon);
1736  }
1737  }
1738 
1739  return(temp);
1740 }
1741 
1742 std::vector<config> unit::get_modification_advances() const
1743 {
1744  std::vector<config> res;
1745  for(const config& adv : modification_advancements()) {
1746  if(adv["strict_amla"].to_bool() && !advances_to_.empty()) {
1747  continue;
1748  }
1749  if(const config& filter = adv.child("filter")) {
1750  if(!unit_filter(vconfig(filter)).matches(*this, loc_)) {
1751  continue;
1752  }
1753  }
1754 
1755  if(modification_count("advancement", adv["id"]) >= static_cast<unsigned>(adv["max_times"].to_int(1))) {
1756  continue;
1757  }
1758 
1759  std::vector<std::string> temp_require = utils::split(adv["require_amla"]);
1760  std::vector<std::string> temp_exclude = utils::split(adv["exclude_amla"]);
1761 
1762  if(temp_require.empty() && temp_exclude.empty()) {
1763  res.push_back(adv);
1764  continue;
1765  }
1766 
1767  std::sort(temp_require.begin(), temp_require.end());
1768  std::sort(temp_exclude.begin(), temp_exclude.end());
1769 
1770  std::vector<std::string> uniq_require, uniq_exclude;
1771 
1772  std::unique_copy(temp_require.begin(), temp_require.end(), std::back_inserter(uniq_require));
1773  std::unique_copy(temp_exclude.begin(), temp_exclude.end(), std::back_inserter(uniq_exclude));
1774 
1775  bool exclusion_found = false;
1776  for(const std::string& s : uniq_exclude) {
1777  int max_num = std::count(temp_exclude.begin(), temp_exclude.end(), s);
1778  int mod_num = modification_count("advancement", s);
1779  if(mod_num >= max_num) {
1780  exclusion_found = true;
1781  break;
1782  }
1783  }
1784 
1785  if(exclusion_found) {
1786  continue;
1787  }
1788 
1789  bool requirements_done = true;
1790  for(const std::string& s : uniq_require) {
1791  int required_num = std::count(temp_require.begin(), temp_require.end(), s);
1792  int mod_num = modification_count("advancement", s);
1793  if(required_num > mod_num) {
1794  requirements_done = false;
1795  break;
1796  }
1797  }
1798 
1799  if(requirements_done) {
1800  res.push_back(adv);
1801  }
1802  }
1803 
1804  return res;
1805 }
1806 
1807 void unit::set_advancements(std::vector<config> advancements)
1808 {
1810  this->advancements_.clear();
1811  for(config& advancement : advancements) {
1812  this->advancements_.push_back(new config());
1813  this->advancements_.back().swap(advancement);
1814  }
1815 }
1816 
1818 {
1819  return type_->id();
1820 }
1821 
1823 {
1825  profile_ = value;
1827 }
1828 
1829 std::size_t unit::modification_count(const std::string& mod_type, const std::string& id) const
1830 {
1831  std::size_t res = 0;
1832  for(const config& item : modifications_.child_range(mod_type)) {
1833  if(item["id"] == id) {
1834  ++res;
1835  }
1836  }
1837 
1838  // For backwards compatibility, if asked for "advancement", also count "advance"
1839  if(mod_type == "advancement") {
1840  res += modification_count("advance", id);
1841  }
1842 
1843  return res;
1844 }
1845 
1846 const std::set<std::string> unit::builtin_effects {
1847  "alignment", "attack", "defense", "ellipse", "experience", "fearless",
1848  "halo", "healthy", "hitpoints", "image_mod", "jamming", "jamming_costs",
1849  "loyal", "max_attacks", "max_experience", "movement", "movement_costs",
1850  "new_ability", "new_advancement", "new_animation", "new_attack", "overlay", "profile",
1851  "recall_cost", "remove_ability", "remove_advancement", "remove_attacks", "resistance",
1852  "status", "type", "variation", "vision", "vision_costs", "zoc"
1853 };
1854 
1856 {
1857  if(apply_to == "attack") {
1858  std::vector<t_string> attack_names;
1859 
1860  std::string desc;
1861  for(attack_ptr a : attacks_) {
1862  bool affected = a->describe_modification(effect, &desc);
1863  if(affected && !desc.empty()) {
1864  attack_names.emplace_back(a->name(), "wesnoth-units");
1865  }
1866  }
1867  if(!attack_names.empty()) {
1868  utils::string_map symbols;
1869  symbols["attack_list"] = utils::format_conjunct_list("", attack_names);
1870  symbols["effect_description"] = desc;
1871  return VGETTEXT("$attack_list|: $effect_description", symbols);
1872  }
1873  } else if(apply_to == "hitpoints") {
1874  const std::string& increase_total = effect["increase_total"];
1875  if(!increase_total.empty()) {
1876  return VGETTEXT(
1877  "<span color=\"$color\">$number_or_percent</span> HP",
1878  {{"number_or_percent", utils::print_modifier(increase_total)}, {"color", increase_total[0] == '-' ? "red" : "green"}});
1879  }
1880  } else {
1881  const std::string& increase = effect["increase"];
1882  if(increase.empty()) {
1883  return "";
1884  }
1885  if(apply_to == "movement") {
1886  return VNGETTEXT(
1887  "<span color=\"$color\">$number_or_percent</span> move",
1888  "<span color=\"$color\">$number_or_percent</span> moves",
1889  std::stoi(increase),
1890  {{"number_or_percent", utils::print_modifier(increase)}, {"color", increase[0] == '-' ? "red" : "green"}});
1891  } else if(apply_to == "vision") {
1892  return VGETTEXT(
1893  "<span color=\"$color\">$number_or_percent</span> vision",
1894  {{"number_or_percent", utils::print_modifier(increase)}, {"color", increase[0] == '-' ? "red" : "green"}});
1895  } else if(apply_to == "jamming") {
1896  return VGETTEXT(
1897  "<span color=\"$color\">$number_or_percent</span> jamming",
1898  {{"number_or_percent", utils::print_modifier(increase)}, {"color", increase[0] == '-' ? "red" : "green"}});
1899  } else if(apply_to == "max_experience") {
1900  // Unlike others, decreasing experience is a *GOOD* thing
1901  return VGETTEXT(
1902  "<span color=\"$color\">$number_or_percent</span> XP to advance",
1903  {{"number_or_percent", utils::print_modifier(increase)}, {"color", increase[0] == '-' ? "green" : "red"}});
1904  } else if(apply_to == "max_attacks") {
1905  return VNGETTEXT(
1906  "<span color=\"$color\">$number_or_percent</span> attack per turn",
1907  "<span color=\"$color\">$number_or_percent</span> attacks per turn",
1908  std::stoi(increase),
1909  {{"number_or_percent", utils::print_modifier(increase)}, {"color", increase[0] == '-' ? "red" : "green"}});
1910  } else if(apply_to == "recall_cost") {
1911  // Unlike others, decreasing recall cost is a *GOOD* thing
1912  return VGETTEXT(
1913  "<span color=\"$color\">$number_or_percent</span> cost to recall",
1914  {{"number_or_percent", utils::print_modifier(increase)}, {"color", increase[0] == '-' ? "green" : "red"}});
1915  }
1916  }
1917  return "";
1918 }
1919 
1920 void unit::apply_builtin_effect(std::string apply_to, const config& effect)
1921 {
1922  appearance_changed_ = true;
1923  if(apply_to == "fearless") {
1925  is_fearless_ = effect["set"].to_bool(true);
1926  } else if(apply_to == "healthy") {
1928  is_healthy_ = effect["set"].to_bool(true);
1929  } else if(apply_to == "profile") {
1930  if(const config::attribute_value* v = effect.get("portrait")) {
1931  set_big_profile((*v).str());
1932  }
1933 
1934  if(const config::attribute_value* v = effect.get("small_portrait")) {
1935  set_small_profile((*v).str());
1936  }
1937 
1938  if(const config::attribute_value* v = effect.get("description")) {
1939  description_ = *v;
1940  }
1941 
1942  if(config::const_child_itors cfg_range = effect.child_range("special_note")) {
1943  for(const config& c : cfg_range) {
1944  if(!c["remove"].to_bool()) {
1945  special_notes_.emplace_back(c["note"].t_str());
1946  } else {
1947  auto iter = std::find(special_notes_.begin(), special_notes_.end(), c["note"].t_str());
1948  if(iter != special_notes_.end()) {
1949  special_notes_.erase(iter);
1950  }
1951  }
1952  }
1953  }
1954  } else if(apply_to == "new_attack") {
1956  attacks_.emplace_back(new attack_type(effect));
1957  } else if(apply_to == "remove_attacks") {
1959  auto iter = std::remove_if(attacks_.begin(), attacks_.end(), [&effect](attack_ptr a) {
1960  return a->matches_filter(effect);
1961  });
1962 
1963  attacks_.erase(iter, attacks_.end());
1964  } else if(apply_to == "attack") {
1966  for(attack_ptr a : attacks_) {
1967  a->apply_modification(effect);
1968  }
1969  } else if(apply_to == "hitpoints") {
1970  LOG_UT << "applying hitpoint mod..." << hit_points_ << "/" << max_hit_points_ << std::endl;
1971  const std::string& increase_hp = effect["increase"];
1972  const std::string& increase_total = effect["increase_total"];
1973  const std::string& set_hp = effect["set"];
1974  const std::string& set_total = effect["set_total"];
1975 
1976  // If the hitpoints are allowed to end up greater than max hitpoints
1977  const bool violate_max = effect["violate_maximum"].to_bool();
1978 
1979  if(!set_hp.empty()) {
1980  if(set_hp.back() == '%') {
1981  hit_points_ = lexical_cast_default<int>(set_hp)*max_hit_points_/100;
1982  } else {
1983  hit_points_ = lexical_cast_default<int>(set_hp);
1984  }
1985  }
1986 
1987  if(!set_total.empty()) {
1988  if(set_total.back() == '%') {
1989  set_max_hitpoints(lexical_cast_default<int>(set_total)*max_hit_points_/100);
1990  } else {
1991  set_max_hitpoints(lexical_cast_default<int>(set_total));
1992  }
1993  }
1994 
1995  if(!increase_total.empty()) {
1996  // A percentage on the end means increase by that many percent
1998  }
1999 
2000  if(max_hit_points_ < 1)
2001  set_max_hitpoints(1);
2002 
2003  if(effect["heal_full"].to_bool()) {
2004  heal_fully();
2005  }
2006 
2007  if(!increase_hp.empty()) {
2009  }
2010 
2011  LOG_UT << "modded to " << hit_points_ << "/" << max_hit_points_ << std::endl;
2012  if(hit_points_ > max_hit_points_ && !violate_max) {
2013  LOG_UT << "resetting hp to max" << std::endl;
2015  }
2016 
2017  if(hit_points_ < 1) {
2018  hit_points_ = 1;
2019  }
2020  } else if(apply_to == "movement") {
2021  const std::string& increase = effect["increase"];
2022 
2023  if(!increase.empty()) {
2025  }
2026 
2027  set_total_movement(effect["set"].to_int(max_movement_));
2028 
2029  if(movement_ > max_movement_) {
2031  }
2032  } else if(apply_to == "vision") {
2033  const std::string& increase = effect["increase"];
2034 
2035  if(!increase.empty()) {
2036  const int current_vision = vision_ < 0 ? max_movement_ : vision_;
2037  vision_ = utils::apply_modifier(current_vision, increase, 1);
2038  }
2039 
2040  vision_ = effect["set"].to_int(vision_);
2041  } else if(apply_to == "jamming") {
2042  const std::string& increase = effect["increase"];
2043 
2044  if(!increase.empty()) {
2045  jamming_ = utils::apply_modifier(jamming_, increase, 1);
2046  }
2047 
2048  jamming_ = effect["set"].to_int(jamming_);
2049  } else if(apply_to == "experience") {
2050  const std::string& increase = effect["increase"];
2051  const std::string& set = effect["set"];
2052 
2053  if(!set.empty()) {
2054  if(set.back() == '%') {
2055  experience_ = lexical_cast_default<int>(set)*max_experience_/100;
2056  } else {
2057  experience_ = lexical_cast_default<int>(set);
2058  }
2059  }
2060 
2061  if(increase.empty() == false) {
2063  }
2064  } else if(apply_to == "max_experience") {
2065  const std::string& increase = effect["increase"];
2066  const std::string& set = effect["set"];
2067 
2068  if(set.empty() == false) {
2069  if(set.back() == '%') {
2070  set_max_experience(lexical_cast_default<int>(set)*max_experience_/100);
2071  } else {
2072  set_max_experience(lexical_cast_default<int>(set));
2073  }
2074  }
2075 
2076  if(increase.empty() == false) {
2078  }
2079  } else if(apply_to == upkeep_loyal::type()) {
2080  upkeep_ = upkeep_loyal();
2081  } else if(apply_to == "status") {
2082  const std::string& add = effect["add"];
2083  const std::string& remove = effect["remove"];
2084 
2085  for(const std::string& to_add : utils::split(add))
2086  {
2087  set_state(to_add, true);
2088  }
2089 
2090  for(const std::string& to_remove : utils::split(remove))
2091  {
2092  set_state(to_remove, false);
2093  }
2094  } else if(std::find(movetype::effects.cbegin(), movetype::effects.cend(), apply_to) != movetype::effects.cend()) {
2095  // "movement_costs", "vision_costs", "jamming_costs", "defense", "resistance"
2096  if(const config& ap = effect.child(apply_to)) {
2098  movement_type_.merge(ap, apply_to, effect["replace"].to_bool());
2099  }
2100  } else if(apply_to == "zoc") {
2101  if(const config::attribute_value* v = effect.get("value")) {
2103  emit_zoc_ = v->to_bool();
2104  }
2105  } else if(apply_to == "new_ability") {
2106  if(const config& ab_effect = effect.child("abilities")) {
2108  config to_append;
2109  for(const config::any_child &ab : ab_effect.all_children_range()) {
2110  if(!has_ability_by_id(ab.cfg["id"])) {
2111  to_append.add_child(ab.key, ab.cfg);
2112  }
2113  }
2114  this->abilities_.append(to_append);
2115  }
2116  } else if(apply_to == "remove_ability") {
2117  if(const config& ab_effect = effect.child("abilities")) {
2118  for(const config::any_child &ab : ab_effect.all_children_range()) {
2119  remove_ability_by_id(ab.cfg["id"]);
2120  }
2121  }
2122  } else if(apply_to == "image_mod") {
2123  LOG_UT << "applying image_mod" << std::endl;
2124  std::string mod = effect["replace"];
2125  if(!mod.empty()){
2126  image_mods_ = mod;
2127  }
2128  LOG_UT << "applying image_mod" << std::endl;
2129  mod = effect["add"].str();
2130  if(!mod.empty()){
2131  if(!image_mods_.empty()) {
2132  image_mods_ += '~';
2133  }
2134 
2135  image_mods_ += mod;
2136  }
2137 
2139  LOG_UT << "applying image_mod" << std::endl;
2140  } else if(apply_to == "new_animation") {
2141  anim_comp_->apply_new_animation_effect(effect);
2142  } else if(apply_to == "ellipse") {
2143  set_image_ellipse(effect["ellipse"]);
2144  } else if(apply_to == "halo") {
2145  set_image_halo(effect["halo"]);
2146  } else if(apply_to == "overlay") {
2147  const std::string& add = effect["add"];
2148  const std::string& replace = effect["replace"];
2149  const std::string& remove = effect["remove"];
2150 
2151  if(!add.empty()) {
2152  for(const auto& to_add : utils::parenthetical_split(add, ',')) {
2153  overlays_.push_back(to_add);
2154  }
2155  }
2156  if(!remove.empty()) {
2157  for(const auto& to_remove : utils::parenthetical_split(remove, ',')) {
2158  overlays_.erase(std::remove(overlays_.begin(), overlays_.end(), to_remove), overlays_.end());
2159  }
2160  }
2161  if(add.empty() && remove.empty() && !replace.empty()) {
2162  overlays_ = utils::parenthetical_split(replace, ',');
2163  }
2164  } else if(apply_to == "new_advancement") {
2165  const std::string& types = effect["types"];
2166  const bool replace = effect["replace"].to_bool(false);
2168 
2169  if(!types.empty()) {
2170  if(replace) {
2172  } else {
2173  std::vector<std::string> temp_advances = utils::parenthetical_split(types, ',');
2174  std::copy(temp_advances.begin(), temp_advances.end(), std::back_inserter(advances_to_));
2175  }
2176  }
2177 
2178  if(effect.has_child("advancement")) {
2179  if(replace) {
2180  advancements_.clear();
2181  }
2182 
2183  config temp = effect;
2184  boost::copy(effect.child_range("advancement"), boost::make_function_output_iterator(ptr_vector_pushback(advancements_)));
2185  }
2186  } else if(apply_to == "remove_advancement") {
2187  const std::string& types = effect["types"];
2188  const std::string& amlas = effect["amlas"];
2190 
2191  std::vector<std::string> temp_advances = utils::parenthetical_split(types, ',');
2193  for(const std::string& unit : temp_advances) {
2194  iter = std::find(advances_to_.begin(), advances_to_.end(), unit);
2195  if(iter != advances_to_.end()) {
2196  advances_to_.erase(iter);
2197  }
2198  }
2199 
2200  temp_advances = utils::parenthetical_split(amlas, ',');
2201 
2202  for(int i = advancements_.size() - 1; i >= 0; i--) {
2203  if(std::find(temp_advances.begin(), temp_advances.end(), advancements_[i]["id"]) != temp_advances.end()) {
2204  advancements_.erase(advancements_.begin() + i);
2205  }
2206  }
2207  } else if(apply_to == "alignment") {
2208  unit_type::ALIGNMENT new_align;
2209  if(new_align.parse(effect["set"])) {
2210  set_alignment(new_align);
2211  }
2212  } else if(apply_to == "max_attacks") {
2213  const std::string& increase = effect["increase"];
2214 
2215  if(!increase.empty()) {
2217  }
2218  } else if(apply_to == "recall_cost") {
2219  const std::string& increase = effect["increase"];
2220  const std::string& set = effect["set"];
2221  const int recall_cost = recall_cost_ < 0 ? resources::gameboard->teams().at(side_).recall_cost() : recall_cost_;
2222 
2223  if(!set.empty()) {
2224  if(set.back() == '%') {
2225  recall_cost_ = lexical_cast_default<int>(set)*recall_cost/100;
2226  } else {
2227  recall_cost_ = lexical_cast_default<int>(set);
2228  }
2229  }
2230 
2231  if(!increase.empty()) {
2232  recall_cost_ = utils::apply_modifier(recall_cost, increase, 1);
2233  }
2234  } else if(effect["apply_to"] == "variation") {
2235  variation_ = effect["name"].str();
2236  const unit_type* base_type = unit_types.find(type().parent_id());
2237  assert(base_type != nullptr);
2238  advance_to(*base_type);
2239  if(effect["heal_full"].to_bool(false)) {
2240  heal_fully();
2241  }
2242  } else if(effect["apply_to"] == "type") {
2243  std::string prev_type = effect["prev_type"];
2244  if(prev_type.empty()) {
2245  prev_type = type().parent_id();
2246  }
2247  const std::string& new_type_id = effect["name"];
2248  const unit_type* new_type = unit_types.find(new_type_id);
2249  if(new_type) {
2250  const bool heal_full = effect["heal_full"].to_bool(false);
2251  advance_to(*new_type);
2252  preferences::encountered_units().insert(new_type_id);
2253  if(heal_full) {
2254  heal_fully();
2255  }
2256  } else {
2257  WRN_UT << "unknown type= in [effect]apply_to=type, ignoring" << std::endl;
2258  }
2259  }
2260 }
2261 
2262 void unit::add_modification(const std::string& mod_type, const config& mod, bool no_add)
2263 {
2264  bool generate_description = mod["generate_description"].to_bool(true);
2265 
2266  if(no_add == false) {
2267  modifications_.add_child(mod_type, mod);
2268  }
2269 
2270  bool set_poisoned = false; // Tracks if the poisoned state was set after the type or variation was changed.
2271  config type_effect, variation_effect;
2272  std::vector<t_string> effects_description;
2273  for(const config& effect : mod.child_range("effect")) {
2274  // Apply SUF.
2275  if(const config& afilter = effect.child("filter")) {
2276  assert(resources::filter_con);
2277  if(!unit_filter(vconfig(afilter)).matches(*this, loc_)) {
2278  continue;
2279  }
2280  }
2281  const std::string& apply_to = effect["apply_to"];
2282  int times = effect["times"].to_int(1);
2283  t_string description;
2284 
2285  if(effect["times"] == "per level") {
2286  times = level_;
2287  }
2288 
2289  if(times) {
2290  while (times > 0) {
2291  times --;
2292 
2293  bool was_poisoned = get_state(STATE_POISONED);
2294  // Apply unit type/variation changes last to avoid double applying effects on advance.
2295  if(apply_to == "type") {
2296  set_poisoned = false;
2297  type_effect = effect;
2298  continue;
2299  }
2300  if(apply_to == "variation") {
2301  set_poisoned = false;
2302  variation_effect = effect;
2303  continue;
2304  }
2305 
2306  std::string description_component;
2307  if(resources::lua_kernel) {
2308  description_component = resources::lua_kernel->apply_effect(apply_to, *this, effect, true);
2309  } else if(builtin_effects.count(apply_to)) {
2310  // Normally, the built-in effects are dispatched through Lua so that a user
2311  // can override them if desired. However, since they're built-in, we can still
2312  // apply them if the lua kernel is unavailable.
2313  apply_builtin_effect(apply_to, effect);
2314  description_component = describe_builtin_effect(apply_to, effect);
2315  }
2316  if(!times) {
2317  description += description_component;
2318  }
2319  if(!was_poisoned && get_state(STATE_POISONED)) {
2320  set_poisoned = true;
2321  } else if(was_poisoned && !get_state(STATE_POISONED)) {
2322  set_poisoned = false;
2323  }
2324  } // end while
2325  } else { // for times = per level & level = 0 we still need to rebuild the descriptions
2326  if(resources::lua_kernel) {
2327  description += resources::lua_kernel->apply_effect(apply_to, *this, effect, false);
2328  } else if(builtin_effects.count(apply_to)) {
2329  description += describe_builtin_effect(apply_to, effect);
2330  }
2331  }
2332 
2333  if(effect["times"] == "per level" && !times) {
2334  description = VGETTEXT("$effect_description per level", {{"effect_description", description}});
2335  }
2336 
2337  if(!description.empty()) {
2338  effects_description.push_back(description);
2339  }
2340  }
2341  // Apply variations -- only apply if we are adding this for the first time.
2342  if((!type_effect.empty() || !variation_effect.empty()) && no_add == false) {
2343  if(!type_effect.empty()) {
2344  std::string description;
2345  if(resources::lua_kernel) {
2346  description = resources::lua_kernel->apply_effect(type_effect["apply_to"], *this, type_effect, true);
2347  } else if(builtin_effects.count(type_effect["apply_to"])) {
2348  apply_builtin_effect(type_effect["apply_to"], type_effect);
2349  description = describe_builtin_effect(type_effect["apply_to"], type_effect);
2350  }
2351  effects_description.push_back(description);
2352  }
2353  if(!variation_effect.empty()) {
2354  std::string description;
2355  if(resources::lua_kernel) {
2356  description = resources::lua_kernel->apply_effect(variation_effect["apply_to"], *this, variation_effect, true);
2357  } else if(builtin_effects.count(variation_effect["apply_to"])) {
2358  apply_builtin_effect(variation_effect["apply_to"], variation_effect);
2359  description = describe_builtin_effect(variation_effect["apply_to"], variation_effect);
2360  }
2361  effects_description.push_back(description);
2362  }
2363  if(set_poisoned)
2364  // An effect explicitly set the poisoned state, and this
2365  // should override the unit being immune to poison.
2366  set_state(STATE_POISONED, true);
2367  }
2368 
2369  t_string description;
2370 
2371  const t_string& mod_description = mod["description"];
2372  if(!mod_description.empty()) {
2373  description = mod_description;
2374  }
2375 
2376  // Punctuation should be translatable: not all languages use Latin punctuation.
2377  // (However, there maybe is a better way to do it)
2378  if(generate_description && !effects_description.empty()) {
2379  if(!mod_description.empty()) {
2380  description += "\n";
2381  }
2382 
2383  for(const auto& desc_line : effects_description) {
2384  description += desc_line + "\n";
2385  }
2386  }
2387 
2388  // store trait info
2389  if(mod_type == "trait") {
2390  add_trait_description(mod, description);
2391  }
2392 
2393  //NOTE: if not a trait, description is currently not used
2394 }
2395 
2396 void unit::add_trait_description(const config& trait, const t_string& description)
2397 {
2398  const std::string& gender_string = gender_ == unit_race::FEMALE ? "female_name" : "male_name";
2399  const auto& gender_specific_name = trait[gender_string];
2400 
2401  const t_string name = gender_specific_name.empty() ? trait["name"] : gender_specific_name;
2402 
2403  if(!name.empty()) {
2404  trait_names_.push_back(name);
2405  trait_descriptions_.push_back(description);
2406  }
2407 }
2408 
2410 {
2411  return type().icon().empty() ? type().image() : type().icon();
2412 }
2413 
2415 {
2416  return type().image().empty() ? type().icon() : type().image();
2417 }
2418 
2420 {
2421  log_scope("apply mods");
2422 
2423  variables_.clear_children("mods");
2424  if(modifications_.has_child("advance")) {
2425  deprecated_message("[advance]", DEP_LEVEL::PREEMPTIVE, {1, 15, 0}, "Use [advancement] instead.");
2426  }
2427  for (const config::any_child &mod : modifications_.all_children_range()) {
2428  add_modification(mod.key, mod.cfg, true);
2429  }
2430 }
2431 
2432 bool unit::invisible(const map_location& loc, bool see_all) const
2433 {
2434  if(loc != get_location()) {
2435  DBG_UT << "unit::invisible called: id = " << id() << " loc = " << loc << " get_loc = " << get_location() << std::endl;
2436  }
2437 
2438  // This is a quick condition to check, and it does not depend on the
2439  // location (so might as well bypass the location-based cache).
2440  if(get_state(STATE_UNCOVERED)) {
2441  return false;
2442  }
2443 
2444  // Fetch from cache
2445  /**
2446  * @todo FIXME: We use the cache only when using the default see_all=true
2447  * Maybe add a second cache if the see_all=false become more frequent.
2448  */
2449  if(see_all) {
2450  const auto itor = invisibility_cache_.find(loc);
2451  if(itor != invisibility_cache_.end()) {
2452  return itor->second;
2453  }
2454  }
2455 
2456  // Test hidden status
2457  static const std::string hides("hides");
2458  bool is_inv = get_ability_bool(hides, loc);
2459  if(is_inv){
2460  is_inv = (resources::gameboard ? !resources::gameboard->would_be_discovered(loc, side_,see_all) : true);
2461  }
2462 
2463  if(see_all) {
2464  // Add to caches
2465  if(invisibility_cache_.empty()) {
2466  units_with_cache.push_back(this);
2467  }
2468 
2469  invisibility_cache_[loc] = is_inv;
2470  }
2471 
2472  return is_inv;
2473 }
2474 
2475 bool unit::is_visible_to_team(const team& team, bool const see_all) const
2476 {
2477  const map_location& loc = get_location();
2478  return is_visible_to_team(loc, team, see_all);
2479 }
2480 
2481 bool unit::is_visible_to_team(const map_location& loc, const team& team, bool const see_all) const
2482 {
2483  if(!display::get_singleton()->get_map().on_board(loc)) {
2484  return false;
2485  }
2486 
2487  if(see_all) {
2488  return true;
2489  }
2490 
2491  if(team.is_enemy(side()) && invisible(loc)) {
2492  return false;
2493  }
2494 
2495  // allied planned moves are also visible under fog. (we assume that fake units on the map are always whiteboard markers)
2496  if(!team.is_enemy(side()) && underlying_id_.is_fake()) {
2497  return true;
2498  }
2499 
2500  // when the whiteboard planned unit map is applied, it uses moved the _real_ unit so
2501  // underlying_id_.is_fake() will be false and the check above will not apply.
2502  // TODO: improve this check so that is also works for allied planned units but without
2503  // breaking sp campaigns with allies under fog. We probably need an explicit flag
2504  // is_planned_ in unit that is set by the whiteboard.
2505  if(team.side() == side()) {
2506  return true;
2507  }
2508 
2509  if(team.fogged(loc)) {
2510  return false;
2511  }
2512 
2513  return true;
2514 }
2515 
2517 {
2518  if(underlying_id_.value == 0) {
2520  underlying_id_ = id_manager.next_id();
2521  } else {
2522  underlying_id_ = id_manager.next_fake_id();
2523  }
2524  }
2525 
2526  if(id_.empty() /*&& !underlying_id_.is_fake()*/) {
2527  std::stringstream ss;
2528  ss << (type_id().empty() ? "Unit" : type_id()) << "-" << underlying_id_.value;
2529  id_ = ss.str();
2530  }
2531 }
2532 
2533 unit& unit::mark_clone(bool is_temporary)
2534 {
2536  if(is_temporary) {
2537  underlying_id_ = ids.next_fake_id();
2538  } else {
2540  underlying_id_ = ids.next_id();
2541  }
2542  else {
2543  underlying_id_ = ids.next_fake_id();
2544  }
2545  std::string::size_type pos = id_.find_last_of('-');
2546  if(pos != std::string::npos && pos+1 < id_.size()
2547  && id_.find_first_not_of("0123456789", pos+1) == std::string::npos) {
2548  // this appears to be a duplicate of a generic unit, so give it a new id
2549  WRN_UT << "assigning new id to clone of generic unit " << id_ << std::endl;
2550  id_.clear();
2551  set_underlying_id(ids);
2552  }
2553  }
2554  return *this;
2555 }
2556 
2557 
2559  : u_(const_cast<unit&>(u))
2560  , moves_(u.movement_left(true))
2561 {
2562  if(operate) {
2564  }
2565 }
2566 
2568 {
2569  assert(resources::gameboard);
2570  try {
2571  if(!resources::gameboard->units().has_unit(&u_)) {
2572  /*
2573  * It might be valid that the unit is not in the unit map.
2574  * It might also mean a no longer valid unit will be assigned to.
2575  */
2576  DBG_UT << "The unit to be removed is not in the unit map." << std::endl;
2577  }
2578 
2580  } catch(...) {}
2581 }
2582 
2584 {
2585  return formatter() << "~RC(" << flag_rgb() << ">" << team::get_side_color_id(side()) << ")";
2586 }
2587 
2589 {
2590  if(!image_mods_.empty()) {
2591  return formatter() << "~" << image_mods_ << TC_image_mods();
2592  }
2593 
2594  return TC_image_mods();
2595 }
2596 
2597 // Called by the Lua API after resetting an attack pointer.
2599 {
2600  set_attr_changed(UA_ATTACKS);
2601  auto iter = std::find(attacks_.begin(), attacks_.end(), atk);
2602  if(iter == attacks_.end()) {
2603  return false;
2604  }
2605  attacks_.erase(iter);
2606  return true;
2607 }
2608 
2610 {
2611  if(attacks_left_ == max_attacks_) {
2612  //TODO: add state_not_attacked
2613  }
2614 
2615  set_attacks(0);
2616 }
2617 
2619 {
2620  if(movement_left() == total_movement()) {
2621  set_state(STATE_NOT_MOVED,true);
2622  }
2623 
2624  set_movement(0, true);
2625 }
2626 
2627 void unit::set_hidden(bool state) const
2628 {
2629 // appearance_changed_ = true;
2630  hidden_ = state;
2631  if(!state) {
2632  return;
2633  }
2634 
2635  // We need to get rid of haloes immediately to avoid display glitches
2636  anim_comp_->clear_haloes();
2637 }
2638 
2640 {
2641  appearance_changed_ = true;
2642  anim_comp_->clear_haloes();
2643  halo_.reset(new std::string(halo));
2644 }
2645 
2647 {
2648  if(upkeep.empty()) {
2649  return;
2650  }
2651 
2652  try {
2653  upkeep_ = upkeep.apply_visitor(upkeep_parser_visitor());
2654  } catch(std::invalid_argument& e) {
2655  WRN_UT << "Found invalid upkeep=\"" << e.what() << "\" in a unit" << std::endl;
2656  upkeep_ = upkeep_full();
2657  }
2658 }
2659 
2661 {
2662  upkeep = boost::apply_visitor(upkeep_type_visitor(), upkeep_);
2663 }
2664 
2666 {
2667  changed_attributes_.reset();
2668  for(const auto& a_ptr : attacks_) {
2669  a_ptr->set_changed(false);
2670  }
2671 }
2672 
2673 // Filters unimportant stats from the unit config and returns a checksum of
2674 // the remaining config.
2676 {
2677  config unit_config;
2678  config wcfg;
2679  u.write(unit_config);
2680 
2681  const std::array<std::string, 22> main_keys {{
2682  "advances_to",
2683  "alignment",
2684  "cost",
2685  "experience",
2686  "gender",
2687  "hitpoints",
2688  "ignore_race_traits",
2689  "ignore_global_traits",
2690  "level",
2691  "recall_cost",
2692  "max_attacks",
2693  "max_experience",
2694  "max_hitpoints",
2695  "max_moves",
2696  "movement",
2697  "movement_type",
2698  "race",
2699  "random_traits",
2700  "resting",
2701  "undead_variation",
2702  "upkeep",
2703  "zoc"
2704  }};
2705 
2706  for(const std::string& main_key : main_keys) {
2707  wcfg[main_key] = unit_config[main_key];
2708  }
2709 
2710  const std::array<std::string, 5> attack_keys {{
2711  "name",
2712  "type",
2713  "range",
2714  "damage",
2715  "number"
2716  }};
2717 
2718  for(const config& att : unit_config.child_range("attack")) {
2719  config& child = wcfg.add_child("attack");
2720 
2721  for(const std::string& attack_key : attack_keys) {
2722  child[attack_key] = att[attack_key];
2723  }
2724 
2725  for(const config& spec : att.child_range("specials")) {
2726  config& child_spec = child.add_child("specials", spec);
2727 
2728  child_spec.recursive_clear_value("description");
2729  }
2730  }
2731 
2732  for(const config& abi : unit_config.child_range("abilities")) {
2733  config& child = wcfg.add_child("abilities", abi);
2734 
2735  child.recursive_clear_value("description");
2736  child.recursive_clear_value("description_inactive");
2737  child.recursive_clear_value("name");
2738  child.recursive_clear_value("name_inactive");
2739  }
2740 
2741  for(const config& trait : unit_config.child_range("trait")) {
2742  config& child = wcfg.add_child("trait", trait);
2743 
2744  child.recursive_clear_value("description");
2745  child.recursive_clear_value("male_name");
2746  child.recursive_clear_value("female_name");
2747  child.recursive_clear_value("name");
2748  }
2749 
2750  const std::array<std::string, 6> child_keys {{
2751  "advance_from",
2752  "defense",
2753  "movement_costs",
2754  "vision_costs",
2755  "jamming_costs",
2756  "resistance"
2757  }};
2758 
2759  for(const std::string& child_key : child_keys) {
2760  for(const config& c : unit_config.child_range(child_key)) {
2761  wcfg.add_child(child_key, c);
2762  }
2763  }
2764 
2765  DBG_UT << wcfg;
2766 
2767  return wcfg.hash();
2768 }
2769 
2770 void swap(unit& lhs, unit& rhs)
2771 {
2772  lhs.swap(rhs);
2773 }
void set_wml_y(int v)
Definition: location.hpp:161
unit_id next_fake_id()
Definition: id.cpp:34
int defense_modifier(const t_translation::terrain_code &terrain) const
Returns the defensive value of the indicated terrain.
Definition: movetype.hpp:267
bool empty() const
Tests for an attribute that either was never set or was set to "".
void remove()
Removes a tip.
Definition: tooltip.cpp:189
const std::string & parent_id() const
The id of the original type from which this (variation) descended.
Definition: types.hpp:143
void set_movement(int moves, bool unit_action=false)
Set this unit&#39;s remaining movement to moves.
Definition: unit.cpp:1188
int max_attacks_
Definition: unit.hpp:1844
bool appearance_changed_
Definition: unit.hpp:1909
config modifications_
Definition: unit.hpp:1888
UNIT_ALIGNMENT ALIGNMENT
Definition: types.hpp:182
std::string apply_effect(const std::string &name, unit &u, const config &cfg, bool need_apply)
static DIRECTION parse_direction(const std::string &str)
Definition: location.cpp:65
std::vector< t_string > trait_descriptions_
Definition: unit.hpp:1871
bool empty() const
Definition: unit.hpp:101
config & child(config_key_type key, int n=0)
Returns the nth child with the given key, or a reference to an invalid config if there is none...
Definition: config.cpp:420
std::string format_conjunct_list(const t_string &empty, const std::vector< t_string > &elems)
Format a conjunctive list.
V::result_t apply_visitor(typename V::param_t state, T &&... args)
Helper function to apply the result of a specified visitor to a variable_info object.
static display * get_singleton()
Returns the display object if a display object exists.
Definition: display.hpp:88
void set_big_profile(const std::string &value)
Definition: unit.cpp:1822
const_all_children_itors all_children_range() const
In-order iteration over all children.
Definition: config.cpp:921
static state_t get_known_boolean_state_id(const std::string &state)
Convert a string status effect ID to a built-in status effect ID.
Definition: unit.cpp:1351
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
virtual const std::vector< team > & teams() const override
Definition: game_board.hpp:92
int jamming_
Definition: unit.hpp:1835
ptr_vector_pushback(boost::ptr_vector< config > &vec)
Definition: unit.cpp:256
vconfig child(const std::string &key) const
Returns a child of *this whose key is key.
Definition: variable.cpp:288
std::map< std::string, t_string > string_map
void apply_modifications()
Re-apply all saved modifications.
Definition: unit.cpp:2419
void clear_children(T... keys)
Definition: config.hpp:479
void recursive_clear_value(config_key_type key)
Definition: config.cpp:652
The unit is a guardian - it won&#39;t move unless a target is sighted.
Definition: unit.hpp:867
This class represents a single unit of a specific type.
Definition: unit.hpp:129
const std::string & type_id() const
The id of this unit&#39;s type.
Definition: unit.cpp:1817
std::string big_profile() const
An optional profile image displays when this unit is &#39;speaking&#39; via [message].
Definition: unit.cpp:1021
int level_
Definition: unit.hpp:1814
Interfaces for manipulating version numbers of engine, add-ons, etc.
bool generate_name() const
Definition: types.hpp:172
double hp_bar_scaling_
Definition: unit.hpp:1886
void append(const config &cfg)
Append data from another config object to this one.
Definition: config.cpp:287
std::string small_profile_
Definition: unit.hpp:1906
std::string join(const T &v, const std::string &s=",")
Generates a new string joining container items in a list.
void advance_to(const unit_type &t, bool use_traits=false)
Advances this unit to another type.
Definition: unit.cpp:891
void new_turn()
Refresh unit for the beginning of a turn.
Definition: unit.cpp:1251
The unit is uncovered - it was hiding but has been spotted.
Definition: unit.hpp:864
void set_usage(const std::string &usage)
Sets this unit&#39;s usage.
Definition: unit.hpp:693
bool hidden_
Definition: unit.hpp:1885
unit_id next_id()
returns id for unit that is created
Definition: id.cpp:27
std::string profile_
Definition: unit.hpp:1905
bool resting_
Definition: unit.hpp:1841
std::string id_
Definition: unit.hpp:1802
iterator erase(const iterator &erase_it)
Definition: unit.hpp:107
const std::string & id() const
Definition: race.hpp:34
config::const_child_itors events() const
Definition: types.hpp:231
Variant for storing WML attributes.
bool get_state(const std::string &state) const
Check if the unit is affected by a status effect.
Definition: unit.cpp:1323
const std::vector< t_string > & special_notes() const
Definition: types.cpp:499
unit_race::GENDER gender_
Definition: unit.hpp:1828
const std::string & big_profile() const
Definition: types.hpp:169
unit_race::GENDER gender() const
The gender of this unit.
Definition: unit.hpp:466
void check_types(const std::vector< std::string > &types) const
Definition: types.cpp:1180
const std::vector< std::string > & advances_to() const
A vector of unit_type ids that this unit_type can advance to.
Definition: types.hpp:113
static game_config_view wrap(const config &cfg)
static id_manager & global_instance()
Definition: id.hpp:60
New lexcical_cast header.
bool has_attribute(config_key_type key) const
Definition: config.cpp:213
#define a
int hitpoints() const
The current number of hitpoints this unit has.
Definition: unit.hpp:500
std::vector< t_string > trait_names_
Definition: unit.hpp:1870
bool generate_name_
Definition: unit.hpp:1901
map_location loc_
Definition: unit.hpp:1789
bool has_child(config_key_type key) const
Determine whether a config has a child or not.
Definition: config.cpp:412
const std::string & flag_rgb() const
Definition: types.cpp:689
unsigned child_count(config_key_type key) const
Definition: config.cpp:390
child_itors child_range(config_key_type key)
Definition: config.cpp:362
config & variables()
Gets any user-defined variables this unit &#39;owns&#39;.
Definition: unit.hpp:704
void set_image_ellipse(const std::string &ellipse)
Set the unit&#39;s ellipse image.
Definition: unit.hpp:1557
void set_small_profile(const std::string &value)
Definition: unit.hpp:597
A status effect not known to the engine.
Definition: unit.hpp:868
config events_
Definition: unit.hpp:1854
attribute_map::value_type attribute
Definition: config.hpp:226
void generate_traits(bool must_have_only=false)
Applies mandatory traits (e.g.
Definition: unit.cpp:814
map_location interrupted_move_
Definition: unit.hpp:1874
const attribute_value * get(config_key_type key) const
Returns a pointer to the attribute with the given key or nullptr if it does not exist.
Definition: config.cpp:742
std::string unit_rgb
t_string description_
Definition: unit.hpp:1893
const std::string & variation() const
The ID of the variation of this unit&#39;s type.
Definition: unit.hpp:573
void clear_changed_attributes()
Definition: unit.cpp:2665
int wml_x() const
Definition: location.hpp:157
The unit is poisoned - it loses health each turn.
Definition: unit.hpp:862
A terrain string which is converted to a terrain is a string with 1 or 2 layers the layers are separa...
Definition: translation.hpp:50
int experience_needed(bool with_acceleration=true) const
Definition: types.cpp:546
double xp_bar_scaling_
Definition: unit.hpp:1886
unit_type_data unit_types
Definition: types.cpp:1378
void set_wml_x(int v)
Definition: location.hpp:160
std::unique_ptr< unit_animation_component > anim_comp_
Definition: unit.hpp:1883
The unit is petrified - it cannot move or be attacked.
Definition: unit.hpp:863
const config & get_cfg() const
Definition: types.hpp:268
STL namespace.
int resistance_against(const attack_type &attack) const
Returns the resistance against the indicated attack.
Definition: movetype.hpp:271
std::string absolute_image() const
The name of the file to game_display (used in menus).
Definition: unit.cpp:2409
#define VNGETTEXT(msgid, msgid_plural, count,...)
bool matches(const unit &u, const map_location &loc) const
Determine if *this matches filter at a specified location.
Definition: filter.hpp:129
const std::string & variation_id() const
The id of this variation; empty if it&#39;s a gender variation or a base unit.
Definition: types.hpp:145
void clear()
Definition: config.cpp:863
void remove_attacks_ai()
Set the unit to have no attacks left for this turn.
Definition: unit.cpp:2609
UNIT_ALIGNMENT alignment_
Definition: unit.hpp:1819
std::string str
Definition: statement.cpp:110
void merge(const config &new_cfg, bool overwrite=true)
Merges the given config over the existing data, the config should have zero or more children named "m...
Definition: movetype.cpp:855
void write(config &cfg) const
Writes the movement type data to the provided config.
Definition: movetype.cpp:899
std::string flag_rgb_
Definition: unit.hpp:1821
-file sdl_utils.hpp
void set_facing(map_location::DIRECTION dir) const
The this unit&#39;s facing.
Definition: unit.cpp:1593
void set_interrupted_move(const map_location &interrupted_move)
Set the target location of the unit&#39;s interrupted move.
Definition: unit.hpp:1410
static int xp_to_advance(const std::string &s)
Definition: menu.cpp:115
std::string image_mods_
Definition: unit.hpp:1822
int recall_cost_
Definition: unit.hpp:1816
void set_total_movement(int value)
Definition: unit.hpp:1257
void operator()(const config &cfg)
Definition: unit.cpp:258
config filter_recall_
Definition: unit.hpp:1855
movetype movement_type_
Definition: unit.hpp:1837
bool canrecruit_
Definition: unit.hpp:1817
const_attr_itors attribute_range() const
Definition: config.cpp:809
bool hold_position_
Definition: unit.hpp:1839
A single unit type that the player may recruit.
Definition: types.hpp:44
void write(config &cfg, bool write_all=true) const
Serializes the current unit metadata values.
Definition: unit.cpp:1428
game_data * gamedata
Definition: resources.cpp:22
bool filter_base_matches(const config &cfg, int def)
Definition: abilities.cpp:1342
std::vector< std::string > recruit_list_
Definition: unit.hpp:1818
int hit_points_
Definition: unit.hpp:1809
int vision_
Definition: unit.hpp:1834
std::vector< unit_ability >::iterator iterator
Definition: unit.hpp:92
int unit_value_
Definition: unit.hpp:1873
state_t
Built-in status effects known to the engine.
Definition: unit.hpp:860
map_location loc_
upkeep_t upkeep_
Definition: unit.hpp:1903
void set_level(int level)
Sets the current level of this unit.
Definition: unit.hpp:566
std::bitset< num_bool_states > known_boolean_states_
Definition: unit.hpp:1850
const unit_type & type() const
This unit&#39;s type, accounting for gender and variation.
Definition: unit.hpp:353
color_t hp_color() const
Color for this unit&#39;s current hitpoints.
Definition: unit.cpp:1091
unsigned int experience_to_advance() const
The number of experience points this unit needs to level up, or 0 if current XP > max XP...
Definition: unit.hpp:542
Pubic entry points for the MP workflow.
Definition: lobby_data.cpp:51
void heal(int amount)
Heal the unit The number of hitpoints to gain.
Definition: unit.cpp:1290
void add_modification(const std::string &type, const config &modification, bool no_add=false)
Add a new modification to the unit.
Definition: unit.cpp:2262
int defense_modifier(const t_translation::terrain_code &terrain) const
The unit&#39;s defense on a given terrain.
Definition: unit.cpp:1617
static void clear_status_caches()
Clear this unit status cache for all units.
Definition: unit.cpp:688
bool is_fearless_
Definition: unit.hpp:1876
void set_advances_to(const std::vector< std::string > &advances_to)
Sets this unit&#39;s advancement options.
Definition: unit.cpp:1181
const_all_children_iterator ordered_end() const
Definition: config.cpp:911
child_list get_children(const std::string &key) const
Definition: variable.cpp:226
std::vector< std::string > overlays_
Definition: unit.hpp:1859
This class stores all the data for a single &#39;side&#39; (in game nomenclature).
Definition: team.hpp:44
void set_max_attacks(int value)
Definition: unit.hpp:981
#define LOG_UT
Definition: unit.cpp:80
A small explanation about what&#39;s going on here: Each action has access to two game_info objects First...
Definition: actions.cpp:59
config variables_
Definition: unit.hpp:1853
static const std::string & leader_crown()
The path to the leader crown overlay.
Definition: unit.cpp:1043
bool unrenamable_
Definition: unit.hpp:1824
static std::map< std::string, state_t > known_boolean_state_names_
Definition: unit.hpp:1851
int max_experience_
Definition: unit.hpp:1812
std::vector< t_string > special_notes_
Definition: unit.hpp:1894
const std::vector< unit_race::GENDER > & genders() const
The returned vector will not be empty, provided this has been built to the HELP_INDEXED status...
Definition: types.hpp:238
const std::string & id() const
Gets this unit&#39;s id.
Definition: unit.hpp:378
void swap(unit &)
Swap, for copy and swap idiom.
Definition: unit.cpp:741
std::string deprecated_message(const std::string &elem_name, DEP_LEVEL level, const version_info &version, const std::string &detail)
Definition: deprecation.cpp:29
int cost() const
Definition: types.hpp:162
void set_state(const std::string &state, bool value)
Set whether the unit is affected by a status effect.
Definition: unit.cpp:1371
int vision() const
Definition: types.hpp:157
static const unit_race null_race
Dummy race used when a race is not yet known.
Definition: race.hpp:68
void set_underlying_id(n_unit::id_manager &id_manager)
Sets the internal ID.
Definition: unit.cpp:2516
int movement_
Definition: unit.hpp:1832
const movetype & movement_type() const
Definition: types.hpp:178
bool is_healthy_
Definition: unit.hpp:1876
int max_hit_points_
Definition: unit.hpp:1810
The unit is slowed - it moves slower and does less damage.
Definition: unit.hpp:861
t_string name_
Definition: unit.hpp:1803
static const ::game_config_view * terrain
The terrain used to create the cache.
Definition: minimap.cpp:130
void set_recruits(const std::vector< std::string > &recruits)
Sets the recruit list.
Definition: unit.cpp:1157
std::ostringstream wrapper.
Definition: formatter.hpp:38
const t_string & type_name() const
The name of the unit in the current language setting.
Definition: types.hpp:136
bool get_attr_changed(UNIT_ATTRIBUTE attr) const
Definition: unit.hpp:184
void new_scenario()
Refresh unit for the beginning of a new scenario.
Definition: unit.cpp:1275
int wml_y() const
Definition: location.hpp:158
void set_alignment(UNIT_ALIGNMENT alignment)
Sets the alignment of this unit.
Definition: unit.hpp:482
filter_context * filter_con
Definition: resources.cpp:23
void parse_upkeep(const config::attribute_value &upkeep)
Definition: unit.cpp:2646
const std::vector< std::string > advances_to_translated() const
Gets the names of the possible types this unit can advance to on level-up.
Definition: unit.cpp:1166
const std::string & usage() const
Definition: types.hpp:165
void set_max_experience(int value)
Definition: unit.hpp:535
color_t xp_color() const
Color for this unit&#39;s XP.
Definition: unit.cpp:1145
game_board * gameboard
Definition: resources.cpp:20
std::string ellipse() const
Definition: types.hpp:171
static const std::set< std::string > effects
The set of applicable effects for movement types.
Definition: movetype.hpp:297
#define WRN_UT
Definition: unit.cpp:81
const t_string & name() const
Gets this unit&#39;s translatable display name.
Definition: unit.hpp:401
unit_race::GENDER string_gender(const std::string &str, unit_race::GENDER def)
Definition: race.cpp:143
int upkeep() const
Gets the amount of gold this unit costs a side per turn.
Definition: unit.cpp:1602
int kill_experience
Definition: game_config.cpp:57
std::vector< std::string > advances_to_t
Definition: unit.hpp:235
uint8_t r
Red value.
Definition: color.hpp:177
bool is_enemy(int n) const
Definition: team.hpp:243
int side_
Definition: unit.hpp:1826
std::size_t value
Definition: id.hpp:26
bool get_attacks_changed() const
Definition: unit.cpp:1418
const std::string & id() const
The id for this unit_type.
Definition: types.hpp:139
void set_hidden(bool state) const
Sets whether the unit is hidden on the map.
Definition: unit.cpp:2627
map_display and display: classes which take care of displaying the map and game-data on the screen...
std::string default_anim_image() const
The default image to use for animation frames with no defined image.
Definition: unit.cpp:2414
const std::vector< std::string > & overlays() const
Get the unit&#39;s overlay images.
Definition: unit.hpp:1585
boost::iterator_range< const_attribute_iterator > const_attr_itors
Definition: config.hpp:286
std::string small_profile() const
An optional profile image to display in Help.
Definition: unit.cpp:1030
The unit has not moved.
Definition: unit.hpp:865
void set_advancements(std::vector< config > advancements)
Sets the raw modification advancement option data.
Definition: unit.cpp:1807
bool mod_duration_match(const std::string &mod_dur, const std::string &goal_dur)
Determines if mod_dur "matches" goal_dur.
Definition: unit.cpp:1204
static color_t hp_color_max()
Definition: unit.cpp:1101
static void add_color_info(const game_config_view &v, bool build_defaults)
game_events::manager * game_events
Definition: resources.cpp:24
int max_movement_
Definition: unit.hpp:1833
all_children_iterator erase(const all_children_iterator &i)
Definition: config.cpp:689
std::string role_
Definition: unit.hpp:1861
void expire_modifications(const std::string &duration)
Clears those modifications whose duration has expired.
Definition: unit.cpp:1214
std::size_t modification_count(const std::string &type, const std::string &id) const
Count modifications of a particular type.
Definition: unit.cpp:1829
void set_attr_changed(UNIT_ATTRIBUTE attr)
Definition: unit.hpp:179
t_string type_name_
The displayed name of this unit type.
Definition: unit.hpp:1797
const std::string & gender_string(unit_race::GENDER gender)
Definition: race.cpp:133
std::string flag_rgb
static std::string get_side_color_id(unsigned side)
Definition: team.cpp:961
double xp_bar_scaling() const
Definition: types.hpp:153
unit & mark_clone(bool is_temporary)
Mark this unit as clone so it can be inserted to unit_map.
Definition: unit.cpp:2533
bool is_fake() const
Definition: id.hpp:28
bool loyal() const
Gets whether this unit is loyal - ie, it costs no upkeep.
Definition: unit.cpp:1612
Encapsulates the map of the game.
Definition: location.hpp:42
boost::iterator_range< const_child_iterator > const_child_itors
Definition: config.hpp:210
std::set< std::string > states_
Definition: unit.hpp:1846
bool invisible(const map_location &loc, bool see_all=true) const
Definition: unit.cpp:2432
const advancements_list & modification_advancements() const
The raw, unparsed data for modification advancements.
Definition: unit.hpp:321
const std::string & undead_variation() const
Info on the type of unit that the unit reanimates as.
Definition: types.hpp:131
#define DBG_UT
Definition: unit.cpp:79
const unit_race * race_
Never nullptr, but may point to the null race.
Definition: unit.hpp:1800
const std::string log_id() const
A variant on id() that is more descriptive, for use with message logging.
Definition: types.hpp:141
bool get_ability_bool(const std::string &tag_name, const map_location &loc) const
Checks whether this unit currently possesses or is affected by a given ability.
Definition: abilities.cpp:144
const unit_race * find_race(const std::string &) const
Definition: types.cpp:1265
void remove_ability_by_id(const std::string &ability)
Removes a unit&#39;s abilities with a specific ID.
Definition: unit.cpp:1405
bool has_zoc() const
Definition: types.hpp:217
void set_image_halo(const std::string &halo)
Set the unit&#39;s halo image.
Definition: unit.cpp:2639
void generate_name()
Generates a random race-appropriate name if one has not already been provided.
Definition: unit.cpp:805
void swap(unit &lhs, unit &rhs)
Implement non-member swap function for std::swap (calls unit::swap).
Definition: unit.cpp:2770
int attacks_left_
Definition: unit.hpp:1843
std::size_t i
Definition: function.cpp:933
int recall_cost() const
Definition: types.hpp:155
void set_undead_variation(const std::string &value)
The ID of the undead variation (ie, dwarf, swimmer) of this unit.
Definition: unit.hpp:579
int max_hitpoints() const
The max number of hitpoints this unit can have.
Definition: unit.hpp:506
Visitor helper class to fetch the appropriate upkeep value.
Definition: unit.hpp:1133
std::unique_ptr< std::string > usage_
Definition: unit.hpp:1896
std::string get_checksum(const unit &u)
Gets a checksum for a unit.
Definition: unit.cpp:2675
static map_location::DIRECTION s
const config & abilities_cfg() const
Definition: types.hpp:225
unit()=delete
void set_emit_zoc(bool val)
Sets the raw zone-of-control flag.
Definition: unit.hpp:1336
void add_trait_description(const config &trait, const t_string &description)
Register a trait&#39;s name and its description for the UI&#39;s use.
Definition: unit.cpp:2396
bool can_recruit() const
Whether this unit can recruit other units - ie, are they a leader unit.
Definition: unit.hpp:613
iterator begin()
Definition: unit.hpp:95
std::map< std::string, std::string > advancement_icons() const
Gets and image path and and associated description for each advancement option.
Definition: unit.cpp:1685
#define log_scope(description)
Definition: log.hpp:186
std::string halo() const
Definition: types.hpp:170
static std::string type()
Definition: unit.hpp:1129
int get_composite_value() const
Definition: abilities.hpp:48
DIRECTION
Valid directions which can be moved in our hexagonal world.
Definition: location.hpp:44
std::vector< std::string > advances_to_
Definition: unit.hpp:1791
const std::string & icon() const
Definition: types.hpp:167
void validate_side(int side)
Definition: team.cpp:759
std::vector< std::string > get_traits_list() const
Gets a list of the traits this unit currently has.
Definition: unit.cpp:871
int level() const
Definition: types.hpp:154
std::unique_ptr< unit_formula_manager > formula_man_
Definition: unit.hpp:1830
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 heal_fully()
Fully heal the unit, restoring it to max hitpoints.
Definition: unit.hpp:832
n_unit::unit_id underlying_id_
Definition: unit.hpp:1804
void set_max_hitpoints(int value)
Definition: unit.hpp:511
static int sort(lua_State *L)
Definition: ltablib.cpp:411
#define VGETTEXT(msgid,...)
Handy wrappers around interpolate_variables_into_string and gettext.
std::string variation_
Definition: unit.hpp:1807
const std::string & small_profile() const
Definition: types.hpp:168
int hitpoints() const
Definition: types.hpp:151
The unit cannot be healed.
Definition: unit.hpp:866
int jamming() const
Definition: types.hpp:160
unit_movement_resetter(const unit_movement_resetter &)=delete
rng * generator
This generator is automatically synced during synced context.
Definition: random.cpp:60
attack_list attacks_
Definition: unit.hpp:1862
int movement() const
Definition: types.hpp:156
std::map< map_location, bool > invisibility_cache_
Hold the visibility status cache for a unit, when not uncovered.
Definition: unit.hpp:1919
std::shared_ptr< attack_type > attack_ptr
Definition: ptr.hpp:35
config & add_child(config_key_type key)
Definition: config.cpp:476
bool is_visible_to_team(const team &team, bool const see_all=true) const
Definition: unit.cpp:2475
Handling of system events.
Definition: manager.hpp:42
const std::vector< std::string > & recruits() const
The type IDs of the other units this unit may recruit, if possible.
Definition: unit.hpp:625
const std::string & flag_rgb() const
Get the source color palette to use when recoloring the unit&#39;s image.
Definition: unit.cpp:1048
std::string undead_variation_
Definition: unit.hpp:1806
const_all_children_iterator ordered_begin() const
Definition: config.cpp:901
config::const_child_itors possible_traits() const
Definition: types.hpp:222
const std::string & image() const
Definition: types.hpp:166
static const unit_type & get_unit_type(const std::string &type_id)
Converts a string ID to a unit_type.
Definition: unit.cpp:215
Definition: display.hpp:44
const unit_type * type_
Never nullptr.
Definition: unit.hpp:1794
static unit_race::GENDER generate_gender(const unit_type &type, bool random_gender)
Definition: unit.cpp:227
bool empty() const
Definition: tstring.hpp:182
unit_type_error error
Definition: types.hpp:51
void init(const config &cfg, bool use_traits=false, const vconfig *vcfg=nullptr)
Definition: unit.cpp:425
void write_upkeep(config::attribute_value &upkeep) const
Definition: unit.cpp:2660
unsigned int num_traits() const
Definition: types.hpp:133
static const std::set< std::string > builtin_effects
Definition: unit.hpp:1503
n_unit::id_manager & unit_id_manager()
Definition: game_board.hpp:86
std::unique_ptr< std::string > halo_
Definition: unit.hpp:1897
double t
Definition: astarsearch.cpp:64
const unit_type & get_variation(const std::string &id) const
Definition: types.cpp:475
std::vector< std::string > split(const config_attribute_value &val)
bool find(E event, F functor)
Tests whether an event handler is available.
int apply_modifier(const int number, const std::string &amount, const int minimum)
std::vector< config > get_modification_advances() const
Gets any non-typed advanced options set by modifications.
Definition: unit.cpp:1742
int max_attacks() const
Definition: types.hpp:161
const map_location & get_location() const
The current map location this unit is at.
Definition: unit.hpp:1343
A variable-expanding proxy for the config class.
Definition: variable.hpp:44
const unit_race * race() const
Never returns nullptr, but may point to the null race.
Definition: types.hpp:264
this module manages the cache of images.
void adjust_profile(std::string &profile)
Definition: types.cpp:1380
const config & get_config() const
Definition: variable.hpp:82
Standard logging facilities (interface).
bool can_advance() const
Checks whether this unit has any options to advance to.
Definition: unit.hpp:269
void apply_builtin_effect(std::string type, const config &effect)
Apply a builtin effect to the unit.
Definition: unit.cpp:1920
V::result_type apply_visitor(const V &visitor) const
Applies a visitor to the underlying variant.
t_string unit_description() const
A detailed description of this unit.
Definition: unit.hpp:448
const unit_type & get_gender_unit_type(std::string gender) const
Returns a gendered variant of this unit_type.
Definition: types.cpp:454
static void check_id(std::string &id)
Validate the id argument.
Definition: types.cpp:1352
game_lua_kernel * lua_kernel
Definition: resources.cpp:25
std::string describe_builtin_effect(std::string type, const config &effect)
Construct a string describing a built-in effect.
Definition: unit.cpp:1855
map_location goto_
Definition: unit.hpp:1874
double hp_bar_scaling() const
Definition: types.hpp:152
int total_movement() const
The maximum moves this unit has.
Definition: unit.hpp:1252
const map_location goto_
Definition: move.cpp:309
bool fogged(const map_location &loc) const
Definition: team.cpp:662
#define e
int side() const
The side this unit belongs to.
Definition: unit.hpp:341
void end_turn()
Refresh unit for the end of a turn.
Definition: unit.cpp:1261
boost::ptr_vector< config > * vec_
Definition: unit.cpp:264
static color_t hp_color_impl(int hitpoints, int max_hitpoints)
Definition: unit.cpp:1053
const config & child_or_empty(config_key_type key) const
Returns the first child with the given key, or an empty config if there is none.
Definition: config.cpp:453
unit_ability_list get_abilities(const std::string &tag_name, const map_location &loc) const
Gets the unit&#39;s active abilities of a particular type if it were on a specified location.
Definition: abilities.cpp:184
const_attack_itors attacks() const
Definition: types.cpp:512
Visitor helper class to parse the upkeep value from a config.
Definition: unit.hpp:1179
int resistance_against(const std::string &damage_name, bool attacker, const map_location &loc, const_attack_ptr weapon=nullptr, const_attack_ptr opp_weapon=nullptr) const
The unit&#39;s resistance against a given damage type.
Definition: unit.cpp:1660
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
std::vector< vconfig > child_list
Definition: variable.hpp:85
std::vector< std::pair< std::string, std::string > > amla_icons() const
Gets the image and description data for modification advancements.
Definition: unit.cpp:1725
int side() const
Definition: team.hpp:188
t_string unit_description() const
Definition: types.cpp:485
#define ERR_UT
Definition: unit.cpp:82
Visitor helper struct to fetch the upkeep type flag if applicable, or the the value otherwise...
Definition: unit.hpp:1160
A config object defines a single node in a WML file, with access to child nodes.
Definition: config.hpp:68
bool null() const
Definition: variable.hpp:80
mock_char c
bool resistance_filter_matches(const config &cfg, bool attacker, const std::string &damage_name, int res) const
Definition: unit.cpp:1632
std::shared_ptr< const attack_type > const_attack_ptr
Definition: ptr.hpp:36
ALIGNMENT alignment() const
Definition: types.hpp:184
std::string TC_image_mods() const
Constructs a recolor (RC) IPF string for this unit&#39;s team color.
Definition: unit.cpp:2583
void remove_movement_ai()
Sets the unit to have no moves left for this turn.
Definition: unit.cpp:2618
const std::set< std::string > get_states() const
Get the status effects currently affecting the unit.
Definition: unit.cpp:1306
const advances_to_t & advances_to() const
Gets the possible types this unit can advance to on level-up.
Definition: unit.hpp:241
virtual ~unit()
Definition: unit.cpp:722
std::string print_modifier(const std::string &mod)
Add a "+" or replace the "-" par Unicode minus.
int recall_cost() const
How much gold it costs to recall this unit, or -1 if the side&#39;s default recall cost is used...
Definition: unit.hpp:641
static std::string write_direction(DIRECTION dir)
Definition: location.cpp:140
void remove_child(config_key_type key, unsigned index)
Definition: config.cpp:694
bool would_be_discovered(const map_location &loc, int side_num, bool see_all=true)
Given a location and a side number, indicates whether an invisible unit of that side at that location...
static rng & default_instance()
Definition: random.cpp:73
static bool is_synced()
std::string hash() const
Definition: config.cpp:1335
void add_events(const config::const_child_itors &cfgs, const std::string &type=std::string())
Definition: manager.cpp:115
static lg::log_domain log_unit("unit")
std::string::const_iterator iterator
Definition: tokenizer.hpp:24
int movement_left() const
Gets how far a unit can move, considering the incapacitated flag.
Definition: unit.hpp:1268
bool random_traits_
Definition: unit.hpp:1900
config abilities_
Definition: unit.hpp:1889
bool empty() const
Definition: config.cpp:884
std::bitset< UA_COUNT > changed_attributes_
Definition: unit.hpp:1910
int experience_
Definition: unit.hpp:1811
std::string image_mods() const
Gets an IPF string containing all IPF image mods.
Definition: unit.cpp:2588
bool has_ability_by_id(const std::string &ability) const
Check if the unit has an ability of a specific ID.
Definition: unit.cpp:1394
iterator end()
Definition: unit.hpp:97
utils::string_map modification_descriptions_
Definition: unit.hpp:1878
config::const_child_itors advancements() const
Definition: types.hpp:228
std::string generate_name(GENDER gender) const
Definition: race.cpp:105
bool end_turn_
Definition: unit.hpp:1840
std::pair< int, map_location > highest(const std::string &key, int def=0) const
Definition: unit.hpp:79
const std::string & default_variation() const
Definition: types.hpp:163
std::unique_ptr< std::string > ellipse_
Definition: unit.hpp:1898
std::pair< std::string, unsigned > item
Definition: help_impl.hpp:384
std::vector< std::string > parenthetical_split(const std::string &val, const char separator, const std::string &left, const std::string &right, const int flags)
Splits a string based either on a separator, except then the text appears within specified parenthesi...
auto * ss
Definition: result_set.cpp:281
map_location::DIRECTION facing_
Definition: unit.hpp:1867
bool emit_zoc_
Definition: unit.hpp:1857
bool remove_attack(attack_ptr atk)
Remove an attack from the unit.
Definition: unit.cpp:2598
advancements_list advancements_
Definition: unit.hpp:1891