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