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