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