The Battle for Wesnoth  1.15.11+dev
action_wml.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  * 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  );
341  }
342 }
343 
344 /**
345  * Experimental data persistence
346  * @todo Finish experimenting.
347  */
349 {
351 }
352 
353 WML_HANDLER_FUNCTION(modify_turns,, cfg)
354 {
355  config::attribute_value value = cfg["value"];
356  std::string add = cfg["add"];
357  config::attribute_value current = cfg["current"];
359  if(!add.empty()) {
360  tod_man.modify_turns_by_wml(add);
361  } else if(!value.empty()) {
362  tod_man.set_number_of_turns_by_wml(value.to_int(-1));
363  }
364  // change current turn only after applying mods
365  if(!current.empty()) {
366  const unsigned int current_turn_number = tod_man.turn();
367  int new_turn_number = current.to_int(current_turn_number);
368  const unsigned int new_turn_number_u = static_cast<unsigned int>(new_turn_number);
369  if(new_turn_number_u < 1 || (new_turn_number > tod_man.number_of_turns() && tod_man.number_of_turns() != -1)) {
370  ERR_NG << "attempted to change current turn number to one out of range (" << new_turn_number << ")" << std::endl;
371  } else if(new_turn_number_u != current_turn_number) {
372  tod_man.set_turn_by_wml(new_turn_number_u, resources::gamedata);
374  }
375  }
376 }
377 
378 /**
379  * Moving a 'unit' - i.e. a dummy unit
380  * that is just moving for the visual effect
381  */
382 WML_HANDLER_FUNCTION(move_unit_fake,, cfg)
383 {
385  events::command_disabler command_disabler;
386  fake_unit_ptr dummy_unit(create_fake_unit(cfg));
387  if(!dummy_unit.get())
388  return;
389 
390  const bool force_scroll = cfg["force_scroll"].to_bool(true);
391 
392  const std::string x = cfg["x"];
393  const std::string y = cfg["y"];
394 
395  const std::vector<std::string> xvals = utils::split(x);
396  const std::vector<std::string> yvals = utils::split(y);
397 
398  const std::vector<map_location>& path = fake_unit_path(*dummy_unit, xvals, yvals);
399  if (!path.empty()) {
400  // Always scroll.
401  unit_display::move_unit(path, dummy_unit.get_unit_ptr(), true, map_location::NDIRECTIONS, force_scroll);
402  }
403 }
404 
405 WML_HANDLER_FUNCTION(move_units_fake,, cfg)
406 {
408  events::command_disabler command_disabler;
409  LOG_NG << "Processing [move_units_fake]\n";
410 
411  const bool force_scroll = cfg["force_scroll"].to_bool();
412  const vconfig::child_list unit_cfgs = cfg.get_children("fake_unit");
413  std::size_t num_units = unit_cfgs.size();
414  std::vector<fake_unit_ptr > units;
415  units.reserve(num_units);
416  std::vector<std::vector<map_location>> paths;
417  paths.reserve(num_units);
418 
419  LOG_NG << "Moving " << num_units << " units\n";
420 
421  std::size_t longest_path = 0;
422 
423  for (const vconfig& config : unit_cfgs) {
424  const std::vector<std::string> xvals = utils::split(config["x"]);
425  const std::vector<std::string> yvals = utils::split(config["y"]);
426  int skip_steps = config["skip_steps"];
427  fake_unit_ptr u = create_fake_unit(config);
428  units.push_back(u);
429  paths.push_back(fake_unit_path(*u, xvals, yvals));
430  if(skip_steps > 0)
431  paths.back().insert(paths.back().begin(), skip_steps, paths.back().front());
432  longest_path = std::max(longest_path, paths.back().size());
433  DBG_NG << "Path " << paths.size() - 1 << " has length " << paths.back().size() << '\n';
434 
435  u->set_location(paths.back().front());
436  units.back().place_on_fake_unit_manager(resources::fake_units);
437  }
438 
439  LOG_NG << "Units placed, longest path is " << longest_path << " long\n";
440 
441  std::vector<map_location> path_step(2);
442  path_step.resize(2);
443  for(std::size_t step = 1; step < longest_path; ++step) {
444  DBG_NG << "Doing step " << step << "...\n";
445  for(std::size_t un = 0; un < num_units; ++un) {
446  if(step >= paths[un].size() || paths[un][step - 1] == paths[un][step])
447  continue;
448  DBG_NG << "Moving unit " << un << ", doing step " << step << '\n';
449  path_step[0] = paths[un][step - 1];
450  path_step[1] = paths[un][step];
451  unit_display::move_unit(path_step, units[un].get_unit_ptr(), true, map_location::NDIRECTIONS, force_scroll);
452  units[un]->set_location(path_step[1]);
453  units[un]->anim_comp().set_standing(false);
454  }
455  }
456 
457  LOG_NG << "Units moved\n";
458 }
459 
460 /**
461  * If we should recall units that match a certain description.
462  * If you change attributes specific to [recall] (that is, not a Standard Unit Filter)
463  * be sure to update data/lua/wml_tag, auto_recall feature for [role] to reflect your changes.
464  */
465 WML_HANDLER_FUNCTION(recall,, cfg)
466 {
467  events::command_disabler command_disabler;
468  LOG_NG << "recalling unit...\n";
469  config temp_config(cfg.get_config());
470  // Prevent the recall unit filter from using the location as a criterion
471 
472  /**
473  * FIXME: we should design the WML to avoid these types of
474  * collisions; filters should be named consistently and always have a
475  * distinct scope.
476  */
477  temp_config["x"] = "recall";
478  temp_config["y"] = "recall";
479  temp_config.remove_attribute("location_id");
480  vconfig unit_filter_cfg(temp_config);
481  const vconfig & leader_filter = cfg.child("secondary_unit");
482 
483  for(int index = 0; index < static_cast<int>(resources::gameboard->teams().size()); ++index) {
484  LOG_NG << "for side " << index + 1 << "...\n";
485  const std::string player_id = resources::gameboard->teams()[index].save_id_or_number();
486 
487  if(resources::gameboard->teams()[index].recall_list().size() < 1) {
488  DBG_NG << "recall list is empty when trying to recall!\n"
489  << "player_id: " << player_id << " side: " << index+1 << "\n";
490  continue;
491  }
492 
493  recall_list_manager & avail = resources::gameboard->teams()[index].recall_list();
494  std::vector<unit_map::unit_iterator> leaders = resources::gameboard->units().find_leaders(index + 1);
495 
496  const unit_filter ufilt(unit_filter_cfg);
497  const unit_filter lfilt(leader_filter); // Note that if leader_filter is null, this correctly gives a null filter that matches all units.
498  for(std::vector<unit_ptr>::iterator u = avail.begin(); u != avail.end(); ++u) {
499  DBG_NG << "checking unit against filter...\n";
500  scoped_recall_unit auto_store("this_unit", player_id, std::distance(avail.begin(), u));
501  if (ufilt(*(*u), map_location())) {
502  DBG_NG << (*u)->id() << " matched the filter...\n";
503  const unit_ptr to_recruit = *u;
504  const unit* pass_check = to_recruit.get();
505  if(!cfg["check_passability"].to_bool(true)) pass_check = nullptr;
506  map_location cfg_loc = cfg_to_loc(cfg);
507  if(cfg.has_attribute("location_id")) {
508  const auto& special_locs = resources::gameboard->map().special_locations().left;
509  const auto& iter = special_locs.find(cfg["location_id"]);
510  if(iter != special_locs.end()) {
511  cfg_loc = iter->second;
512  }
513  }
514 
515  for (unit_map::const_unit_iterator leader : leaders) {
516  DBG_NG << "...considering " + leader->id() + " as the recalling leader...\n";
517  map_location loc = cfg_loc;
518  if ( lfilt(*leader) &&
519  unit_filter(vconfig(leader->recall_filter())).matches( *(*u),map_location() ) ) {
520  DBG_NG << "...matched the leader filter and is able to recall the unit.\n";
521  if(!resources::gameboard->map().on_board(loc))
522  loc = leader->get_location();
523  if(pass_check || (resources::gameboard->units().count(loc) > 0))
524  loc = pathfind::find_vacant_tile(loc, pathfind::VACANT_ANY, pass_check);
525  if(resources::gameboard->map().on_board(loc)) {
526  DBG_NG << "...valid location for the recall found. Recalling.\n";
527  avail.erase(u); // Erase before recruiting, since recruiting can fire more events
528  actions::place_recruit(to_recruit, loc, leader->get_location(), 0, true,
529  map_location::parse_direction(cfg["facing"]),
530  cfg["show"].to_bool(true), cfg["fire_event"].to_bool(false),
531  true, true);
532  return;
533  }
534  }
535  }
536  if (resources::gameboard->map().on_board(cfg_loc)) {
537  map_location loc = cfg_loc;
538  if(pass_check || (resources::gameboard->units().count(loc) > 0))
539  loc = pathfind::find_vacant_tile(loc, pathfind::VACANT_ANY, pass_check);
540  // Check if we still have a valid location
541  if (resources::gameboard->map().on_board(loc)) {
542  DBG_NG << "No usable leader found, but found usable location. Recalling.\n";
543  avail.erase(u); // Erase before recruiting, since recruiting can fire more events
544  map_location null_location = map_location::null_location();
545  actions::place_recruit(to_recruit, loc, null_location, 0, true,
546  map_location::parse_direction(cfg["facing"]),
547  cfg["show"].to_bool(true), cfg["fire_event"].to_bool(false),
548  true, true);
549  return;
550  }
551  }
552  }
553  }
554  }
555  LOG_WML << "A [recall] tag with the following content failed:\n" << cfg.get_config().debug();
556 }
557 
558 namespace {
559  struct map_choice : public mp_sync::user_choice
560  {
561  map_choice(const std::string& filename) : filename_(filename) {}
562  std::string filename_;
563  virtual config query_user(int /*side*/) const override
564  {
565  std::string res = filesystem::read_map(filename_);
566  return config {"map_data", res};
567  }
568  virtual config random_choice(int /*side*/) const override
569  {
570  return config();
571  }
572  virtual std::string description() const override
573  {
574  return "Map Data";
575  }
576  virtual bool is_visible() const override
577  {
578  // Allow query_user() to be called during prestart events, as it doesn't show any UI.
579  return false;
580  }
581  };
582 }
583 
584 /**
585  * Experimental map replace
586  * @todo Finish experimenting.
587  */
588 WML_HANDLER_FUNCTION(replace_map,, cfg)
589 {
590  /*
591  * When a hex changes from a village terrain to a non-village terrain, and
592  * a team owned that village it loses that village. When a hex changes from
593  * a non-village terrain to a village terrain and there is a unit on that
594  * hex it does not automatically capture the village. The reason for not
595  * capturing villages it that there are too many choices to make; should a
596  * unit loose its movement points, should capture events be fired. It is
597  * easier to do this as wanted by the author in WML.
598  */
599 
600  const gamemap * game_map = & resources::gameboard->map();
601  gamemap map(*game_map);
602 
603  try {
604  if(!cfg["map_file"].empty()) {
605  config file_cfg = mp_sync::get_user_choice("map_data", map_choice(cfg["map_file"].str()));
606  map.read(file_cfg["map_data"].str(), false);
607  } else if(!cfg["map_data"].empty()) {
608  map.read(cfg["map_data"], false);
609  } else {
610  deprecated_message("[replace_map]map=", DEP_LEVEL::INDEFINITE, "1.16", "Use map_data= instead.");
611  map.read(cfg["map"], false);
612  }
613  } catch(const incorrect_map_format_error&) {
614  const std::string log_map_name = cfg["map"].empty() ? cfg["map_file"] : std::string("from inline data");
615  lg::wml_error() << "replace_map: Unable to load map " << log_map_name << std::endl;
616  return;
617  } catch(const wml_exception& e) {
618  e.show();
619  return;
620  }
621 
622  if (map.total_width() > game_map->total_width()
623  || map.total_height() > game_map->total_height()) {
624  if (!cfg["expand"].to_bool()) {
625  lg::wml_error() << "replace_map: Map dimension(s) increase but expand is not set" << std::endl;
626  return;
627  }
628  }
629 
630  if (map.total_width() < game_map->total_width()
631  || map.total_height() < game_map->total_height()) {
632  if (!cfg["shrink"].to_bool()) {
633  lg::wml_error() << "replace_map: Map dimension(s) decrease but shrink is not set" << std::endl;
634  return;
635  }
636  }
637 
638  std::optional<std::string> errmsg = resources::gameboard->replace_map(map);
639 
640  if (errmsg) {
641  lg::wml_error() << *errmsg << std::endl;
642  }
643 
647 }
648 
649 /**
650  * Experimental data persistence
651  * @todo Finish experimenting.
652  */
654 {
655  if (!resources::controller->is_replay())
657 }
658 
659 WML_HANDLER_FUNCTION(set_variables,, cfg)
660 {
661  const t_string& name = cfg["name"];
663  if(name.empty()) {
664  ERR_NG << "trying to set a variable with an empty name:\n" << cfg.get_config().debug();
665  return;
666  }
667 
668  std::vector<config> data;
669  if(cfg.has_attribute("to_variable"))
670  {
671  try
672  {
674  for (const config& c : tovar.as_array())
675  {
676  data.push_back(c);
677  }
678  }
679  catch(const invalid_variablename_exception&)
680  {
681  ERR_NG << "Cannot do [set_variables] with invalid to_variable variable: " << cfg["to_variable"] << " with " << cfg.get_config().debug() << std::endl;
682  }
683  } else {
684  typedef std::pair<std::string, vconfig> vchild;
685  for (const vchild& p : cfg.all_ordered()) {
686  if(p.first == "value") {
687  data.push_back(p.second.get_parsed_config());
688  } else if(p.first == "literal") {
689  data.push_back(p.second.get_config());
690  } else if(p.first == "split") {
691  const vconfig & split_element = p.second;
692 
693  std::string split_string=split_element["list"];
694  std::string separator_string=split_element["separator"];
695  std::string key_name=split_element["key"];
696  if(key_name.empty())
697  {
698  key_name="value";
699  }
700 
701  bool remove_empty = split_element["remove_empty"].to_bool();
702 
703  char* separator = separator_string.empty() ? nullptr : &separator_string[0];
704  if(separator_string.size() > 1){
705  ERR_NG << "[set_variables] [split] separator only supports 1 character, multiple passed: " << split_element["separator"] << " with " << cfg.get_config().debug() << std::endl;
706  }
707 
708  std::vector<std::string> split_vector;
709 
710  //if no separator is specified, explode the string
711  if(separator == nullptr)
712  {
713  for(std::string::iterator i=split_string.begin(); i!=split_string.end(); ++i)
714  {
715  split_vector.push_back(std::string(1, *i));
716  }
717  }
718  else {
719  split_vector=utils::split(split_string, *separator, remove_empty ? utils::REMOVE_EMPTY | utils::STRIP_SPACES : utils::STRIP_SPACES);
720  }
721 
722  for(std::vector<std::string>::iterator i=split_vector.begin(); i!=split_vector.end(); ++i)
723  {
724  data.emplace_back(key_name, *i);
725  }
726  }
727  }
728  }
729  try
730  {
731  const std::string& mode = cfg["mode"];
732  if(mode == "merge")
733  {
734  if(dest.explicit_index() && data.size() > 1)
735  {
736  //merge children into one
737  config merged_children;
738  for (const config &ch : data) {
739  merged_children.append(ch);
740  }
741  data = {merged_children};
742  }
743  dest.merge_array(data);
744  }
745  else if(mode == "insert")
746  {
747  dest.insert_array(data);
748  }
749  else if(mode == "append")
750  {
751  dest.append_array(data);
752  }
753  else /*default if(mode == "replace")*/
754  {
755  dest.replace_array(data);
756  }
757  }
758  catch(const invalid_variablename_exception&)
759  {
760  ERR_NG << "Cannot do [set_variables] with invalid destination variable: " << name << " with " << cfg.get_config().debug() << std::endl;
761  }
762 }
763 
764 /**
765  * Store the relative direction from one hex to another in a WML variable.
766  * This is mainly useful as a diagnostic tool, but could be useful
767  * for some kind of scenario.
768  */
769 WML_HANDLER_FUNCTION(store_relative_direction,, cfg)
770 {
771  if (!cfg.child("source")) {
772  WRN_NG << "No source in [store_relative_direction]" << std::endl;
773  return;
774  }
775  if (!cfg.child("destination")) {
776  WRN_NG << "No destination in [store_relative_direction]" << std::endl;
777  return;
778  }
779  if (!cfg.has_attribute("variable")) {
780  WRN_NG << "No variable in [store_relative_direction]" << std::endl;
781  return;
782  }
783 
784  const map_location src = cfg_to_loc(cfg.child("source"));
785  const map_location dst = cfg_to_loc(cfg.child("destination"));
786 
787  std::string variable = cfg["variable"];
788  map_location::RELATIVE_DIR_MODE mode = static_cast<map_location::RELATIVE_DIR_MODE> (cfg["mode"].to_int(0));
789  try
790  {
792 
794  }
795  catch(const invalid_variablename_exception&)
796  {
797  ERR_NG << "Cannot do [store_relative_direction] with invalid destination variable: " << variable << " with " << cfg.get_config().debug() << std::endl;
798  }
799 }
800 
801 /**
802  * Store the rotation of one hex around another in a WML variable.
803  * In increments of 60 degrees, clockwise.
804  * This is mainly useful as a diagnostic tool, but could be useful
805  * for some kind of scenario.
806  */
807 WML_HANDLER_FUNCTION(store_rotate_map_location,, cfg)
808 {
809  if (!cfg.child("source")) {
810  WRN_NG << "No source in [store_rotate_map_location]" << std::endl;
811  return;
812  }
813  if (!cfg.child("destination")) {
814  WRN_NG << "No destination in [store_rotate_map_location]" << std::endl;
815  return;
816  }
817  if (!cfg.has_attribute("variable")) {
818  WRN_NG << "No variable in [store_rotate_map_location]" << std::endl;
819  return;
820  }
821 
822  const map_location src = cfg_to_loc(cfg.child("source"));
823  const map_location dst = cfg_to_loc(cfg.child("destination"));
824 
825  std::string variable = cfg["variable"];
826  int angle = cfg["angle"].to_int(1);
827 
828  try
829  {
831 
832  dst.rotate_right_around_center(src,angle).write(store.as_container());
833  }
834  catch(const invalid_variablename_exception&)
835  {
836  ERR_NG << "Cannot do [store_rotate_map_location] with invalid destination variable: " << variable << " with " << cfg.get_config().debug() << std::endl;
837  }
838 }
839 
840 
841 /**
842  * Store time of day config in a WML variable. This is useful for those who
843  * are too lazy to calculate the corresponding time of day for a given turn,
844  * or if the turn / time-of-day sequence mutates in a scenario.
845  */
846 WML_HANDLER_FUNCTION(store_time_of_day,, cfg)
847 {
848  const map_location loc = cfg_to_loc(cfg);
849  int turn = cfg["turn"];
850  // using 0 will use the current turn
851  const time_of_day& tod = resources::tod_manager->get_time_of_day(loc,turn);
852 
853  std::string variable = cfg["variable"];
854  if(variable.empty()) {
855  variable = "time_of_day";
856  }
857  try
858  {
860  tod.write(store.as_container());
861  }
862  catch(const invalid_variablename_exception&)
863  {
864  ERR_NG << "Found invalid variablename " << variable << " in [store_time_of_day] with " << cfg.get_config().debug() << "\n";
865  }
866 }
867 
868 WML_HANDLER_FUNCTION(tunnel,, cfg)
869 {
870  const bool remove = cfg["remove"].to_bool(false);
871  const bool delay = cfg["delayed_variable_substitution"].to_bool(true);
872  if (remove) {
873  const std::vector<std::string> ids = utils::split(cfg["id"]);
874  for (const std::string &id : ids) {
876  }
877  } else if (cfg.get_children("source").empty() ||
878  cfg.get_children("target").empty() ||
879  cfg.get_children("filter").empty()) {
880  ERR_WML << "[tunnel] is missing a mandatory tag:\n"
881  << cfg.get_config().debug();
882  } else {
883  pathfind::teleport_group tunnel(delay ? cfg : vconfig(cfg.get_parsed_config()), false);
884  resources::tunnels->add(tunnel);
885 
886  if(cfg["bidirectional"].to_bool(true)) {
887  tunnel = pathfind::teleport_group(delay ? cfg : vconfig(cfg.get_parsed_config()), true);
888  resources::tunnels->add(tunnel);
889  }
890  }
891 }
892 
893 /** If we should spawn a new unit on the map somewhere */
895 {
896  events::command_disabler command_disabler;
897  config parsed_cfg = cfg.get_parsed_config();
898 
899  config::attribute_value to_variable = cfg["to_variable"];
900  if (!to_variable.blank())
901  {
902  parsed_cfg.remove_attribute("to_variable");
903  unit_ptr new_unit = unit::create(parsed_cfg, true, &cfg);
904  try
905  {
906  config &var = resources::gamedata->get_variable_cfg(to_variable);
907  var.clear();
908  new_unit->write(var);
909  if (const config::attribute_value *v = parsed_cfg.get("x")) var["x"] = *v;
910  if (const config::attribute_value *v = parsed_cfg.get("y")) var["y"] = *v;
911  }
912  catch(const invalid_variablename_exception&)
913  {
914  ERR_NG << "Cannot do [unit] with invalid to_variable: " << to_variable << " with " << cfg.get_config().debug() << std::endl;
915  }
916  return;
917 
918  }
919 
920  int side = parsed_cfg["side"].to_int(1);
921 
922 
923  if ((side<1)||(side > static_cast<int>(resources::gameboard->teams().size()))) {
924  ERR_NG << "wrong side in [unit] tag - no such side: "<<side<<" ( number of teams :"<<resources::gameboard->teams().size()<<")"<<std::endl;
925  DBG_NG << parsed_cfg.debug();
926  return;
927  }
928  team &tm = resources::gameboard->get_team(side);
929 
930  unit_creator uc(tm,resources::gameboard->map().starting_position(side));
931 
932  uc
933  .allow_add_to_recall(true)
934  .allow_discover(true)
935  .allow_get_village(true)
936  .allow_invalidate(true)
937  .allow_rename_side(true)
938  .allow_show(true);
939 
940  uc.add_unit(parsed_cfg, &cfg);
941 
942 }
943 
944 WML_HANDLER_FUNCTION(on_undo, event_info, cfg)
945 {
946  if(cfg["delayed_variable_substitution"].to_bool(false)) {
947  synced_context::add_undo_commands(cfg.get_config(), event_info);
948  } else {
949  synced_context::add_undo_commands(cfg.get_parsed_config(), event_info);
950  }
951 }
952 
953 } // 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:355
static display * get_singleton()
Returns the display object if a display object exists.
Definition: display.hpp:90
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:1228
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:288
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:281
Various functions implementing vision (through fog of war and shroud).
static manager & get_singleton()
Definition: manager.hpp:143
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:302
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:78
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:54
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:766
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:1447
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:895
void write(config &cfg) const
Definition: time_of_day.cpp:54
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:229
bool empty() const
Definition: variable.hpp:100
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:562
#define WRN_NG
Definition: action_wml.cpp:69
Object which defines a time of day with associated bonuses, image, sounds etc.
Definition: time_of_day.hpp:55
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:44
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:86
#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:29
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
const time_of_day & get_time_of_day(int for_turn=0) const
Returns global time of day for the passed turn.
Definition: tod_manager.hpp:54
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:143
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
std::stringstream & wml_error()
Use this logger to send errors due to deprecated WML.
Definition: log.cpp:288
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:380
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:71
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:500
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:298
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:506
std::vector< std::string > split(const config_attribute_value &val)
A variable-expanding proxy for the config class.
Definition: variable.hpp:44
const config & get_config() const
Definition: variable.hpp:75
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:78
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:1322
void verify_and_clear_global_variable(const vconfig &pcfg)
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