The Battle for Wesnoth  1.17.0-dev
action_wml.cpp
Go to the documentation of this file.
1 /*
2  Copyright (C) 2003 - 2021
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  * Implementations of action WML tags, other than those implemented in Lua, and
18  * excluding conditional action WML.
19  */
20 
23 #include "game_events/pump.hpp"
24 
25 #include "actions/attack.hpp"
26 #include "actions/create.hpp"
27 #include "actions/move.hpp"
28 #include "actions/vision.hpp"
29 #include "ai/manager.hpp"
30 #include "fake_unit_ptr.hpp"
31 #include "filesystem.hpp"
32 #include "game_display.hpp"
33 #include "preferences/game.hpp"
34 #include "gettext.hpp"
36 #include "gui/widgets/retval.hpp"
37 #include "log.hpp"
38 #include "map/map.hpp"
39 #include "map/exception.hpp"
40 #include "map/label.hpp"
41 #include "pathfind/teleport.hpp"
42 #include "pathfind/pathfind.hpp"
43 #include "persist_var.hpp"
44 #include "play_controller.hpp"
45 #include "recall_list_manager.hpp"
46 #include "replay.hpp"
47 #include "random.hpp"
48 #include "mouse_handler_base.hpp" // for events::commands_disabled
49 #include "resources.hpp"
51 #include "side_filter.hpp"
52 #include "soundsource.hpp"
53 #include "synced_context.hpp"
54 #include "synced_user_choice.hpp"
55 #include "team.hpp"
56 #include "terrain/filter.hpp"
57 #include "units/unit.hpp"
59 #include "units/udisplay.hpp"
60 #include "units/filter.hpp"
61 #include "units/types.hpp"
62 #include "wml_exception.hpp"
63 #include "whiteboard/manager.hpp"
64 #include "deprecation.hpp"
65 
66 static lg::log_domain log_engine("engine");
67 #define DBG_NG LOG_STREAM(debug, log_engine)
68 #define LOG_NG LOG_STREAM(info, log_engine)
69 #define WRN_NG LOG_STREAM(warn, log_engine)
70 #define ERR_NG LOG_STREAM(err, log_engine)
71 
72 static lg::log_domain log_display("display");
73 #define DBG_DP LOG_STREAM(debug, log_display)
74 #define LOG_DP LOG_STREAM(info, log_display)
75 
76 static lg::log_domain log_wml("wml");
77 #define LOG_WML LOG_STREAM(info, log_wml)
78 #define WRN_WML LOG_STREAM(warn, log_wml)
79 #define ERR_WML LOG_STREAM(err, log_wml)
80 
81 static lg::log_domain log_config("config");
82 #define ERR_CF LOG_STREAM(err, log_config)
83 
84 
85 // This file is in the game_events namespace.
86 namespace game_events
87 {
88 
89 // This must be defined before any WML actions are.
90 // (So keep it at the rop of this file?)
92 
93 namespace { // Support functions
94 
95  /**
96  * Converts a vconfig to a location (based on x,y=).
97  * The default parameter values cause the default return value (if neither
98  * x nor y is specified) to equal map_location::null_location().
99  */
100  map_location cfg_to_loc(const vconfig& cfg, int defaultx = -999, int defaulty = -999)
101  {
102  return map_location(cfg["x"].to_int(defaultx), cfg["y"].to_int(defaulty), wml_loc());
103  }
104 
105  fake_unit_ptr create_fake_unit(const vconfig& cfg)
106  {
107  std::string type = cfg["type"];
108  std::string variation = cfg["variation"];
109  std::string img_mods = cfg["image_mods"];
110 
111  std::size_t side_num = cfg["side"].to_int(1);
112  if (!resources::gameboard->has_team(side_num)) {
113  side_num = 1;
114  }
115 
116  unit_race::GENDER gender = string_gender(cfg["gender"]);
117  const unit_type *ut = unit_types.find(type);
118  if (!ut) return fake_unit_ptr();
119  fake_unit_ptr fake = fake_unit_ptr(unit::create(*ut, side_num, false, gender));
120 
121  if(!variation.empty()) {
122  config mod;
123  config &effect = mod.add_child("effect");
124  effect["apply_to"] = "variation";
125  effect["name"] = variation;
126  fake->add_modification("variation",mod);
127  }
128 
129  if(!img_mods.empty()) {
130  config mod;
131  config &effect = mod.add_child("effect");
132  effect["apply_to"] = "image_mod";
133  effect["add"] = img_mods;
134  fake->add_modification("image_mod",mod);
135  }
136 
137  return fake;
138  }
139 
140  std::vector<map_location> fake_unit_path(const unit& fake_unit, const std::vector<std::string>& xvals, const std::vector<std::string>& yvals)
141  {
142  const gamemap *game_map = & resources::gameboard->map();
143  std::vector<map_location> path;
144  map_location src;
145  map_location dst;
146  for(std::size_t i = 0; i != std::min(xvals.size(),yvals.size()); ++i) {
147  if(i==0){
148  try {
149  src.set_wml_x(std::stoi(xvals[i]));
150  src.set_wml_y(std::stoi(yvals[i]));
151  } catch(std::invalid_argument&) {
152  ERR_CF << "Invalid move_unit_fake source: " << xvals[i] << ", " << yvals[i] << '\n';
153  continue;
154  }
155  if (!game_map->on_board(src)) {
156  ERR_CF << "Invalid move_unit_fake source: " << src << '\n';
157  break;
158  }
159  path.push_back(src);
160  continue;
161  }
162  pathfind::shortest_path_calculator calc(fake_unit,
163  resources::gameboard->get_team(fake_unit.side()),
164  resources::gameboard->teams(),
165  *game_map);
166 
167  try {
168  dst.set_wml_x(std::stoi(xvals[i]));
169  dst.set_wml_y(std::stoi(yvals[i]));
170  } catch(std::invalid_argument&) {
171  ERR_CF << "Invalid move_unit_fake destination: " << xvals[i] << ", " << yvals[i] << '\n';
172  }
173  if (!game_map->on_board(dst)) {
174  ERR_CF << "Invalid move_unit_fake destination: " << dst << '\n';
175  break;
176  }
177 
178  pathfind::plain_route route = pathfind::a_star_search(src, dst, 10000, calc,
179  game_map->w(), game_map->h());
180 
181  if (route.steps.empty()) {
182  WRN_NG << "Could not find move_unit_fake route from " << src << " to " << dst << ": ignoring complexities" << std::endl;
183  pathfind::emergency_path_calculator emergency_calc(fake_unit, *game_map);
184 
185  route = pathfind::a_star_search(src, dst, 10000, emergency_calc,
186  game_map->w(), game_map->h());
187  if(route.steps.empty()) {
188  // This would occur when trying to do a MUF of a unit
189  // over locations which are unreachable to it (infinite movement
190  // costs). This really cannot fail.
191  WRN_NG << "Could not find move_unit_fake route from " << src << " to " << dst << ": ignoring terrain" << std::endl;
192  pathfind::dummy_path_calculator dummy_calc(fake_unit, *game_map);
193  route = a_star_search(src, dst, 10000, dummy_calc, game_map->w(), game_map->h());
194  assert(!route.steps.empty());
195  }
196  }
197  // we add this section to the end of the complete path
198  // skipping section's head because already included
199  // by the previous iteration
200  path.insert(path.end(),
201  route.steps.begin()+1, route.steps.end());
202 
203  src = dst;
204  }
205  return path;
206  }
207 } // end anonymous namespace (support functions)
208 
209 /**
210  * Using this constructor for a static object outside action_wml.cpp
211  * will likely lead to a static initialization fiasco.
212  * @param[in] tag The WML tag for this action.
213  * @param[in] function The callback for this action.
214  */
215 wml_action::wml_action(const std::string & tag, handler function)
216 {
217  registry_[tag] = function;
218 }
219 
220 
221 /**
222  * WML_HANDLER_FUNCTION macro handles auto registration for wml handlers
223  *
224  * @param pname wml tag name
225  * @param pei the variable name of the queued_event object inside the function
226  * @param pcfg the variable name of the config object inside the function
227  *
228  * You are warned! This is evil macro magic!
229  *
230  * The following code registers a [foo] tag:
231  * \code
232  * // comment out unused parameters to prevent compiler warnings
233  * WML_HANDLER_FUNCTION(foo, event_info, cfg)
234  * {
235  * // code for foo
236  * }
237  * \endcode
238  *
239  * Generated code looks like this:
240  * \code
241  * void wml_func_foo(...);
242  * static wml_action wml_action_foo("foo", &wml_func_foo);
243  * void wml_func_foo(...)
244  * {
245  * // code for foo
246  * }
247  * \endcode
248  */
249 #define WML_HANDLER_FUNCTION(pname, pei, pcfg) \
250  static void wml_func_##pname(const queued_event &pei, const vconfig &pcfg); \
251  static wml_action wml_action_##pname(#pname, &wml_func_##pname); \
252  static void wml_func_##pname(const queued_event& pei, const vconfig& pcfg)
253 
254 
255 /**
256  * Experimental data persistence
257  * @todo Finish experimenting.
258  */
260 {
261  if (!resources::controller->is_replay())
263 }
264 
265 static void on_replay_error(const std::string& message)
266 {
267  ERR_NG << "Error via [do_command]:" << std::endl;
268  ERR_NG << message << std::endl;
269 }
270 
271 // This tag exposes part of the code path used to handle [command]'s in replays
272 // This allows to perform scripting in WML that will use the same code path as player actions, for example.
273 WML_HANDLER_FUNCTION(do_command,, cfg)
274 {
275  // Doing this in a whiteboard applied context will cause bugs
276  // Note that even though game_events::wml_event_pump() will always apply the real unit map
277  // It is still possible get a wml commands to run in a whiteboard applied context
278  // With the theme_items lua callbacks
279  if(resources::whiteboard->has_planned_unit_map())
280  {
281  ERR_NG << "[do_command] called while whiteboard is applied, ignoring" << std::endl;
282  return;
283  }
284 
285  static const std::set<std::string> allowed_tags {"attack", "move", "recruit", "recall", "disband", "fire_event", "custom_command"};
286 
287  const bool is_too_early = resources::gamedata->phase() != game_data::START && resources::gamedata->phase() != game_data::PLAY;
288  const bool is_unsynced_too_early = resources::gamedata->phase() != game_data::PLAY;
289  const bool is_unsynced = synced_context::get_synced_state() == synced_context::UNSYNCED;
290  if(is_too_early)
291  {
292  ERR_NG << "[do_command] called too early, only allowed at START or later" << std::endl;
293  return;
294  }
295  if(is_unsynced && resources::controller->is_lingering())
296  {
297  ERR_NG << "[do_command] cannot be used in linger mode" << std::endl;
298  return;
299  }
300  if(is_unsynced && !resources::controller->gamestate().init_side_done())
301  {
302  ERR_NG << "[do_command] cannot be used before the turn has started" << std::endl;
303  return;
304  }
305  if(is_unsynced && is_unsynced_too_early)
306  {
307  ERR_NG << "[do_command] called too early" << std::endl;
308  return;
309  }
310  if(is_unsynced && events::commands_disabled)
311  {
312  ERR_NG << "[do_command] cannot invoke synced commands while commands are blocked" << std::endl;
313  return;
314  }
315  if(is_unsynced && !resources::controller->current_team().is_local())
316  {
317  ERR_NG << "[do_command] can only be used from clients that control the currently playing side" << std::endl;
318  return;
319  }
320  for(const auto& [key, child] : cfg.all_ordered())
321  {
322  if(allowed_tags.find(key) == allowed_tags.end()) {
323  ERR_NG << "unsupported tag [" << key << "] in [do_command]" << std::endl;
324  std::stringstream o;
325  std::copy(allowed_tags.begin(), allowed_tags.end(), std::ostream_iterator<std::string>(o, " "));
326  ERR_NG << "allowed tags: " << o.str() << std::endl;
327  continue;
328  }
329  // TODO: afaik run_in_synced_context_if_not_already thows exceptions when the executed action end the scenario or the turn.
330  // This could cause problems, specially when its unclear whether that exception is caught by lua or not...
331 
332  //Note that this fires related events and everything else that also happens normally.
333  //have to watch out with the undo stack, therefore forbid [auto_shroud] and [update_shroud] here...
335  /*commandname*/ key,
336  /*data*/ child.get_parsed_config(),
337  /*use_undo*/ true,
338  /*show*/ true,
339  /*error_handler*/ &on_replay_error
340  );
342  }
343 }
344 
345 /**
346  * Experimental data persistence
347  * @todo Finish experimenting.
348  */
350 {
352 }
353 
354 WML_HANDLER_FUNCTION(modify_turns,, cfg)
355 {
356  config::attribute_value value = cfg["value"];
357  std::string add = cfg["add"];
358  config::attribute_value current = cfg["current"];
360  if(!add.empty()) {
361  tod_man.modify_turns_by_wml(add);
362  } else if(!value.empty()) {
363  tod_man.set_number_of_turns_by_wml(value.to_int(-1));
364  }
365  // change current turn only after applying mods
366  if(!current.empty()) {
367  const unsigned int current_turn_number = tod_man.turn();
368  int new_turn_number = current.to_int(current_turn_number);
369  const unsigned int new_turn_number_u = static_cast<unsigned int>(new_turn_number);
370  if(new_turn_number_u < 1 || (new_turn_number > tod_man.number_of_turns() && tod_man.number_of_turns() != -1)) {
371  ERR_NG << "attempted to change current turn number to one out of range (" << new_turn_number << ")" << std::endl;
372  } else if(new_turn_number_u != current_turn_number) {
373  tod_man.set_turn_by_wml(new_turn_number_u, resources::gamedata);
375  }
376  }
377 }
378 
379 /**
380  * Moving a 'unit' - i.e. a dummy unit
381  * that is just moving for the visual effect
382  */
383 WML_HANDLER_FUNCTION(move_unit_fake,, cfg)
384 {
386  events::command_disabler command_disabler;
387  fake_unit_ptr dummy_unit(create_fake_unit(cfg));
388  if(!dummy_unit.get())
389  return;
390 
391  const bool force_scroll = cfg["force_scroll"].to_bool(true);
392 
393  const std::string x = cfg["x"];
394  const std::string y = cfg["y"];
395 
396  const std::vector<std::string> xvals = utils::split(x);
397  const std::vector<std::string> yvals = utils::split(y);
398 
399  const std::vector<map_location>& path = fake_unit_path(*dummy_unit, xvals, yvals);
400  if (!path.empty()) {
401  // Always scroll.
402  unit_display::move_unit(path, dummy_unit.get_unit_ptr(), true, map_location::NDIRECTIONS, force_scroll);
403  }
404 }
405 
406 WML_HANDLER_FUNCTION(move_units_fake,, cfg)
407 {
409  events::command_disabler command_disabler;
410  LOG_NG << "Processing [move_units_fake]\n";
411 
412  const bool force_scroll = cfg["force_scroll"].to_bool();
413  const vconfig::child_list unit_cfgs = cfg.get_children("fake_unit");
414  std::size_t num_units = unit_cfgs.size();
415  std::vector<fake_unit_ptr > units;
416  units.reserve(num_units);
417  std::vector<std::vector<map_location>> paths;
418  paths.reserve(num_units);
419 
420  LOG_NG << "Moving " << num_units << " units\n";
421 
422  std::size_t longest_path = 0;
423 
424  for (const vconfig& config : unit_cfgs) {
425  const std::vector<std::string> xvals = utils::split(config["x"]);
426  const std::vector<std::string> yvals = utils::split(config["y"]);
427  int skip_steps = config["skip_steps"];
428  fake_unit_ptr u = create_fake_unit(config);
429  units.push_back(u);
430  paths.push_back(fake_unit_path(*u, xvals, yvals));
431  if(skip_steps > 0)
432  paths.back().insert(paths.back().begin(), skip_steps, paths.back().front());
433  longest_path = std::max(longest_path, paths.back().size());
434  DBG_NG << "Path " << paths.size() - 1 << " has length " << paths.back().size() << '\n';
435 
436  u->set_location(paths.back().front());
437  units.back().place_on_fake_unit_manager(resources::fake_units);
438  }
439 
440  LOG_NG << "Units placed, longest path is " << longest_path << " long\n";
441 
442  std::vector<map_location> path_step(2);
443  path_step.resize(2);
444  for(std::size_t step = 1; step < longest_path; ++step) {
445  DBG_NG << "Doing step " << step << "...\n";
446  for(std::size_t un = 0; un < num_units; ++un) {
447  if(step >= paths[un].size() || paths[un][step - 1] == paths[un][step])
448  continue;
449  DBG_NG << "Moving unit " << un << ", doing step " << step << '\n';
450  path_step[0] = paths[un][step - 1];
451  path_step[1] = paths[un][step];
452  unit_display::move_unit(path_step, units[un].get_unit_ptr(), true, map_location::NDIRECTIONS, force_scroll);
453  units[un]->set_location(path_step[1]);
454  units[un]->anim_comp().set_standing(false);
455  }
456  }
457 
458  LOG_NG << "Units moved\n";
459 }
460 
461 /**
462  * If we should recall units that match a certain description.
463  * If you change attributes specific to [recall] (that is, not a Standard Unit Filter)
464  * be sure to update data/lua/wml_tag, auto_recall feature for [role] to reflect your changes.
465  */
466 WML_HANDLER_FUNCTION(recall,, cfg)
467 {
468  events::command_disabler command_disabler;
469  LOG_NG << "recalling unit...\n";
470  config temp_config(cfg.get_config());
471  // Prevent the recall unit filter from using the location as a criterion
472 
473  /**
474  * FIXME: we should design the WML to avoid these types of
475  * collisions; filters should be named consistently and always have a
476  * distinct scope.
477  */
478  temp_config["x"] = "recall";
479  temp_config["y"] = "recall";
480  temp_config.remove_attribute("location_id");
481  vconfig unit_filter_cfg(temp_config);
482  const vconfig & leader_filter = cfg.child("secondary_unit");
483 
484  for(int index = 0; index < static_cast<int>(resources::gameboard->teams().size()); ++index) {
485  LOG_NG << "for side " << index + 1 << "...\n";
486  const std::string player_id = resources::gameboard->teams()[index].save_id_or_number();
487 
488  if(resources::gameboard->teams()[index].recall_list().size() < 1) {
489  DBG_NG << "recall list is empty when trying to recall!\n"
490  << "player_id: " << player_id << " side: " << index+1 << "\n";
491  continue;
492  }
493 
494  recall_list_manager & avail = resources::gameboard->teams()[index].recall_list();
495  std::vector<unit_map::unit_iterator> leaders = resources::gameboard->units().find_leaders(index + 1);
496 
497  const unit_filter ufilt(unit_filter_cfg);
498  const unit_filter lfilt(leader_filter); // Note that if leader_filter is null, this correctly gives a null filter that matches all units.
499  for(std::vector<unit_ptr>::iterator u = avail.begin(); u != avail.end(); ++u) {
500  DBG_NG << "checking unit against filter...\n";
501  scoped_recall_unit auto_store("this_unit", player_id, std::distance(avail.begin(), u));
502  if (ufilt(*(*u), map_location())) {
503  DBG_NG << (*u)->id() << " matched the filter...\n";
504  const unit_ptr to_recruit = *u;
505  const unit* pass_check = to_recruit.get();
506  if(!cfg["check_passability"].to_bool(true)) pass_check = nullptr;
507  map_location cfg_loc = cfg_to_loc(cfg);
508  if(cfg.has_attribute("location_id")) {
509  const auto& special_locs = resources::gameboard->map().special_locations().left;
510  const auto& iter = special_locs.find(cfg["location_id"]);
511  if(iter != special_locs.end()) {
512  cfg_loc = iter->second;
513  }
514  }
515 
516  for (unit_map::const_unit_iterator leader : leaders) {
517  DBG_NG << "...considering " + leader->id() + " as the recalling leader...\n";
518  map_location loc = cfg_loc;
519  if ( lfilt(*leader) &&
520  unit_filter(vconfig(leader->recall_filter())).matches( *(*u),map_location() ) ) {
521  DBG_NG << "...matched the leader filter and is able to recall the unit.\n";
522  if(!resources::gameboard->map().on_board(loc))
523  loc = leader->get_location();
524  if(pass_check || (resources::gameboard->units().count(loc) > 0))
525  loc = pathfind::find_vacant_tile(loc, pathfind::VACANT_ANY, pass_check);
526  if(resources::gameboard->map().on_board(loc)) {
527  DBG_NG << "...valid location for the recall found. Recalling.\n";
528  avail.erase(u); // Erase before recruiting, since recruiting can fire more events
529  actions::place_recruit(to_recruit, loc, leader->get_location(), 0, true,
530  map_location::parse_direction(cfg["facing"]),
531  cfg["show"].to_bool(true), cfg["fire_event"].to_bool(false),
532  true, true);
533  return;
534  }
535  }
536  }
537  if (resources::gameboard->map().on_board(cfg_loc)) {
538  map_location loc = cfg_loc;
539  if(pass_check || (resources::gameboard->units().count(loc) > 0))
540  loc = pathfind::find_vacant_tile(loc, pathfind::VACANT_ANY, pass_check);
541  // Check if we still have a valid location
542  if (resources::gameboard->map().on_board(loc)) {
543  DBG_NG << "No usable leader found, but found usable location. Recalling.\n";
544  avail.erase(u); // Erase before recruiting, since recruiting can fire more events
545  map_location null_location = map_location::null_location();
546  actions::place_recruit(to_recruit, loc, null_location, 0, true,
547  map_location::parse_direction(cfg["facing"]),
548  cfg["show"].to_bool(true), cfg["fire_event"].to_bool(false),
549  true, true);
550  return;
551  }
552  }
553  }
554  }
555  }
556  LOG_WML << "A [recall] tag with the following content failed:\n" << cfg.get_config().debug();
557 }
558 
559 namespace {
560  struct map_choice : public mp_sync::user_choice
561  {
562  map_choice(const std::string& filename) : filename_(filename) {}
563  std::string filename_;
564  virtual config query_user(int /*side*/) const override
565  {
566  std::string res = filesystem::read_map(filename_);
567  return config {"map_data", res};
568  }
569  virtual config random_choice(int /*side*/) const override
570  {
571  return config();
572  }
573  virtual std::string description() const override
574  {
575  return "Map Data";
576  }
577  virtual bool is_visible() const override
578  {
579  // Allow query_user() to be called during prestart events, as it doesn't show any UI.
580  return false;
581  }
582  };
583 }
584 
585 /**
586  * Experimental map replace
587  * @todo Finish experimenting.
588  */
589 WML_HANDLER_FUNCTION(replace_map,, cfg)
590 {
591  /*
592  * When a hex changes from a village terrain to a non-village terrain, and
593  * a team owned that village it loses that village. When a hex changes from
594  * a non-village terrain to a village terrain and there is a unit on that
595  * hex it does not automatically capture the village. The reason for not
596  * capturing villages it that there are too many choices to make; should a
597  * unit loose its movement points, should capture events be fired. It is
598  * easier to do this as wanted by the author in WML.
599  */
600 
601  const gamemap * game_map = & resources::gameboard->map();
602  gamemap map(*game_map);
603 
604  try {
605  if(!cfg["map_file"].empty()) {
606  config file_cfg = mp_sync::get_user_choice("map_data", map_choice(cfg["map_file"].str()));
607  map.read(file_cfg["map_data"].str(), false);
608  } else if(!cfg["map_data"].empty()) {
609  map.read(cfg["map_data"], false);
610  } else {
611  deprecated_message("[replace_map]map=", DEP_LEVEL::INDEFINITE, "1.16", "Use map_data= instead.");
612  map.read(cfg["map"], false);
613  }
614  } catch(const incorrect_map_format_error&) {
615  const std::string log_map_name = cfg["map"].empty() ? cfg["map_file"] : std::string("from inline data");
616  lg::log_to_chat() << "replace_map: Unable to load map " << log_map_name << '\n';
617  ERR_WML << "replace_map: Unable to load map " << log_map_name;
618  return;
619  } catch(const wml_exception& e) {
620  e.show();
621  return;
622  }
623 
624  if (map.total_width() > game_map->total_width()
625  || map.total_height() > game_map->total_height()) {
626  if (!cfg["expand"].to_bool()) {
627  lg::log_to_chat() << "replace_map: Map dimension(s) increase but expand is not set\n";
628  ERR_WML << "replace_map: Map dimension(s) increase but expand is not set";
629  return;
630  }
631  }
632 
633  if (map.total_width() < game_map->total_width()
634  || map.total_height() < game_map->total_height()) {
635  if (!cfg["shrink"].to_bool()) {
636  lg::log_to_chat() << "replace_map: Map dimension(s) decrease but shrink is not set\n";
637  ERR_WML << "replace_map: Map dimension(s) decrease but shrink is not set";
638  return;
639  }
640  }
641 
642  std::optional<std::string> errmsg = resources::gameboard->replace_map(map);
643 
644  if (errmsg) {
645  lg::log_to_chat() << *errmsg << '\n';
646  ERR_WML << *errmsg;
647  }
648 
652 }
653 
654 /**
655  * Experimental data persistence
656  * @todo Finish experimenting.
657  */
659 {
660  if (!resources::controller->is_replay())
662 }
663 
664 WML_HANDLER_FUNCTION(set_variables,, cfg)
665 {
666  const t_string& name = cfg["name"];
668  if(name.empty()) {
669  ERR_NG << "trying to set a variable with an empty name:\n" << cfg.get_config().debug();
670  return;
671  }
672 
673  std::vector<config> data;
674  if(cfg.has_attribute("to_variable"))
675  {
676  try
677  {
679  for (const config& c : tovar.as_array())
680  {
681  data.push_back(c);
682  }
683  }
684  catch(const invalid_variablename_exception&)
685  {
686  ERR_NG << "Cannot do [set_variables] with invalid to_variable variable: " << cfg["to_variable"] << " with " << cfg.get_config().debug() << std::endl;
687  }
688  } else {
689  typedef std::pair<std::string, vconfig> vchild;
690  for (const vchild& p : cfg.all_ordered()) {
691  if(p.first == "value") {
692  data.push_back(p.second.get_parsed_config());
693  } else if(p.first == "literal") {
694  data.push_back(p.second.get_config());
695  } else if(p.first == "split") {
696  const vconfig & split_element = p.second;
697 
698  std::string split_string=split_element["list"];
699  std::string separator_string=split_element["separator"];
700  std::string key_name=split_element["key"];
701  if(key_name.empty())
702  {
703  key_name="value";
704  }
705 
706  bool remove_empty = split_element["remove_empty"].to_bool();
707 
708  char* separator = separator_string.empty() ? nullptr : &separator_string[0];
709  if(separator_string.size() > 1){
710  ERR_NG << "[set_variables] [split] separator only supports 1 character, multiple passed: " << split_element["separator"] << " with " << cfg.get_config().debug() << std::endl;
711  }
712 
713  std::vector<std::string> split_vector;
714 
715  //if no separator is specified, explode the string
716  if(separator == nullptr)
717  {
718  for(std::string::iterator i=split_string.begin(); i!=split_string.end(); ++i)
719  {
720  split_vector.push_back(std::string(1, *i));
721  }
722  }
723  else {
724  split_vector=utils::split(split_string, *separator, remove_empty ? utils::REMOVE_EMPTY | utils::STRIP_SPACES : utils::STRIP_SPACES);
725  }
726 
727  for(std::vector<std::string>::iterator i=split_vector.begin(); i!=split_vector.end(); ++i)
728  {
729  data.emplace_back(key_name, *i);
730  }
731  }
732  }
733  }
734  try
735  {
736  const std::string& mode = cfg["mode"];
737  if(mode == "merge")
738  {
739  if(dest.explicit_index() && data.size() > 1)
740  {
741  //merge children into one
742  config merged_children;
743  for (const config &ch : data) {
744  merged_children.append(ch);
745  }
746  data = {merged_children};
747  }
748  dest.merge_array(data);
749  }
750  else if(mode == "insert")
751  {
752  dest.insert_array(data);
753  }
754  else if(mode == "append")
755  {
756  dest.append_array(data);
757  }
758  else /*default if(mode == "replace")*/
759  {
760  dest.replace_array(data);
761  }
762  }
763  catch(const invalid_variablename_exception&)
764  {
765  ERR_NG << "Cannot do [set_variables] with invalid destination variable: " << name << " with " << cfg.get_config().debug() << std::endl;
766  }
767 }
768 
769 /**
770  * Store the relative direction from one hex to another in a WML variable.
771  * This is mainly useful as a diagnostic tool, but could be useful
772  * for some kind of scenario.
773  */
774 WML_HANDLER_FUNCTION(store_relative_direction,, cfg)
775 {
776  if (!cfg.child("source")) {
777  WRN_NG << "No source in [store_relative_direction]" << std::endl;
778  return;
779  }
780  if (!cfg.child("destination")) {
781  WRN_NG << "No destination in [store_relative_direction]" << std::endl;
782  return;
783  }
784  if (!cfg.has_attribute("variable")) {
785  WRN_NG << "No variable in [store_relative_direction]" << std::endl;
786  return;
787  }
788 
789  const map_location src = cfg_to_loc(cfg.child("source"));
790  const map_location dst = cfg_to_loc(cfg.child("destination"));
791 
792  std::string variable = cfg["variable"];
793  map_location::RELATIVE_DIR_MODE mode = static_cast<map_location::RELATIVE_DIR_MODE> (cfg["mode"].to_int(0));
794  try
795  {
797 
799  }
800  catch(const invalid_variablename_exception&)
801  {
802  ERR_NG << "Cannot do [store_relative_direction] with invalid destination variable: " << variable << " with " << cfg.get_config().debug() << std::endl;
803  }
804 }
805 
806 /**
807  * Store the rotation of one hex around another in a WML variable.
808  * In increments of 60 degrees, clockwise.
809  * This is mainly useful as a diagnostic tool, but could be useful
810  * for some kind of scenario.
811  */
812 WML_HANDLER_FUNCTION(store_rotate_map_location,, cfg)
813 {
814  if (!cfg.child("source")) {
815  WRN_NG << "No source in [store_rotate_map_location]" << std::endl;
816  return;
817  }
818  if (!cfg.child("destination")) {
819  WRN_NG << "No destination in [store_rotate_map_location]" << std::endl;
820  return;
821  }
822  if (!cfg.has_attribute("variable")) {
823  WRN_NG << "No variable in [store_rotate_map_location]" << std::endl;
824  return;
825  }
826 
827  const map_location src = cfg_to_loc(cfg.child("source"));
828  const map_location dst = cfg_to_loc(cfg.child("destination"));
829 
830  std::string variable = cfg["variable"];
831  int angle = cfg["angle"].to_int(1);
832 
833  try
834  {
836 
837  dst.rotate_right_around_center(src,angle).write(store.as_container());
838  }
839  catch(const invalid_variablename_exception&)
840  {
841  ERR_NG << "Cannot do [store_rotate_map_location] with invalid destination variable: " << variable << " with " << cfg.get_config().debug() << std::endl;
842  }
843 }
844 
845 WML_HANDLER_FUNCTION(tunnel,, cfg)
846 {
847  const bool remove = cfg["remove"].to_bool(false);
848  const bool delay = cfg["delayed_variable_substitution"].to_bool(true);
849  if (remove) {
850  const std::vector<std::string> ids = utils::split(cfg["id"]);
851  for (const std::string &id : ids) {
853  }
854  } else if (cfg.get_children("source").empty() ||
855  cfg.get_children("target").empty() ||
856  cfg.get_children("filter").empty()) {
857  ERR_WML << "[tunnel] is missing a mandatory tag:\n"
858  << cfg.get_config().debug();
859  } else {
860  pathfind::teleport_group tunnel(delay ? cfg : vconfig(cfg.get_parsed_config()), false);
861  resources::tunnels->add(tunnel);
862 
863  if(cfg["bidirectional"].to_bool(true)) {
864  tunnel = pathfind::teleport_group(delay ? cfg : vconfig(cfg.get_parsed_config()), true);
865  resources::tunnels->add(tunnel);
866  }
867  }
868 }
869 
870 /** If we should spawn a new unit on the map somewhere */
872 {
873  events::command_disabler command_disabler;
874  config parsed_cfg = cfg.get_parsed_config();
875 
876  config::attribute_value to_variable = cfg["to_variable"];
877  if (!to_variable.blank())
878  {
879  parsed_cfg.remove_attribute("to_variable");
880  unit_ptr new_unit = unit::create(parsed_cfg, true, &cfg);
881  try
882  {
883  config &var = resources::gamedata->get_variable_cfg(to_variable);
884  var.clear();
885  new_unit->write(var);
886  if (const config::attribute_value *v = parsed_cfg.get("x")) var["x"] = *v;
887  if (const config::attribute_value *v = parsed_cfg.get("y")) var["y"] = *v;
888  }
889  catch(const invalid_variablename_exception&)
890  {
891  ERR_NG << "Cannot do [unit] with invalid to_variable: " << to_variable << " with " << cfg.get_config().debug() << std::endl;
892  }
893  return;
894 
895  }
896 
897  int side = parsed_cfg["side"].to_int(1);
898 
899 
900  if ((side<1)||(side > static_cast<int>(resources::gameboard->teams().size()))) {
901  ERR_NG << "wrong side in [unit] tag - no such side: "<<side<<" ( number of teams :"<<resources::gameboard->teams().size()<<")"<<std::endl;
902  DBG_NG << parsed_cfg.debug();
903  return;
904  }
905  team &tm = resources::gameboard->get_team(side);
906 
907  unit_creator uc(tm,resources::gameboard->map().starting_position(side));
908 
909  uc
910  .allow_add_to_recall(true)
911  .allow_discover(true)
912  .allow_get_village(true)
913  .allow_invalidate(true)
914  .allow_rename_side(true)
915  .allow_show(true);
916 
917  uc.add_unit(parsed_cfg, &cfg);
918 
919 }
920 
921 WML_HANDLER_FUNCTION(on_undo, event_info, cfg)
922 {
923  if(cfg["delayed_variable_substitution"].to_bool(false)) {
924  synced_context::add_undo_commands(cfg.get_config(), event_info);
925  } else {
926  synced_context::add_undo_commands(cfg.get_parsed_config(), event_info);
927  }
928 }
929 
930 } // end namespace game_events
void set_wml_y(int v)
Definition: location.hpp:156
std::optional< std::string > replace_map(const gamemap &r)
Definition: game_board.cpp:289
void verify_and_get_global_variable(const vconfig &pcfg)
play_controller * controller
Definition: resources.cpp:21
static void add_undo_commands(const config &commands, const game_events::queued_event &ctx)
bool empty() const
Tests for an attribute that either was never set or was set to "".
std::map< std::string, handler > map
Definition: action_wml.hpp:50
unit_creator & allow_rename_side(bool b)
config get_user_choice(const std::string &name, const user_choice &uch, int side=0)
static synced_state get_synced_state()
#define ERR_NG
Definition: action_wml.cpp:70
static void get_global_variable(persist_context &ctx, const vconfig &pcfg)
Definition: persist_var.cpp:63
static DIRECTION parse_direction(const std::string &str)
Definition: location.cpp:65
::tod_manager * tod_manager
Definition: resources.cpp:29
std::vector< unit_iterator > find_leaders(int side)
Definition: map.cpp:354
static display * get_singleton()
Returns the display object if a display object exists.
Definition: display.hpp:91
Function which doesn&#39;t take anything into account.
Definition: pathfind.hpp:254
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:1261
virtual const std::vector< team > & teams() const override
Definition: game_board.hpp:84
location_map & special_locations()
Definition: map.hpp:89
vconfig child(const std::string &key) const
Returns a child of *this whose key is key.
Definition: variable.cpp:286
virtual const unit_map & units() const override
Definition: game_board.hpp:111
DIRECTION get_relative_dir(const map_location &loc, map_location::RELATIVE_DIR_MODE mode) const
Definition: location.cpp:226
#define LOG_NG
Definition: action_wml.cpp:68
This class represents a single unit of a specific type.
Definition: unit.hpp:120
wml_action(const std::string &tag, handler function)
Using this constructor for a static object outside action_wml.cpp will likely lead to a static initia...
Definition: action_wml.cpp:215
void append(const config &cfg)
Append data from another config object to this one.
Definition: config.cpp:284
Various functions implementing vision (through fog of war and shroud).
static manager & get_singleton()
Definition: manager.hpp:143
void raise_gamestate_changed()
Notifies all observers of &#39;ai_gamestate_changed&#39; event.
Definition: manager.cpp:410
unit_creator & allow_invalidate(bool b)
static void set_global_variable(persist_context &ctx, const vconfig &pcfg)
Definition: persist_var.cpp:98
unit_creator & allow_show(bool b)
bool explicit_index() const
Various functions that implement attacks and attack calculations.
void remove(const std::string &id)
Definition: teleport.cpp:307
Variant for storing WML attributes.
Add a special kind of assert to validate whether the input from WML doesn&#39;t contain any problems that...
internal_ptr get_unit_ptr()
Get a copy of the internal unit pointer.
config & get_variable_cfg(const std::string &varname)
throws invalid_variablename_exception if varname is no valid variable name.
Definition: game_data.cpp:79
void raise_map_changed()
Notifies all observers of &#39;ai_map_changed&#39; event.
Definition: manager.cpp:426
maybe_const_t< config::attribute_value, V > & as_scalar() const
If instantiated with vi_policy_const, the lifetime of the returned const attribute_value reference mi...
#define LOG_WML
Definition: action_wml.cpp:77
map_location find_vacant_tile(const map_location &loc, VACANT_TILE_TYPE vacancy, const unit *pass_check, const team *shroud_check, const game_board *board)
Function that will find a location on the board that is as near to loc as possible, but which is unoccupied by any units.
Definition: pathfind.cpp:53
unit_creator & allow_discover(bool b)
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:769
virtual const gamemap & map() const override
Definition: game_board.hpp:101
WML_HANDLER_FUNCTION(clear_global_variable,, pcfg)
Experimental data persistence.
Definition: action_wml.cpp:259
void modify_turns_by_wml(const std::string &mod)
unit_type_data unit_types
Definition: types.cpp:1480
void set_wml_x(int v)
Definition: location.hpp:155
Define actions for the game&#39;s events mechanism.
config::child_itors insert_array(std::vector< config > children) const
Replay control code.
This class encapsulates the recall list of a team.
static lg::log_domain log_config("config")
void verify_and_set_global_variable(const vconfig &pcfg)
bool matches(const unit &u, const map_location &loc) const
Determine if *this matches filter at a specified location.
Definition: filter.hpp:131
Additional functionality for a non-const variable_info.
maybe_const_t< config, V > & as_container() const
If instantiated with vi_policy_const, the lifetime of the returned const attribute_value reference mi...
void clear()
Definition: config.cpp:899
An object to leave the synced context during draw or unsynced wml items when we don’t know whether w...
void remove_attribute(config_key_type key)
Definition: config.cpp:232
bool empty() const
Definition: variable.hpp:98
unit_creator & allow_add_to_recall(bool b)
std::shared_ptr< unit > unit_ptr
Definition: ptr.hpp:25
void new_turn()
Update lighting settings.
static unit_ptr create(const config &cfg, bool use_traits=false, const vconfig *vcfg=nullptr)
Initializes a unit from a config.
Definition: unit.hpp:189
A single unit type that the player may recruit.
Definition: types.hpp:44
game_data * gamedata
Definition: resources.cpp:22
std::string filename_
Definition: action_wml.cpp:563
#define WRN_NG
Definition: action_wml.cpp:69
void show() const
Shows the error in a dialog.
This class stores all the data for a single &#39;side&#39; (in game nomenclature).
Definition: team.hpp:71
team & get_team(int i)
Definition: game_board.hpp:96
std::size_t size(const std::string &str)
Length in characters of a UTF-8 string.
Definition: unicode.cpp:84
#define ERR_WML
Definition: action_wml.cpp:79
std::vector< map_location > steps
Definition: pathfind.hpp:134
#define DBG_NG
Definition: action_wml.cpp:67
void set_number_of_turns_by_wml(int num)
std::string deprecated_message(const std::string &elem_name, DEP_LEVEL level, const version_info &version, const std::string &detail)
Definition: deprecation.cpp:30
int w() const
Effective map width.
Definition: map.hpp:49
Structure which holds a single route between one location and another.
Definition: pathfind.hpp:131
void merge_array(std::vector< config > children) const
variable_access_create get_variable_access_write(const std::string &varname)
returns a variable_access that can be used to change the game variables
Definition: game_data.hpp:51
bool blank() const
Tests for an attribute that was never set.
game_board * gameboard
Definition: resources.cpp:20
Interface for querying local choices.
iterator begin()
begin iterator
Encapsulates the map of the game.
Definition: map.hpp:170
unit_race::GENDER string_gender(const std::string &str, unit_race::GENDER def)
Definition: race.cpp:148
fake_unit_manager * fake_units
Definition: resources.cpp:30
std::string path
Definition: game_config.cpp:38
config::child_itors append_array(std::vector< config > children) const
Managing the AIs lifecycle - headers TODO: Refactor history handling and internal commands...
Function which only uses terrain, ignoring shroud, enemies, etc.
Definition: pathfind.hpp:240
void read(const std::string &data, const bool allow_invalid=true)
Definition: map.cpp:132
iterator end()
end iterator
void needs_rebuild(bool b)
Sets whether the screen (map visuals) needs to be rebuilt.
int number_of_turns() const
std::string read_map(const std::string &name)
void set_turn_by_wml(const int num, game_data *vars=nullptr, const bool increase_limit_if_needed=true)
Dynamically change the current turn number.
Encapsulates the map of the game.
Definition: location.hpp:37
#define ERR_CF
Definition: action_wml.cpp:82
Various functions related to moving units.
Domain specific events.
Definition: action_wml.cpp:86
Helper class, don&#39;t construct this directly.
static map registry_
Tracks the known action handlers.
Definition: action_wml.hpp:65
std::shared_ptr< wb::manager > whiteboard
Definition: resources.cpp:33
Various functions related to the creation of units (recruits, recalls, and placed units)...
Define conditionals for the game&#39;s events mechanism, a.k.a.
int total_width() const
Real width of the map, including borders.
Definition: map.hpp:58
unit * get()
Get a raw pointer to the underlying unit.
std::size_t i
Definition: function.cpp:940
unit_creator & allow_get_village(bool b)
mock_party p
Define the game&#39;s event mechanism.
config::child_itors replace_array(std::vector< config > children) const
bool on_board(const map_location &loc) const
Tell if a location is on the map.
Definition: map.cpp:384
static lg::log_domain log_display("display")
Declarations for File-IO.
std::size_t index(const std::string &str, const std::size_t index)
Codepoint index corresponding to the nth character in a UTF-8 string.
Definition: unicode.cpp:69
int total_height() const
Real height of the map, including borders.
Definition: map.hpp:61
config & add_child(config_key_type key)
Definition: config.cpp:503
REMOVE_EMPTY: remove empty elements.
iterator erase(iterator it)
Erase an iterator to this object.
void add_unit(const config &cfg, const vconfig *vcfg=nullptr)
adds a unit on map without firing any events (so, usable during team construction in gamestatus) ...
static void on_replay_error(const std::string &message)
Definition: action_wml.cpp:265
void add(const teleport_group &group)
Definition: teleport.cpp:303
bool empty() const
Definition: tstring.hpp:186
Information on a WML variable.
static bool run_in_synced_context_if_not_already(const std::string &commandname, const config &data, bool use_undo=true, bool show=true, synced_command::error_handler_function error_handler=default_error_function)
Checks whether we are currently running in a synced context, and if not we enters it...
void reload_map()
Updates internals that cache map size.
Definition: display.cpp:508
std::vector< std::string > split(const config_attribute_value &val)
A variable-expanding proxy for the config class.
Definition: variable.hpp:42
const config & get_config() const
Definition: variable.hpp:73
Standard logging facilities (interface).
static const map_location & null_location()
Definition: location.hpp:80
static lg::log_domain log_engine("engine")
A RAII object to temporary leave the synced context like in wesnoth.synchronize_choice.
int turn() const
#define e
int side() const
The side this unit belongs to.
Definition: unit.hpp:333
static void clear_global_variable(persist_context &ctx, const vconfig &pcfg)
Definition: persist_var.cpp:92
maybe_const_t< config::child_itors, V > as_array() const
If instantiated with vi_policy_const, the lifetime of the returned const attribute_value reference mi...
place_recruit_result place_recruit(unit_ptr u, const map_location &recruit_location, const map_location &recruited_from, int cost, bool is_recall, map_location::DIRECTION facing, bool show, bool fire_event, bool full_movement, bool wml_triggered)
Place a unit into the game.
Definition: create.cpp:612
std::vector< vconfig > child_list
Definition: variable.hpp:76
static lg::log_domain log_wml("wml")
plain_route a_star_search(const map_location &src, const map_location &dst, double stop_at, const cost_calculator &calc, const std::size_t width, const std::size_t height, const teleport_map *teleports, bool border)
PHASE phase() const
Definition: game_data.hpp:78
A config object defines a single node in a WML file, with access to child nodes.
Definition: config.hpp:59
mock_char c
int h() const
Effective map height.
Definition: map.hpp:52
This module contains various pathfinding functions and utilities.
static std::string write_direction(DIRECTION dir)
Definition: location.cpp:140
pathfind::manager * tunnels
Definition: resources.cpp:31
std::string::const_iterator iterator
Definition: tokenizer.hpp:24
Holds a temporary unit that can be drawn on the map without being placed in the unit_map.
Display units performing various actions: moving, attacking, and dying.
void move_unit(const std::vector< map_location > &path, unit_ptr u, bool animate, map_location::DIRECTION dir, bool force_scroll)
Display a unit moving along a given path.
Definition: udisplay.cpp:509
std::string debug() const
Definition: config.cpp:1326
void verify_and_clear_global_variable(const vconfig &pcfg)
std::stringstream & log_to_chat()
Use this to show WML errors in the ingame chat.
Definition: log.cpp:287
static game_display * get_singleton()
variable_access_const get_variable_access_read(const std::string &varname) const
returns a variable_access that cannot be used to change the game variables
Definition: game_data.hpp:45