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