The Battle for Wesnoth  1.15.3+dev
game_lua_kernel.cpp
Go to the documentation of this file.
1 /*
2  Copyright (C) 2009 - 2018 by Guillaume Melquiond <guillaume.melquiond@gmail.com>
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  * Provides a Lua interpreter, to be embedded in WML.
18  *
19  * @note Naming conventions:
20  * - intf_ functions are exported in the wesnoth domain,
21  * - impl_ functions are hidden inside metatables,
22  * - cfun_ functions are closures,
23  * - luaW_ functions are helpers in Lua style.
24  */
25 
27 
28 #include "actions/attack.hpp" // for battle_context_unit_stats, etc
29 #include "actions/advancement.hpp" // for advance_unit_at, etc
30 #include "actions/move.hpp" // for clear_shroud
31 #include "actions/vision.hpp" // for clear_shroud
32 #include "ai/composite/ai.hpp" // for ai_composite
33 #include "ai/composite/component.hpp" // for component, etc
34 #include "ai/composite/contexts.hpp" // for ai_context
35 #include "ai/lua/engine_lua.hpp" // for engine_lua
36 #include "ai/composite/rca.hpp" // for candidate_action
37 #include "ai/composite/stage.hpp" // for stage
38 #include "ai/configuration.hpp" // for configuration
39 #include "ai/lua/core.hpp" // for lua_ai_context, etc
40 #include "ai/manager.hpp" // for manager, holder
41 #include "attack_prediction.hpp" // for combatant
42 #include "chat_events.hpp" // for chat_handler, etc
43 #include "config.hpp" // for config, etc
44 #include "display_chat_manager.hpp" // for clear_chat_messages
45 #include "floating_label.hpp"
46 #include "formatter.hpp"
47 #include "game_board.hpp" // for game_board
48 #include "game_classification.hpp" // for game_classification, etc
49 #include "game_config.hpp" // for debug, base_income, etc
50 #include "game_config_manager.hpp" // for game_config_manager
51 #include "game_data.hpp" // for game_data, etc
52 #include "game_display.hpp" // for game_display
53 #include "game_errors.hpp" // for game_error
54 #include "game_events/conditional_wml.hpp" // for conditional_passed
56 #include "game_events/pump.hpp" // for queued_event
57 #include "preferences/game.hpp" // for encountered_units
58 #include "help/help.hpp"
59 #include "log.hpp" // for LOG_STREAM, logger, etc
60 #include "utils/make_enum.hpp" // for operator<<
61 #include "map/map.hpp" // for gamemap
62 #include "map/label.hpp"
63 #include "map/location.hpp" // for map_location
64 #include "mouse_events.hpp" // for mouse_handler
65 #include "mp_game_settings.hpp" // for mp_game_settings
66 #include "pathfind/pathfind.hpp" // for full_cost_map, plain_route, etc
67 #include "pathfind/teleport.hpp" // for get_teleport_locations, etc
68 #include "play_controller.hpp" // for play_controller
69 #include "recall_list_manager.hpp" // for recall_list_manager
70 #include "replay.hpp" // for get_user_choice, etc
71 #include "reports.hpp" // for register_generator, etc
72 #include "resources.hpp" // for whiteboard
73 #include "scripting/lua_audio.hpp"
74 #include "scripting/lua_unit.hpp"
76 #include "scripting/lua_common.hpp"
78 #include "scripting/lua_gui2.hpp" // for show_gamestate_inspector
80 #include "scripting/lua_race.hpp"
81 #include "scripting/lua_team.hpp"
83 #include "scripting/push_check.hpp"
84 #include "synced_commands.hpp"
85 #include "color.hpp" // for surface
86 #include "sdl/surface.hpp" // for surface
87 #include "side_filter.hpp" // for side_filter
88 #include "sound.hpp" // for commit_music_changes, etc
89 #include "soundsource.hpp"
90 #include "synced_context.hpp" // for synced_context, etc
91 #include "synced_user_choice.hpp"
92 #include "team.hpp" // for team, village_owner
93 #include "terrain/terrain.hpp" // for terrain_type
94 #include "terrain/filter.hpp" // for terrain_filter
95 #include "terrain/translation.hpp" // for read_terrain_code, etc
96 #include "terrain/type_data.hpp"
97 #include "time_of_day.hpp" // for time_of_day
98 #include "tod_manager.hpp" // for tod_manager
99 #include "tstring.hpp" // for t_string, operator+
100 #include "units/unit.hpp" // for unit
101 #include "units/animation_component.hpp" // for unit_animation_component
102 #include "units/udisplay.hpp"
103 #include "units/filter.hpp"
104 #include "units/map.hpp" // for unit_map, etc
105 #include "units/ptr.hpp" // for unit_const_ptr, unit_ptr
106 #include "units/types.hpp" // for unit_type_data, unit_types, etc
107 #include "variable.hpp" // for vconfig, etc
108 #include "variable_info.hpp"
109 #include "whiteboard/manager.hpp" // for whiteboard
110 #include "wml_exception.hpp"
111 #include "deprecation.hpp"
112 
113 #include "utils/functional.hpp" // for bind_t, bind
114 #include <boost/range/algorithm/copy.hpp> // boost::copy
115 #include <boost/range/adaptors.hpp> // boost::adaptors::filtered
116 #include <array>
117 #include <cassert> // for assert
118 #include <cstring> // for strcmp
119 #include <iterator> // for distance, advance
120 #include <map> // for map, map<>::value_type, etc
121 #include <new> // for operator new
122 #include <set> // for set
123 #include <sstream> // for operator<<, basic_ostream, etc
124 #include <utility> // for pair
125 #include <algorithm>
126 #include <vector> // for vector, etc
127 #include <SDL2/SDL_timer.h> // for SDL_GetTicks
128 #include "lua/lauxlib.h" // for luaL_checkinteger, etc
129 #include "lua/lua.h" // for lua_setfield, etc
130 
131 class CVideo;
132 
133 #ifdef DEBUG_LUA
134 #include "scripting/debug_lua.hpp"
135 #endif
136 
137 static lg::log_domain log_scripting_lua("scripting/lua");
138 #define LOG_LUA LOG_STREAM(info, log_scripting_lua)
139 #define WRN_LUA LOG_STREAM(warn, log_scripting_lua)
140 #define ERR_LUA LOG_STREAM(err, log_scripting_lua)
141 
142 std::vector<config> game_lua_kernel::preload_scripts;
144 
145 // Template which allows to push member functions to the lua kernel base into lua as C functions, using a shim
147 
148 template <member_callback method>
150  return ((lua_kernel_base::get_lua_kernel<game_lua_kernel>(L)).*method)(L);
151 }
152 
153 // Pass a const bool also...
154 typedef int (game_lua_kernel::*member_callback2)(lua_State *, bool);
155 
156 template <member_callback2 method, bool b>
158  return ((lua_kernel_base::get_lua_kernel<game_lua_kernel>(L)).*method)(L, b);
159 }
160 
162 {
163  map_locker(game_lua_kernel* kernel) : kernel_(kernel)
164  {
165  ++kernel_->map_locked_;
166  }
168  {
169  --kernel_->map_locked_;
170  }
172 };
173 
174 
176 {
177  game_lua_kernel::preload_scripts.clear();
178  for (const config& cfg : game_config.child_range("lua")) {
179  game_lua_kernel::preload_scripts.push_back(cfg);
180  }
181  game_lua_kernel::preload_config = game_config.child("game_config");
182 }
183 
184 void game_lua_kernel::log_error(char const * msg, char const * context)
185 {
186  lua_kernel_base::log_error(msg, context);
187  lua_chat(context, msg);
188 }
189 
190 void game_lua_kernel::lua_chat(const std::string& caption, const std::string& msg)
191 {
192  if (game_display_) {
193  game_display_->get_chat_manager().add_chat_message(std::time(nullptr), caption, 0, msg,
195  }
196 }
197 
198 /**
199  * Gets a vector of sides from side= attribute in a given config node.
200  * Promotes consistent behavior.
201  */
202 std::vector<int> game_lua_kernel::get_sides_vector(const vconfig& cfg)
203 {
204  const config::attribute_value sides = cfg["side"];
205  const vconfig &ssf = cfg.child("filter_side");
206 
207  if (!ssf.null()) {
208  if(!sides.empty()) { WRN_LUA << "ignoring duplicate side filter information (inline side=)" << std::endl; }
209  side_filter filter(ssf, &game_state_);
210  return filter.get_teams();
211  }
212 
213  side_filter filter(sides.str(), &game_state_);
214  return filter.get_teams();
215 }
216 
217 
218 
220 {
221  lua_pushnumber(L, lua_kernel_base::get_lua_kernel<game_lua_kernel>(L).map().special_locations().size());
222  return 1;
223 }
224 
226 {
227  const t_translation::starting_positions::left_map& left = lua_kernel_base::get_lua_kernel<game_lua_kernel>(L).map().special_locations().left;
228 
229  t_translation::starting_positions::left_const_iterator it;
230  if (lua_isnoneornil(L, 2)) {
231  it = left.begin();
232  }
233  else {
234  it = left.find(luaL_checkstring(L, 2));
235  if (it == left.end()) {
236  return 0;
237  }
238  ++it;
239  }
240  if (it == left.end()) {
241  return 0;
242  }
243  lua_pushstring(L, it->first.c_str());
244  luaW_pushlocation(L, it->second);
245  return 2;
246 }
247 
249 {
251  lua_pushvalue(L, -2);
252  lua_pushnil(L);
253  return 3;
254 }
255 
257 {
258  const t_translation::starting_positions::left_map& left = lua_kernel_base::get_lua_kernel<game_lua_kernel>(L).map().special_locations().left;
259  auto it = left.find(luaL_checkstring(L, 2));
260  if (it == left.end()) {
261  return 0;
262  }
263  else {
264  luaW_pushlocation(L, it->second);
265  return 1;
266  }
267 }
268 
270 {
271  lua_pushstring(L, "special locations cannot be modified using wesnoth.special_locations");
272  return lua_error(L);
273 }
274 
276 {
277  lua_newtable(L); // The functor table
278  lua_newtable(L); // The functor metatable
279  lua_pushstring(L, "__len");
281  lua_rawset(L, -3);
282  lua_pushstring(L, "__index");
284  lua_rawset(L, -3);
285  lua_pushstring(L, "__newindex");
287  lua_rawset(L, -3);
288  lua_pushstring(L, "__pairs");
290  lua_rawset(L, -3);
291  lua_setmetatable(L, -2); // Apply the metatable to the functor table
292 }
293 
294 namespace {
295  /**
296  * Temporary entry to a queued_event stack
297  */
298  struct queued_event_context
299  {
300  typedef game_events::queued_event qe;
301  std::stack<qe const *> & stack_;
302 
303  queued_event_context(qe const *new_qe, std::stack<qe const*> & stack)
304  : stack_(stack)
305  {
306  stack_.push(new_qe);
307  }
308 
309  ~queued_event_context()
310  {
311  stack_.pop();
312  }
313  };
314 }//unnamed namespace for queued_event_context
315 
316 /**
317  * Gets currently viewing side.
318  * - Ret 1: integer specifying the currently viewing side
319  * - Ret 2: Bool whether the vision is not limited to that team, this can for example be true during replays.
320  */
322 {
323  if(const display* disp = display::get_singleton()) {
324  lua_pushinteger(L, disp->viewing_side());
325  lua_pushboolean(L, disp->show_everything());
326  return 2;
327  }
328  else {
329  return 0;
330  }
331 }
332 
333 static const char animatorKey[] = "unit animator";
334 
336  unit_animator& anim = *static_cast<unit_animator*>(luaL_checkudata(L, 1, animatorKey));
337  anim.~unit_animator();
338  return 0;
339 }
340 
342 {
343  unit_animator& anim = *static_cast<unit_animator*>(luaL_checkudata(L, 1, animatorKey));
344  unit& u = luaW_checkunit(L, 2);
345  std::string which = luaL_checkstring(L, 3);
346 
347  using hit_type = unit_animation::hit_type;
348  std::string hits_str = luaL_checkstring(L, 4);
349  hit_type hits = hit_type::string_to_enum(hits_str, hit_type::INVALID);
350 
351  map_location dest;
352  int v1 = 0, v2 = 0;
353  bool bars = false;
354  t_string text;
355  color_t color{255, 255, 255};
356  const_attack_ptr primary, secondary;
357 
358  if(lua_istable(L, 5)) {
359  lua_getfield(L, 5, "target");
360  if(luaW_tolocation(L, -1, dest)) {
361  if(dest == u.get_location()) {
362  return luaL_argerror(L, 5, "target location must be different from animated unit's location");
363  } else if(!tiles_adjacent(dest, u.get_location())) {
364  return luaL_argerror(L, 5, "target location must be adjacent to the animated unit");
365  }
366  } else {
367  // luaW_tolocation may set the location to (0,0) if it fails
368  dest = map_location();
369  if(!lua_isnoneornil(L, -1)) {
370  return luaW_type_error(L, 5, "target", "location table");
371  }
372  }
373  lua_pop(L, 1);
374 
375  lua_getfield(L, 5, "value");
376  if(lua_isnumber(L, -1)) {
377  v1 = lua_tonumber(L, -1);
378  } else if(lua_istable(L, -1)) {
379  lua_rawgeti(L, -1, 1);
380  v1 = lua_tonumber(L, -1);
381  lua_pop(L, 1);
382  lua_rawgeti(L, -1, 2);
383  v2 = lua_tonumber(L, -1);
384  lua_pop(L, 1);
385  } else if(!lua_isnoneornil(L, -1)) {
386  return luaW_type_error(L, 5, "value", "number or array of two numbers");
387  }
388  lua_pop(L, 1);
389 
390  lua_getfield(L, 5, "with_bars");
391  if(lua_isboolean(L, -1)) {
392  bars = luaW_toboolean(L, -1);
393  } else if(!lua_isnoneornil(L, -1)) {
394  return luaW_type_error(L, 5, "with_bars", lua_typename(L, LUA_TBOOLEAN));
395  }
396  lua_pop(L, 1);
397 
398  lua_getfield(L, 5, "text");
399  if(lua_isstring(L, -1)) {
400  text = lua_tostring(L, -1);
401  } else if(luaW_totstring(L, -1, text)) {
402  // Do nothing; luaW_totstring already assigned the value
403  } else if(!lua_isnoneornil(L, -1)) {
404  return luaW_type_error(L, 5, "text", lua_typename(L, LUA_TSTRING));
405  }
406  lua_pop(L, 1);
407 
408  lua_getfield(L, 5, "color");
409  if(lua_istable(L, -1) && lua_rawlen(L, -1) == 3) {
410  int idx = lua_absindex(L, -1);
411  lua_rawgeti(L, idx, 1); // red @ -3
412  lua_rawgeti(L, idx, 2); // green @ -2
413  lua_rawgeti(L, idx, 3); // blue @ -1
414  color = color_t(lua_tonumber(L, -3), lua_tonumber(L, -2), lua_tonumber(L, -1));
415  lua_pop(L, 3);
416  } else if(!lua_isnoneornil(L, -1)) {
417  return luaW_type_error(L, 5, "color", "array of three numbers");
418  }
419  lua_pop(L, 1);
420 
421  lua_getfield(L, 5, "primary");
422  primary = luaW_toweapon(L, -1);
423  if(!primary && !lua_isnoneornil(L, -1)) {
424  return luaW_type_error(L, 5, "primary", "weapon");
425  }
426  lua_pop(L, 1);
427 
428  lua_getfield(L, 5, "secondary");
429  secondary = luaW_toweapon(L, -1);
430  if(!secondary && !lua_isnoneornil(L, -1)) {
431  return luaW_type_error(L, 5, "secondary", "weapon");
432  }
433  lua_pop(L, 1);
434  } else if(!lua_isnoneornil(L, 5)) {
435  return luaW_type_error(L, 5, "table of options");
436  }
437 
438  anim.add_animation(&u, which, u.get_location(), dest, v1, bars, text, color, hits, primary, secondary, v2);
439  return 0;
440 }
441 
443 {
445  if(v.update_locked() || v.faked()) {
446  return 0;
447  }
448  events::command_disabler command_disabler;
449  unit_animator& anim = *static_cast<unit_animator*>(luaL_checkudata(L, 1, animatorKey));
450  play_controller_.play_slice(false);
451  anim.start_animations();
452  anim.wait_for_end();
453  anim.set_all_standing();
454  anim.clear();
455  return 0;
456 }
457 
459 {
460  unit_animator& anim = *static_cast<unit_animator*>(luaL_checkudata(L, 1, animatorKey));
461  anim.clear();
462  return 0;
463 }
464 
466 {
467  const char* m = lua_tostring(L, 2);
468  return luaW_getmetafield(L, 1, m);
469 }
470 
472 {
473  new(L) unit_animator;
475  luaL_Reg metafuncs[] {
476  {"__gc", impl_animator_collect},
477  {"__index", impl_animator_get},
478  {"add", impl_add_animation},
479  {"run", &dispatch<&game_lua_kernel::impl_run_animation>},
480  {"clear", impl_clear_animation},
481  {nullptr, nullptr},
482  };
483  luaL_setfuncs(L, metafuncs, 0);
484  lua_pushstring(L, "__metatable");
485  lua_setfield(L, -2, animatorKey);
486  }
487  lua_setmetatable(L, -2);
488  return 1;
489 }
490 
492 {
493  if (game_display_) {
494  return lua_gui2::show_gamestate_inspector(luaW_checkvconfig(L, 1), gamedata(), game_state_);
495  }
496  return 0;
497 }
498 
499 /**
500  * Gets the unit at the given location or with the given id.
501  * - Arg 1: location
502  * OR
503  * - Arg 1: string ID
504  * - Ret 1: full userdata with __index pointing to impl_unit_get and
505  * __newindex pointing to impl_unit_set.
506  */
508 {
509  map_location loc;
510  if(lua_isstring(L, 1) && !lua_isnumber(L, 1)) {
511  std::string id = luaL_checkstring(L, 1);
512  for(const unit& u : units()) {
513  if(u.id() == id) {
514  luaW_pushunit(L, u.underlying_id());
515  return 1;
516  }
517  }
518  return 0;
519  }
520  if(!luaW_tolocation(L, 1, loc)) {
521  return luaL_argerror(L, 1, "expected string or location");
522  }
523  unit_map::const_iterator ui = units().find(loc);
524 
525  if (!ui.valid()) return 0;
526 
527  luaW_pushunit(L, ui->underlying_id());
528  return 1;
529 }
530 
531 /**
532  * Gets the unit displayed in the sidebar.
533  * - Ret 1: full userdata with __index pointing to impl_unit_get and
534  * __newindex pointing to impl_unit_set.
535  */
537 {
538  if (!game_display_) {
539  return 0;
540  }
541 
542  unit_map::const_iterator ui = board().find_visible_unit(
543  game_display_->displayed_unit_hex(),
544  teams()[game_display_->viewing_team()],
545  game_display_->show_everything());
546  if (!ui.valid()) return 0;
547 
548  luaW_pushunit(L, ui->underlying_id());
549  return 1;
550 }
551 
552 /**
553  * Gets all the units matching a given filter.
554  * - Arg 1: optional table containing a filter
555  * - Arg 2: optional location (to find all units that would match on that location)
556  OR unit (to find all units that would match adjacent to that unit)
557  * - Ret 1: table containing full userdata with __index pointing to
558  * impl_unit_get and __newindex pointing to impl_unit_set.
559  */
561 {
562  vconfig filter = luaW_checkvconfig(L, 1, true);
563  unit_filter filt(filter);
564  std::vector<const unit*> units;
565 
566  if(unit* u_adj = luaW_tounit(L, 2)) {
567  if(!u_adj) {
568  return luaL_argerror(L, 2, "unit not found");
569  }
570  units = filt.all_matches_with_unit(*u_adj);
571  } else if(!lua_isnoneornil(L, 2)) {
572  map_location loc;
573  luaW_tolocation(L, 2, loc);
574  if(!loc.valid()) {
575  return luaL_argerror(L, 2, "invalid location");
576  }
577  units = filt.all_matches_at(loc);
578  } else {
579  units = filt.all_matches_on_map();
580  }
581 
582  // Go through all the units while keeping the following stack:
583  // 1: return table, 2: userdata
584  lua_settop(L, 0);
585  lua_newtable(L);
586  int i = 1;
587 
588  for (const unit * ui : units) {
589  luaW_pushunit(L, ui->underlying_id());
590  lua_rawseti(L, 1, i);
591  ++i;
592  }
593  return 1;
594 }
595 
596 /**
597  * Matches a unit against the given filter.
598  * - Arg 1: full userdata.
599  * - Arg 2: table containing a filter
600  * - Arg 3: optional location OR optional "adjacent" unit
601  * - Ret 1: boolean.
602  */
604 {
605  lua_unit& u = *luaW_checkunit_ref(L, 1);
606 
607  vconfig filter = luaW_checkvconfig(L, 2, true);
608 
609  if (filter.null()) {
610  lua_pushboolean(L, true);
611  return 1;
612  }
613 
614  if(unit* u_adj = luaW_tounit(L, 3)) {
615  if(int side = u.on_recall_list()) {
616  WRN_LUA << "wesnoth.units.matches called with a secondary unit (3rd argument), ";
617  WRN_LUA << "but unit to match was on recall list. ";
618  WRN_LUA << "Thus the 3rd argument is ignored.\n";
619  team &t = board().get_team(side);
620  scoped_recall_unit auto_store("this_unit", t.save_id_or_number(), t.recall_list().find_index(u->id()));
621  lua_pushboolean(L, unit_filter(filter).matches(*u, map_location()));
622  return 1;
623  }
624  if (!u_adj) {
625  return luaL_argerror(L, 3, "unit not found");
626  }
627  lua_pushboolean(L, unit_filter(filter).matches(*u, *u_adj));
628  } else if(int side = u.on_recall_list()) {
629  map_location loc;
630  luaW_tolocation(L, 3, loc); // If argument 3 isn't a location, loc is unchanged
631  team &t = board().get_team(side);
632  scoped_recall_unit auto_store("this_unit", t.save_id_or_number(), t.recall_list().find_index(u->id()));
633  lua_pushboolean(L, unit_filter(filter).matches(*u, loc));
634  return 1;
635  } else {
636  map_location loc = u->get_location();
637  luaW_tolocation(L, 3, loc); // If argument 3 isn't a location, loc is unchanged
638  lua_pushboolean(L, unit_filter(filter).matches(*u, loc));
639  }
640  return 1;
641 }
642 
643 /**
644  * Gets the numeric ids of all the units matching a given filter on the recall lists.
645  * - Arg 1: optional table containing a filter
646  * - Ret 1: table containing full userdata with __index pointing to
647  * impl_unit_get and __newindex pointing to impl_unit_set.
648  */
650 {
651  vconfig filter = luaW_checkvconfig(L, 1, true);
652 
653  // Go through all the units while keeping the following stack:
654  // 1: return table, 2: userdata
655  lua_settop(L, 0);
656  lua_newtable(L);
657  int i = 1, s = 1;
658  const unit_filter ufilt(filter);
659  for (team &t : teams())
660  {
661  for (unit_ptr & u : t.recall_list())
662  {
663  if (!filter.null()) {
664  scoped_recall_unit auto_store("this_unit",
665  t.save_id_or_number(), t.recall_list().find_index(u->id()));
666  if (!ufilt( *u, map_location() ))
667  continue;
668  }
669  luaW_pushunit(L, s, u->underlying_id());
670  lua_rawseti(L, 1, i);
671  ++i;
672  }
673  ++s;
674  }
675  return 1;
676 }
677 
678 /**
679  * Fires an event.
680  * - Arg 1: string containing the event name or id.
681  * - Arg 2: optional first location.
682  * - Arg 3: optional second location.
683  * - Arg 4: optional WML table used as the [weapon] tag.
684  * - Arg 5: optional WML table used as the [second_weapon] tag.
685  * - Ret 1: boolean indicating whether the event was processed or not.
686  */
688 {
689  char const *m = luaL_checkstring(L, 1);
690 
691  int pos = 2;
692  map_location l1, l2;
693  config data;
694 
695  if (luaW_tolocation(L, 2, l1)) {
696  if (luaW_tolocation(L, 3, l2)) {
697  pos = 4;
698  } else {
699  pos = 3;
700  }
701  }
702 
703  if (!lua_isnoneornil(L, pos)) {
704  data.add_child("first", luaW_checkconfig(L, pos));
705  }
706  ++pos;
707  if (!lua_isnoneornil(L, pos)) {
708  data.add_child("second", luaW_checkconfig(L, pos));
709  }
710 
711  bool b = false;
712 
713  if (by_id) {
714  b = std::get<0>(play_controller_.pump().fire("", m, l1, l2, data));
715  }
716  else {
717  b = std::get<0>(play_controller_.pump().fire(m, l1, l2, data));
718  }
719  lua_pushboolean(L, b);
720  return 1;
721 }
722 
723 
724 /**
725  * Fires a wml menu item.
726  * - Arg 1: id of the item. it is not possible to fire items that don't have ids with this function.
727  * - Arg 2: optional first location.
728  * - Ret 1: boolean, true indicating that the event was fired successfully
729  *
730  * NOTE: This is not an "official" feature, it may currently cause assertion failures if used with
731  * menu items which have "needs_select". It is not supported right now to use it this way.
732  * The purpose of this function right now is to make it possible to have automated sanity tests for
733  * the wml menu items system.
734  */
736 {
737  char const *m = luaL_checkstring(L, 1);
738 
739  map_location l1 = luaW_checklocation(L, 2);
740 
741  bool b = game_state_.get_wml_menu_items().fire_item(m, l1, gamedata(), game_state_, units());
742  lua_pushboolean(L, b);
743  return 1;
744 }
745 
746 /**
747  * Gets a WML variable.
748  * - Arg 1: string containing the variable name.
749  * - Arg 2: optional bool indicating if tables for containers should be left empty.
750  * - Ret 1: value of the variable, if any.
751  */
753 {
754  char const *m = luaL_checkstring(L, 1);
756  return luaW_pushvariable(L, v) ? 1 : 0;
757 }
758 
759 /**
760  * Sets a WML variable.
761  * - Arg 1: string containing the variable name.
762  * - Arg 2: boolean/integer/string/table containing the value.
763  */
765 {
766  const std::string m = luaL_checkstring(L, 1);
767  if(m.empty()) return luaL_argerror(L, 1, "empty variable name");
768  if (lua_isnoneornil(L, 2)) {
770  return 0;
771  }
773  luaW_checkvariable(L, v, 2);
774  return 0;
775 }
776 
777 
779 {
780  config cfg = luaW_checkconfig(L, 1);
781  game_state_.add_side_wml(cfg);
782 
783  return 0;
784 }
785 
787 {
788  game_state_.get_wml_menu_items().set_item(luaL_checkstring(L, 1), luaW_checkvconfig(L,2));
789  return 0;
790 }
791 
793 {
794  std::string ids(luaL_checkstring(L, 1));
795  for(const std::string& id : utils::split(ids, ',', utils::STRIP_SPACES)) {
796  if(id.empty()) {
797  WRN_LUA << "[clear_menu_item] has been given an empty id=, ignoring" << std::endl;
798  continue;
799  }
800  game_state_.get_wml_menu_items().erase(id);
801  }
802  return 0;
803 }
804 
806 {
807  game_classification &classification = play_controller_.get_classification();
808  classification.end_credits = luaW_toboolean(L, 1);
809  return 0;
810 }
811 
813 {
814  game_classification &classification = play_controller_.get_classification();
815  classification.end_text = luaW_checktstring(L, 1);
816  if (lua_isnumber(L, 2)) {
817  classification.end_text_duration = static_cast<int> (lua_tonumber(L, 2));
818  }
819 
820  return 0;
821 }
822 
824 {
825  deprecated_message("wesnoth.set_next_scenario", DEP_LEVEL::INDEFINITE, "");
827  return 0;
828 }
829 
830 int game_lua_kernel::intf_shroud_op(lua_State *L, bool place_shroud)
831 {
832 
833  int side_num = luaL_checkinteger(L, 1);
834 
835  if(lua_isstring(L, 2)) {
836  std::string data = lua_tostring(L, 2);
837  // Special case - using a shroud_data string, or "all"
838  team& side = board().get_team(side_num);
839  if(place_shroud) {
840  side.reshroud();
841  }
842  if(data != "all") {
843  side.merge_shroud_map_data(data);
844  } else if(!place_shroud) {
845  bool was_shrouded = side.uses_shroud();
846  side.set_shroud(false);
847  actions::clear_shroud(side.side());
848  side.set_shroud(was_shrouded);
849  }
850  return 0;
851  } else if(lua_istable(L, 2)) {
852  std::vector<map_location> locs_v = lua_check<std::vector<map_location>>(L, 2);
853  std::set<map_location> locs(locs_v.begin(), locs_v.end());
854  team &t = board().get_team(side_num);
855 
856  for (const map_location& loc : locs)
857  {
858  if (place_shroud) {
859  t.place_shroud(loc);
860  } else {
861  t.clear_shroud(loc);
862  }
863  }
864  } else {
865  return luaL_argerror(L, 2, "expected list of locations or shroud data string");
866  }
867 
868  game_display_->labels().recalculate_shroud();
869  game_display_->recalculate_minimap();
870  game_display_->invalidate_all();
871 
872  return 0;
873 }
874 
875 
876 /**
877  * Highlights the given location on the map.
878  * - Arg 1: location.
879  */
881 {
882  if (!game_display_) {
883  return 0;
884  }
885 
886  const map_location loc = luaW_checklocation(L, 1);
887  if(!map().on_board(loc)) return luaL_argerror(L, 1, "not on board");
888  game_display_->highlight_hex(loc);
889  game_display_->display_unit_hex(loc);
890 
891  return 0;
892 }
893 
894 /**
895  * Returns whether the first side is an enemy of the second one.
896  * - Args 1,2: side numbers.
897  * - Ret 1: boolean.
898  */
900 {
901  unsigned side_1, side_2;
902  if(team* t = luaW_toteam(L, 1)) {
903  side_1 = t->side();
904  } else {
905  side_1 = luaL_checkinteger(L, 1);
906  }
907  if(team* t = luaW_toteam(L, 2)) {
908  side_2 = t->side();
909  } else {
910  side_2 = luaL_checkinteger(L, 2);
911  }
912  if (side_1 > teams().size() || side_2 > teams().size()) return 0;
913  lua_pushboolean(L, board().get_team(side_1).is_enemy(side_2));
914  return 1;
915 }
916 
917 /**
918  * Gets whether gamemap scrolling is disabled for the user.
919  * - Ret 1: boolean.
920  */
922 {
923  if (!game_display_) {
924  return 0;
925  }
926 
927  lua_pushboolean(L, game_display_->view_locked());
928  return 1;
929 }
930 
931 /**
932  * Sets whether gamemap scrolling is disabled for the user.
933  * - Arg 1: boolean, specifying the new locked/unlocked status.
934  */
936 {
937  bool lock = luaW_toboolean(L, 1);
938  if (game_display_) {
939  game_display_->set_view_locked(lock);
940  }
941  return 0;
942 }
943 
944 /**
945  * Gets a terrain code.
946  * - Arg 1: map location.
947  * - Ret 1: string.
948  */
950 {
951  map_location loc = luaW_checklocation(L, 1);
952 
953  const t_translation::terrain_code& t = board().map().
954  get_terrain(loc);
956  return 1;
957 }
958 
959 /**
960  * Sets a terrain code.
961  * - Arg 1: map location.
962  * - Arg 2: terrain code string.
963  * - Arg 3: layer: (overlay|base|both, default=both)
964  * - Arg 4: replace_if_failed, default = no
965  */
967 {
968  map_location loc = luaW_checklocation(L, 1);
969  std::string t_str(luaL_checkstring(L, 2));
970 
971  std::string mode_str = "both";
972  bool replace_if_failed = false;
973  if (!lua_isnone(L, 3)) {
974  if (!lua_isnil(L, 3)) {
975  mode_str = luaL_checkstring(L, 3);
976  }
977 
978  if(!lua_isnoneornil(L, 4)) {
979  replace_if_failed = luaW_toboolean(L, 4);
980  }
981  }
982 
983  bool result = board().change_terrain(loc, t_str, mode_str, replace_if_failed);
984 
985  if (game_display_) {
986  game_display_->needs_rebuild(result);
987  }
988 
989  return 0;
990 }
991 
992 /**
993  * Reaplces part of the map.
994  * - Arg 1: map location.
995  * - Arg 2: map data string.
996  * - Arg 3: table for optional named arguments
997  * - is_odd: boolen, if Arg2 has the odd mapo format (as if it was cut from a odd map location)
998  * - ignore_special_locations: boolean
999  * - rules: table of tables
1000 */
1002 {
1003  map_location loc = luaW_checklocation(L, 1);
1004  std::string t_str(luaL_checkstring(L, 2));
1005  bool is_odd = false;
1006  bool ignore_special_locations = false;
1007  std::vector<gamemap::overlay_rule> rules;
1008 
1009  if(lua_istable(L, 3)) {
1010  if(luaW_tableget(L, 3, "is_odd")) {
1011  is_odd = luaW_toboolean(L, -1);
1012  lua_pop(L, 1);
1013  }
1014  if(luaW_tableget(L, 3, "ignore_special_locations")) {
1015  ignore_special_locations = luaW_toboolean(L, -1);
1016  lua_pop(L, 1);
1017  }
1018  if(luaW_tableget(L, 3, "rules")) {
1019  //todo: reduce code dublication by using read_rules_vector.
1020  if(!lua_istable(L, -1)) {
1021  return luaL_argerror(L, 3, "rules must be a table");
1022  }
1023 
1024  for (int i = 1, i_end = lua_rawlen(L, -1); i <= i_end; ++i)
1025  {
1026  lua_rawgeti(L, -1, i);
1027  if(!lua_istable(L, -1)) {
1028  return luaL_argerror(L, 3, "rules must be a table of tables");
1029  }
1030  rules.push_back(gamemap::overlay_rule());
1031  auto& rule = rules.back();
1032  if(luaW_tableget(L, -1, "old")) {
1033  rule.old_ = t_translation::read_list(luaW_tostring(L, -1));
1034  lua_pop(L, 1);
1035  }
1036 
1037  if(luaW_tableget(L, -1, "new")) {
1038  rule.new_ = t_translation::read_list(luaW_tostring(L, -1));
1039  lua_pop(L, 1);
1040  }
1041 
1042  if(luaW_tableget(L, -1, "mode")) {
1043  auto str = luaW_tostring(L, -1);
1044  rule.mode_ = str == "base" ? terrain_type_data::BASE : (str == "overlay" ? terrain_type_data::OVERLAY : terrain_type_data::BOTH);
1045  lua_pop(L, 1);
1046  }
1047 
1048  if(luaW_tableget(L, -1, "terrain")) {
1050  if(!terrain.empty()) {
1051  rule.terrain_ = terrain[0];
1052  }
1053  lua_pop(L, 1);
1054  }
1055 
1056  if(luaW_tableget(L, -1, "use_old")) {
1057  rule.use_old_ = luaW_toboolean(L, -1);
1058  lua_pop(L, 1);
1059  }
1060 
1061  if(luaW_tableget(L, -1, "replace_if_failed")) {
1062  rule.replace_if_failed_ = luaW_toboolean(L, -1);
1063  lua_pop(L, 1);
1064  }
1065 
1066  lua_pop(L, 1);
1067  }
1068  lua_pop(L, 1);
1069  }
1070  }
1071 
1072 
1073  gamemap mask_map(board().map().tdata(), "");
1074  mask_map.read(t_str, false);
1075  board().map_->overlay(mask_map, loc, rules, is_odd, ignore_special_locations);
1076 
1077  for(team& t : board().teams()) {
1078  t.fix_villages(board().map());
1079  }
1080 
1081  if (game_display_) {
1082  game_display_->needs_rebuild(true);
1083  }
1084 
1085  return 0;
1086 }
1087 
1088 /**
1089  * Gets details about a terrain.
1090  * - Arg 1: terrain code string.
1091  * - Ret 1: table.
1092  */
1094 {
1095  char const *m = luaL_checkstring(L, 1);
1097  if (t == t_translation::NONE_TERRAIN) return 0;
1098  const terrain_type& info = board().map().tdata()->get_terrain_info(t);
1099 
1100  lua_newtable(L);
1101  lua_pushstring(L, info.id().c_str());
1102  lua_setfield(L, -2, "id");
1103  luaW_pushtstring(L, info.name());
1104  lua_setfield(L, -2, "name");
1105  luaW_pushtstring(L, info.editor_name());
1106  lua_setfield(L, -2, "editor_name");
1107  luaW_pushtstring(L, info.description());
1108  lua_setfield(L, -2, "description");
1109  lua_push(L, info.icon_image());
1110  lua_setfield(L, -2, "icon");
1111  lua_push(L, info.editor_image());
1112  lua_setfield(L, -2, "editor_image");
1113  lua_pushinteger(L, info.light_bonus(0));
1114  lua_setfield(L, -2, "light");
1115  lua_pushboolean(L, info.is_village());
1116  lua_setfield(L, -2, "village");
1117  lua_pushboolean(L, info.is_castle());
1118  lua_setfield(L, -2, "castle");
1119  lua_pushboolean(L, info.is_keep());
1120  lua_setfield(L, -2, "keep");
1121  lua_pushinteger(L, info.gives_healing());
1122  lua_setfield(L, -2, "healing");
1123 
1124  return 1;
1125 }
1126 
1127 /**
1128  * Gets time of day information.
1129  * - Arg 1: optional turn number
1130  * - Arg 2: optional location
1131  * - Arg 3: optional boolean (consider_illuminates)
1132  * - Ret 1: table.
1133  */
1135 {
1136  unsigned arg = 1;
1137 
1138  int for_turn = tod_man().turn();
1139  map_location loc = map_location();
1140  bool consider_illuminates = false;
1141 
1142  if(lua_isnumber(L, arg)) {
1143  ++arg;
1144  for_turn = luaL_checkinteger(L, 1);
1145  int number_of_turns = tod_man().number_of_turns();
1146  if(for_turn < 1 || (number_of_turns != -1 && for_turn > number_of_turns)) {
1147  return luaL_argerror(L, 1, "turn number out of range");
1148  }
1149  }
1150  else if(lua_isnil(L, arg)) ++arg;
1151 
1152  if(luaW_tolocation(L, arg, loc)) {
1153  if(!board().map().on_board(loc)) return luaL_argerror(L, arg, "coordinates are not on board");
1154 
1155  if(lua_istable(L, arg)) {
1156  lua_rawgeti(L, arg, 3);
1157  consider_illuminates = luaW_toboolean(L, -1);
1158  lua_pop(L, 1);
1159  } else if(lua_isboolean(L, arg + 1)) {
1160  consider_illuminates = luaW_toboolean(L, arg + 1);
1161  }
1162  }
1163 
1164  const time_of_day& tod = consider_illuminates ?
1165  tod_man().get_illuminated_time_of_day(board().units(), board().map(), loc, for_turn) :
1166  tod_man().get_time_of_day(loc, for_turn);
1167 
1168  lua_newtable(L);
1169  lua_pushstring(L, tod.id.c_str());
1170  lua_setfield(L, -2, "id");
1171  lua_pushinteger(L, tod.lawful_bonus);
1172  lua_setfield(L, -2, "lawful_bonus");
1174  lua_setfield(L, -2, "bonus_modified");
1175  lua_pushstring(L, tod.image.c_str());
1176  lua_setfield(L, -2, "image");
1177  luaW_pushtstring(L, tod.name);
1178  lua_setfield(L, -2, "name");
1179 
1180  lua_pushinteger(L, tod.color.r);
1181  lua_setfield(L, -2, "red");
1182  lua_pushinteger(L, tod.color.g);
1183  lua_setfield(L, -2, "green");
1184  lua_pushinteger(L, tod.color.b);
1185  lua_setfield(L, -2, "blue");
1186 
1187  return 1;
1188 }
1189 
1190 /**
1191  * Gets the max liminal bonus
1192  * - Ret 1: integer.
1193  */
1195 {
1196  int bonus = tod_man().get_max_liminal_bonus();
1197  lua_pushinteger(L, bonus);
1198 
1199  return 1;
1200 }
1201 
1202 /**
1203  * Gets the side of a village owner.
1204  * - Arg 1: map location.
1205  * - Ret 1: integer.
1206  */
1208 {
1209  map_location loc = luaW_checklocation(L, 1);
1210  if (!board().map().is_village(loc))
1211  return 0;
1212 
1213  int side = board().village_owner(loc) + 1;
1214  if (!side) return 0;
1215  lua_pushinteger(L, side);
1216  return 1;
1217 }
1218 
1219 /**
1220  * Sets the owner of a village.
1221  * - Arg 1: map location.
1222  * - Arg 2: integer for the side or empty to remove ownership.
1223  */
1225 {
1226  map_location loc = luaW_checklocation(L, 1);
1227  if(!board().map().is_village(loc)) {
1228  return 0;
1229  }
1230 
1231  const int old_side_num = board().village_owner(loc) + 1;
1232  const int new_side_num = lua_isnoneornil(L, 2) ? 0 : luaL_checkinteger(L, 2);
1233 
1234  team* old_side = nullptr;
1235  team* new_side = nullptr;
1236 
1237  if(old_side_num == new_side_num) {
1238  return 0;
1239  }
1240 
1241  try {
1242  old_side = &board().get_team(old_side_num);
1243  } catch(const std::out_of_range&) {
1244  // old_side_num is invalid, most likely because the village wasn't captured.
1245  old_side = nullptr;
1246  }
1247 
1248  try {
1249  new_side = &board().get_team(new_side_num);
1250  } catch(const std::out_of_range&) {
1251  // new_side_num is invalid.
1252  new_side = nullptr;
1253  }
1254 
1255  // The new side was valid, but already defeated. Do nothing.
1256  if(new_side && board().team_is_defeated(*new_side)) {
1257  return 0;
1258  }
1259 
1260  // Even if the new side is not valid, we still want to remove the village from the old side.
1261  // This covers the case where new_side_num equals 0. The behavior in that case is to simply
1262  // un-assign the village from the old side, which of course we also want to happen if the new
1263  // side IS valid. If the village in question hadn't been captured, this won't fire (old_side
1264  // will be a nullptr).
1265  if(old_side) {
1266  old_side->lose_village(loc);
1267  }
1268 
1269  // If the new side was valid, re-assign the village.
1270  if(new_side) {
1271  new_side->get_village(loc, old_side_num, (luaW_toboolean(L, 3) ? &gamedata() : nullptr));
1272  }
1273 
1274  return 0;
1275 }
1276 
1277 
1278 /**
1279  * Returns the map size.
1280  * - Ret 1: width.
1281  * - Ret 2: height.
1282  * - Ret 3: border size.
1283  */
1285 {
1286  const gamemap &map = board().map();
1287  lua_pushinteger(L, map.w());
1288  lua_pushinteger(L, map.h());
1289  lua_pushinteger(L, map.border_size());
1290  return 3;
1291 }
1292 
1293 /**
1294  * Returns the currently overed tile.
1295  * - Ret 1: x.
1296  * - Ret 2: y.
1297  */
1299 {
1300  if (!game_display_) {
1301  return 0;
1302  }
1303 
1304  const map_location &loc = game_display_->mouseover_hex();
1305  if (!board().map().on_board(loc)) return 0;
1306  lua_pushinteger(L, loc.wml_x());
1307  lua_pushinteger(L, loc.wml_y());
1308  return 2;
1309 }
1310 
1311 /**
1312  * Returns the currently selected tile.
1313  * - Ret 1: x.
1314  * - Ret 2: y.
1315  */
1317 {
1318  if (!game_display_) {
1319  return 0;
1320  }
1321 
1322  const map_location &loc = game_display_->selected_hex();
1323  if (!board().map().on_board(loc)) return 0;
1324  lua_pushinteger(L, loc.wml_x());
1325  lua_pushinteger(L, loc.wml_y());
1326  return 2;
1327 }
1328 
1329 
1330 /**
1331  * Gets a table for an resource tag.
1332  * - Arg 1: userdata (ignored).
1333  * - Arg 2: string containing id of the desired resource
1334  * - Ret 1: config for the era
1335  */
1337 {
1338  std::string m = luaL_checkstring(L, 1);
1339  if(const config& res = game_config_manager::get()->game_config().find_child("resource","id",m)) {
1340  luaW_pushconfig(L, res);
1341  return 1;
1342  }
1343  else {
1344  return luaL_argerror(L, 1, ("Cannot find ressource with id '" + m + "'").c_str());
1345  }
1346 }
1347 
1348 /**
1349  * Gets a table for an era tag.
1350  * - Arg 1: userdata (ignored).
1351  * - Arg 2: string containing id of the desired era
1352  * - Ret 1: config for the era
1353  */
1354 static int intf_get_era(lua_State *L)
1355 {
1356  char const *m = luaL_checkstring(L, 1);
1357  luaW_pushconfig(L, game_config_manager::get()->game_config().find_child("era","id",m));
1358  return 1;
1359 }
1360 
1361 /**
1362  * Gets some game_config data (__index metamethod).
1363  * - Arg 1: userdata (ignored).
1364  * - Arg 2: string containing the name of the property.
1365  * - Ret 1: something containing the attribute.
1366  */
1368 {
1369  LOG_LUA << "impl_game_config_get\n";
1370  char const *m = luaL_checkstring(L, 2);
1371 
1372  // Find the corresponding attribute.
1373  return_int_attrib("last_turn", tod_man().number_of_turns());
1374  return_bool_attrib("do_healing", play_controller_.gamestate().do_healing_);
1375  return_string_attrib("next_scenario", gamedata().next_scenario());
1376  return_string_attrib("theme", gamedata().get_theme());
1377  return_string_attrib("scenario_id", gamedata().get_id());
1378  return_vector_string_attrib("defeat_music", gamedata().get_defeat_music());
1379  return_vector_string_attrib("victory_music", gamedata().get_victory_music());
1380  return_vector_string_attrib("active_resources", utils::split(play_controller_.get_loaded_resources()) );
1381 
1382  const mp_game_settings& mp_settings = play_controller_.get_mp_settings();
1383  const game_classification & classification = play_controller_.get_classification();
1384 
1385  return_string_attrib("campaign_type", classification.campaign_type.to_string());
1386  if(classification.campaign_type==game_classification::CAMPAIGN_TYPE::MULTIPLAYER) {
1387  return_cfgref_attrib("mp_settings", mp_settings.to_config());
1388  return_cfgref_attrib("era", game_config_manager::get()->game_config().find_child("era","id",classification.era_id));
1389  //^ finds the era with name matching mp_era, and creates a lua reference from the config of that era.
1390 
1391  //This code for SigurdFD, not the cleanest implementation but seems to work just fine.
1392  std::vector<std::string> eras_list;
1393  for (const config& era : game_config_manager::get()->game_config().child_range("era") ) {
1394  eras_list.push_back(era["id"].str());
1395  }
1396  return_string_attrib("eras", utils::join(eras_list));
1397  }
1399 }
1400 
1401 /**
1402  * Sets some game_config data (__newindex metamethod).
1403  * - Arg 1: userdata (ignored).
1404  * - Arg 2: string containing the name of the property.
1405  * - Arg 3: something containing the attribute.
1406  */
1408 {
1409  LOG_LUA << "impl_game_config_set\n";
1410  char const *m = luaL_checkstring(L, 2);
1411 
1412  // Find the corresponding attribute.
1413  modify_int_attrib("base_income", game_config::base_income = value);
1414  modify_int_attrib("village_income", game_config::village_income = value);
1415  modify_int_attrib("village_support", game_config::village_support = value);
1416  modify_int_attrib("poison_amount", game_config::poison_amount = value);
1417  modify_int_attrib("rest_heal_amount", game_config::rest_heal_amount = value);
1418  modify_int_attrib("recall_cost", game_config::recall_cost = value);
1419  modify_int_attrib("kill_experience", game_config::kill_experience = value);
1420  modify_int_attrib("combat_experience", game_config::combat_experience = value);
1421  modify_int_attrib("last_turn", tod_man().set_number_of_turns_by_wml(value));
1422  modify_bool_attrib("do_healing", play_controller_.gamestate().do_healing_ = value);
1423  modify_string_attrib("next_scenario", gamedata().set_next_scenario(value));
1424  modify_string_attrib("theme",
1425  gamedata().set_theme(value);
1427  game_display_->set_theme(play_controller_.get_theme(game_config, value));
1428  );
1429  modify_vector_string_attrib("defeat_music", gamedata().set_defeat_music(std::move(value)));
1430  modify_vector_string_attrib("victory_music", gamedata().set_victory_music(std::move(value)));
1432 }
1433 
1434 /**
1435  converts synced_context::get_synced_state() to a string.
1436 */
1438 {
1439  //maybe return "initial" for game_data::INITIAL?
1440  if(gamedata().phase() == game_data::PRELOAD || gamedata().phase() == game_data::INITIAL)
1441  {
1442  return "preload";
1443  }
1445  {
1447  return "local_choice";
1449  return "synced";
1451  return "unsynced";
1452  default:
1453  throw game::game_error("Found corrupt synced_context::synced_state");
1454  }
1455 }
1456 
1457 
1458 /**
1459  * Gets some data about current point of game (__index metamethod).
1460  * - Arg 1: userdata (ignored).
1461  * - Arg 2: string containing the name of the property.
1462  * - Ret 1: something containing the attribute.
1463  */
1465 {
1466  char const *m = luaL_checkstring(L, 2);
1467 
1468  // Find the corresponding attribute.
1469  return_int_attrib("side", play_controller_.current_side());
1470  return_int_attrib("turn", play_controller_.turn());
1471  return_string_attrib("synced_state", synced_state());
1472  return_bool_attrib("user_can_invoke_commands", !play_controller_.is_lingering() && play_controller_.gamestate().init_side_done() && !events::commands_disabled && gamedata().phase() == game_data::PLAY);
1473 
1474  if (strcmp(m, "event_context") == 0)
1475  {
1476  const game_events::queued_event &ev = get_event_info();
1477  config cfg;
1478  cfg["name"] = ev.name;
1479  cfg["id"] = ev.id;
1480  if (const config &weapon = ev.data.child("first")) {
1481  cfg.add_child("weapon", weapon);
1482  }
1483  if (const config &weapon = ev.data.child("second")) {
1484  cfg.add_child("second_weapon", weapon);
1485  }
1486 
1487  const config::attribute_value di = ev.data["damage_inflicted"];
1488  if(!di.empty()) {
1489  cfg["damage_inflicted"] = di;
1490  }
1491 
1492  if (ev.loc1.valid()) {
1493  cfg["x1"] = ev.loc1.filter_loc().wml_x();
1494  cfg["y1"] = ev.loc1.filter_loc().wml_y();
1495  // The position of the unit involved in this event, currently the only case where this is different from x1/y1 are enter/exit_hex events
1496  cfg["unit_x"] = ev.loc1.wml_x();
1497  cfg["unit_y"] = ev.loc1.wml_y();
1498  }
1499  if (ev.loc2.valid()) {
1500  cfg["x2"] = ev.loc2.filter_loc().wml_x();
1501  cfg["y2"] = ev.loc2.filter_loc().wml_y();
1502  }
1503  luaW_pushconfig(L, cfg);
1504  return 1;
1505  }
1506 
1507  return 0;
1508 }
1509 
1510 /**
1511  * Displays a message in the chat window and in the logs.
1512  * - Arg 1: optional message header.
1513  * - Arg 2 (or 1): message.
1514  */
1516 {
1517  t_string m = luaW_checktstring(L, 1);
1518  t_string h = m;
1519  if (lua_isnone(L, 2)) {
1520  h = "Lua";
1521  } else {
1522  m = luaW_checktstring(L, 2);
1523  }
1524  lua_chat(h, m);
1525  LOG_LUA << "Script says: \"" << m << "\"\n";
1526  return 0;
1527 }
1528 
1530 {
1531  if (game_display_) {
1533  }
1534  return 0;
1535 }
1536 
1538 {
1539  if(!game_display_) {
1540  return 0;
1541  }
1542  double factor = luaL_checknumber(L, 1);
1543  bool relative = luaW_toboolean(L, 2);
1544  if(relative) {
1545  factor *= game_display_->get_zoom_factor();
1546  }
1547  // Passing true explicitly to avoid casting to int.
1548  // Without doing one of the two, the call is ambiguous.
1549  game_display_->set_zoom(factor * game_config::tile_size, true);
1550  lua_pushnumber(L, game_display_->get_zoom_factor());
1551  return 1;
1552 }
1553 
1554 /**
1555  * Removes all messages from the chat window.
1556  */
1558 {
1559  if (game_display_) {
1560  game_display_->get_chat_manager().clear_chat_messages();
1561  }
1562  return 0;
1563 }
1564 
1566 {
1567  const end_level_data& data = *static_cast<end_level_data*>(lua_touserdata(L, 1));
1568  const char* m = luaL_checkstring(L, 2);
1569 
1570  return_bool_attrib("linger_mode", data.transient.linger_mode);
1571  return_bool_attrib("reveal_map", data.transient.reveal_map);
1572  return_bool_attrib("carryover_report", data.transient.carryover_report);
1573  return_bool_attrib("prescenario_save", data.prescenario_save);
1574  return_bool_attrib("replay_save", data.replay_save);
1575  return_bool_attrib("proceed_to_next_level", data.proceed_to_next_level);
1576  return_bool_attrib("is_victory", data.is_victory);
1577  return_bool_attrib("is_loss", !data.is_victory);
1578  return_cstring_attrib("result", data.is_victory ? "victory" : "loss"); // to match wesnoth.end_level()
1579  return_string_attrib("test_result", data.test_result);
1580  return_cfg_attrib("__cfg", data.to_config_full());
1581 
1582  return 0;
1583 }
1584 
1585 namespace {
1586  struct end_level_committer {
1587  end_level_committer(end_level_data& data, play_controller& pc) : data_(data), pc_(pc) {}
1588  ~end_level_committer() {
1589  pc_.set_end_level_data(data_);
1590  }
1591  private:
1592  end_level_data& data_;
1593  play_controller& pc_;
1594  };
1595 }
1596 
1598 {
1599  end_level_data& data = *static_cast<end_level_data*>(lua_touserdata(L, 1));
1600  const char* m = luaL_checkstring(L, 2);
1601  end_level_committer commit(data, play_controller_);
1602 
1603  modify_bool_attrib("linger_mode", data.transient.linger_mode = value);
1604  modify_bool_attrib("reveal_map", data.transient.reveal_map = value);
1605  modify_bool_attrib("carryover_report", data.transient.carryover_report = value);
1606  modify_bool_attrib("prescenario_save", data.prescenario_save = value);
1607  modify_bool_attrib("replay_save", data.replay_save = value);
1608  modify_string_attrib("test_result", data.test_result = value);
1609 
1610  return 0;
1611 }
1612 
1614 {
1615  end_level_data* data = static_cast<end_level_data*>(lua_touserdata(L, 1));
1616  UNUSED(data); // Suppress an erroneous MSVC warning (a destructor call doesn't count as a reference)
1617  data->~end_level_data();
1618  return 0;
1619 }
1620 
1622 {
1623  if (!play_controller_.is_regular_game_end()) {
1624  return 0;
1625  }
1626  auto data = play_controller_.get_end_level_data_const();
1627  new(L) end_level_data(data);
1628  if(luaL_newmetatable(L, "end level data")) {
1629  static luaL_Reg const callbacks[] {
1630  { "__index", &impl_end_level_data_get},
1631  { "__newindex", &dispatch<&game_lua_kernel::impl_end_level_data_set>},
1632  { "__gc", &impl_end_level_data_collect},
1633  { nullptr, nullptr }
1634  };
1635  luaL_setfuncs(L, callbacks, 0);
1636  }
1637  lua_setmetatable(L, -2);
1638  return 1;
1639 }
1640 
1642 {
1643  vconfig cfg(luaW_checkvconfig(L, 1));
1644  end_level_data data;
1645 
1646  data.proceed_to_next_level = cfg["proceed_to_next_level"].to_bool(true);
1647  data.transient.carryover_report = cfg["carryover_report"].to_bool(true);
1648  data.prescenario_save = cfg["save"].to_bool(true);
1649  data.replay_save = cfg["replay_save"].to_bool(true);
1650  data.transient.linger_mode = cfg["linger_mode"].to_bool(true) && !teams().empty();
1651  data.transient.reveal_map = cfg["reveal_map"].to_bool(true);
1652  data.is_victory = cfg["result"] == "victory";
1653  data.test_result = cfg["test_result"].str(LEVEL_RESULT::enum_to_string(LEVEL_RESULT::TEST_NOT_SET));
1654  play_controller_.set_end_level_data(data);
1655  return 0;
1656 }
1657 
1659 {
1660  //note that next_player_number = 1, next_player_number = nteams+1 both set the next team to be the first team
1661  //but the later will make the turn counter change aswell fire turn end events accoringly etc.
1662  if (!lua_isnoneornil(L, 1)) {
1663  int npn = luaL_checknumber(L, 1);
1664  if (npn <= 0 /*TODO: || npn > 2*nteams*/) {
1665  return luaL_argerror(L, 1, "side number out of range");
1666  }
1668  }
1669  play_controller_.force_end_turn();
1670  return 0;
1671 }
1672 
1673 /**
1674  * Evaluates a boolean WML conditional.
1675  * - Arg 1: WML table.
1676  * - Ret 1: boolean.
1677  */
1679 {
1680  vconfig cond = luaW_checkvconfig(L, 1);
1681  bool b = game_events::conditional_passed(cond);
1682  lua_pushboolean(L, b);
1683  return 1;
1684 }
1685 
1686 
1687 /**
1688  * Finds a path between two locations.
1689  * - Arg 1: source location. (Or Arg 1: unit.)
1690  * - Arg 2: destination.
1691  * - Arg 3: optional cost function or
1692  * table (optional fields: ignore_units, ignore_teleport, max_cost, viewing_side).
1693  * - Ret 1: array of pairs containing path steps.
1694  * - Ret 2: path cost.
1695  */
1697 {
1698  int arg = 1;
1699  map_location src, dst;
1700  const unit* u = nullptr;
1701 
1702  if (lua_isuserdata(L, arg))
1703  {
1704  u = &luaW_checkunit(L, arg);
1705  src = u->get_location();
1706  ++arg;
1707  }
1708  else
1709  {
1710  src = luaW_checklocation(L, arg);
1711  unit_map::const_unit_iterator ui = units().find(src);
1712  if (ui.valid()) {
1713  u = ui.get_shared_ptr().get();
1714  }
1715  ++arg;
1716  }
1717 
1718  dst = luaW_checklocation(L, arg);
1719  ++arg;
1720 
1721  if (!board().map().on_board(src))
1722  return luaL_argerror(L, 1, "invalid location");
1723  if (!board().map().on_board(dst))
1724  return luaL_argerror(L, arg - 2, "invalid location");
1725 
1726  const gamemap &map = board().map();
1727  int viewing_side = 0;
1728  bool ignore_units = false, see_all = false, ignore_teleport = false;
1729  double stop_at = 10000;
1730  std::unique_ptr<pathfind::cost_calculator> calc;
1731 
1732  if (lua_istable(L, arg))
1733  {
1734  ignore_units = luaW_table_get_def<bool>(L, arg, "ignore_units", false);
1735 
1736  ignore_teleport = luaW_table_get_def<bool>(L, arg, "ignore_teleport", false);
1737 
1738  stop_at = luaW_table_get_def<double>(L, arg, "stop_at", stop_at);
1739 
1740 
1741  lua_pushstring(L, "viewing_side");
1742  lua_rawget(L, arg);
1743  if (!lua_isnil(L, -1)) {
1744  int i = luaL_checkinteger(L, -1);
1745  if (i >= 1 && i <= static_cast<int>(teams().size())) viewing_side = i;
1746  else see_all = true;
1747  }
1748  lua_pop(L, 1);
1749 
1750  lua_pushstring(L, "calculate");
1751  lua_rawget(L, arg);
1752  if(lua_isfunction(L, -1)) {
1753  calc.reset(new lua_pathfind_cost_calculator(L, lua_gettop(L)));
1754  }
1755  // Don't pop, the lua_pathfind_cost_calculator requires it to stay on the stack.
1756  }
1757  else if (lua_isfunction(L, arg))
1758  {
1759  deprecated_message("wesnoth.find_path with cost_function as last argument", DEP_LEVEL::FOR_REMOVAL, {1, 17, 0}, "Use calculate=cost_function inside the path options table instead.");
1760  calc.reset(new lua_pathfind_cost_calculator(L, arg));
1761  }
1762 
1763  const team& viewing_team = viewing_side
1764  ? board().get_team(viewing_side)
1765  : board().get_team(u->side());
1766 
1767  pathfind::teleport_map teleport_locations;
1768 
1769  if(!ignore_teleport) {
1770  teleport_locations = pathfind::get_teleport_locations(*u, viewing_team, see_all, ignore_units);
1771  }
1772 
1773  if (!calc) {
1774  if (!u) return luaL_argerror(L, 1, "unit not found");
1775 
1776  calc.reset(new pathfind::shortest_path_calculator(*u, viewing_team,
1777  teams(), map, ignore_units, false, see_all));
1778  }
1779 
1780  pathfind::plain_route res = pathfind::a_star_search(src, dst, stop_at, *calc, map.w(), map.h(),
1781  &teleport_locations);
1782 
1783  int nb = res.steps.size();
1784  lua_createtable(L, nb, 0);
1785  for (int i = 0; i < nb; ++i)
1786  {
1787  lua_createtable(L, 2, 0);
1788  lua_pushinteger(L, res.steps[i].wml_x());
1789  lua_rawseti(L, -2, 1);
1790  lua_pushinteger(L, res.steps[i].wml_y());
1791  lua_rawseti(L, -2, 2);
1792  lua_rawseti(L, -2, i + 1);
1793  }
1794  lua_pushinteger(L, res.move_cost);
1795 
1796  return 2;
1797 }
1798 
1799 /**
1800  * Finds all the locations reachable by a unit.
1801  * - Arg 1: source location OR unit.
1802  * - Arg 2: optional table (optional fields: ignore_units, ignore_teleport, additional_turns, viewing_side).
1803  * - Ret 1: array of triples (coordinates + remaining movement).
1804  */
1806 {
1807  int arg = 1;
1808  const unit* u = nullptr;
1809 
1810  if (lua_isuserdata(L, arg))
1811  {
1812  u = &luaW_checkunit(L, arg);
1813  ++arg;
1814  }
1815  else
1816  {
1817  map_location src = luaW_checklocation(L, arg);
1818  unit_map::const_unit_iterator ui = units().find(src);
1819  if (!ui.valid())
1820  return luaL_argerror(L, 1, "unit not found");
1821  u = ui.get_shared_ptr().get();
1822  ++arg;
1823  }
1824 
1825  int viewing_side = 0;
1826  bool ignore_units = false, see_all = false, ignore_teleport = false;
1827  int additional_turns = 0;
1828 
1829  if (lua_istable(L, arg))
1830  {
1831  lua_pushstring(L, "ignore_units");
1832  lua_rawget(L, arg);
1833  ignore_units = luaW_toboolean(L, -1);
1834  lua_pop(L, 1);
1835 
1836  lua_pushstring(L, "ignore_teleport");
1837  lua_rawget(L, arg);
1838  ignore_teleport = luaW_toboolean(L, -1);
1839  lua_pop(L, 1);
1840 
1841  lua_pushstring(L, "additional_turns");
1842  lua_rawget(L, arg);
1843  additional_turns = lua_tointeger(L, -1);
1844  lua_pop(L, 1);
1845 
1846  lua_pushstring(L, "viewing_side");
1847  lua_rawget(L, arg);
1848  if (!lua_isnil(L, -1)) {
1849  int i = luaL_checkinteger(L, -1);
1850  if (i >= 1 && i <= static_cast<int>(teams().size())) viewing_side = i;
1851  else see_all = true;
1852  }
1853  lua_pop(L, 1);
1854  }
1855 
1856  const team& viewing_team = viewing_side
1857  ? board().get_team(viewing_side)
1858  : board().get_team(u->side());
1859 
1860  pathfind::paths res(*u, ignore_units, !ignore_teleport,
1861  viewing_team, additional_turns, see_all, ignore_units);
1862 
1863  int nb = res.destinations.size();
1864  lua_createtable(L, nb, 0);
1865  for (int i = 0; i < nb; ++i)
1866  {
1868  lua_createtable(L, 2, 0);
1869  lua_pushinteger(L, s.curr.wml_x());
1870  lua_rawseti(L, -2, 1);
1871  lua_pushinteger(L, s.curr.wml_y());
1872  lua_rawseti(L, -2, 2);
1873  lua_pushinteger(L, s.move_left);
1874  lua_rawseti(L, -2, 3);
1875  lua_rawseti(L, -2, i + 1);
1876  }
1877 
1878  return 1;
1879 }
1880 
1881 static bool intf_find_cost_map_helper(const unit * ptr) {
1882  return ptr->get_location().valid();
1883 }
1884 
1885 template<typename T> // This is only a template so I can avoid typing out the long typename. >_>
1886 static int load_fake_units(lua_State* L, int arg, T& fake_units)
1887 {
1888  for (int i = 1, i_end = lua_rawlen(L, arg); i <= i_end; ++i)
1889  {
1890  map_location src;
1891  lua_rawgeti(L, arg, i);
1892  int entry = lua_gettop(L);
1893  if (!lua_istable(L, entry)) {
1894  goto error;
1895  }
1896 
1897  if (!luaW_tolocation(L, entry, src)) {
1898  goto error;
1899  }
1900 
1901  lua_rawgeti(L, entry, 3);
1902  if (!lua_isnumber(L, -1)) {
1903  lua_getfield(L, entry, "side");
1904  if (!lua_isnumber(L, -1)) {
1905  goto error;
1906  }
1907  }
1908  int side = lua_tointeger(L, -1);
1909 
1910  lua_rawgeti(L, entry, 4);
1911  if (!lua_isstring(L, -1)) {
1912  lua_getfield(L, entry, "type");
1913  if (!lua_isstring(L, -1)) {
1914  goto error;
1915  }
1916  }
1917  std::string unit_type = lua_tostring(L, -1);
1918 
1919  fake_units.emplace_back(src, side, unit_type);
1920 
1921  lua_settop(L, entry - 1);
1922  }
1923  return 0;
1924 error:
1925  return luaL_argerror(L, arg, "unit type table malformed - each entry should be either array of 4 elements or table with keys x, y, side, type");
1926 }
1927 
1928 /**
1929  * Is called with one or more units and builds a cost map.
1930  * - Arg 1: source location. (Or Arg 1: unit. Or Arg 1: table containing a filter)
1931  * - Arg 2: optional array of tables with 4 elements (coordinates + side + unit type string)
1932  * - Arg 3: optional table (optional fields: ignore_units, ignore_teleport, viewing_side, debug).
1933  * - Arg 4: optional table: standard location filter.
1934  * - Ret 1: array of triples (coordinates + array of tuples(summed cost + reach counter)).
1935  */
1937 {
1938  int arg = 1;
1939  unit* unit = luaW_tounit(L, arg, true);
1941  luaW_tovconfig(L, arg, filter);
1942 
1943  std::vector<const ::unit*> real_units;
1944  typedef std::vector<std::tuple<map_location, int, std::string>> unit_type_vector;
1945  unit_type_vector fake_units;
1946 
1947 
1948  if (unit) // 1. arg - unit
1949  {
1950  real_units.push_back(unit);
1951  }
1952  else if (!filter.null()) // 1. arg - filter
1953  {
1954  boost::copy(unit_filter(filter).all_matches_on_map() | boost::adaptors::filtered(&intf_find_cost_map_helper), std::back_inserter(real_units));
1955  }
1956  else // 1. arg - coordinates
1957  {
1958  map_location src = luaW_checklocation(L, arg);
1959  unit_map::const_unit_iterator ui = units().find(src);
1960  if (ui.valid())
1961  {
1962  real_units.push_back(&(*ui));
1963  }
1964  }
1965  ++arg;
1966 
1967  if (lua_istable(L, arg)) // 2. arg - optional types
1968  {
1969  load_fake_units(L, arg, fake_units);
1970  ++arg;
1971  }
1972 
1973  if(real_units.empty() && fake_units.empty())
1974  {
1975  return luaL_argerror(L, 1, "unit(s) not found");
1976  }
1977 
1978  int viewing_side = 0;
1979  bool ignore_units = true, see_all = true, ignore_teleport = false, debug = false, use_max_moves = false;
1980 
1981  if (lua_istable(L, arg)) // 4. arg - options
1982  {
1983  lua_pushstring(L, "ignore_units");
1984  lua_rawget(L, arg);
1985  if (!lua_isnil(L, -1))
1986  {
1987  ignore_units = luaW_toboolean(L, -1);
1988  }
1989  lua_pop(L, 1);
1990 
1991  lua_pushstring(L, "ignore_teleport");
1992  lua_rawget(L, arg);
1993  if (!lua_isnil(L, -1))
1994  {
1995  ignore_teleport = luaW_toboolean(L, -1);
1996  }
1997  lua_pop(L, 1);
1998 
1999  lua_pushstring(L, "viewing_side");
2000  lua_rawget(L, arg);
2001  if (!lua_isnil(L, -1))
2002  {
2003  int i = luaL_checkinteger(L, -1);
2004  if (i >= 1 && i <= static_cast<int>(teams().size()))
2005  {
2006  viewing_side = i;
2007  see_all = false;
2008  }
2009  }
2010 
2011  lua_pushstring(L, "debug");
2012  lua_rawget(L, arg);
2013  if (!lua_isnil(L, -1))
2014  {
2015  debug = luaW_toboolean(L, -1);
2016  }
2017  lua_pop(L, 1);
2018 
2019  lua_pushstring(L, "use_max_moves");
2020  lua_rawget(L, arg);
2021  if (!lua_isnil(L, -1))
2022  {
2023  use_max_moves = luaW_toboolean(L, -1);
2024  }
2025  lua_pop(L, 1);
2026  ++arg;
2027  }
2028 
2029  // 5. arg - location filter
2030  filter = vconfig::unconstructed_vconfig();
2031  std::set<map_location> location_set;
2032  luaW_tovconfig(L, arg, filter);
2033  if (filter.null())
2034  {
2035  filter = vconfig(config(), true);
2036  }
2037  filter_context & fc = game_state_;
2038  const terrain_filter t_filter(filter, &fc);
2039  t_filter.get_locations(location_set, true);
2040  ++arg;
2041 
2042  // build cost_map
2043  const team& viewing_team = viewing_side
2044  ? board().get_team(viewing_side)
2045  : board().teams()[0];
2046 
2047  pathfind::full_cost_map cost_map(
2048  ignore_units, !ignore_teleport, viewing_team, see_all, ignore_units);
2049 
2050  for (const ::unit* const u : real_units)
2051  {
2052  cost_map.add_unit(*u, use_max_moves);
2053  }
2054  for (const unit_type_vector::value_type& fu : fake_units)
2055  {
2056  const unit_type* ut = unit_types.find(std::get<2>(fu));
2057  cost_map.add_unit(std::get<0>(fu), ut, std::get<1>(fu));
2058  }
2059 
2060  if (debug)
2061  {
2062  if (game_display_) {
2063  game_display_->labels().clear_all();
2064  for (const map_location& loc : location_set)
2065  {
2066  std::stringstream s;
2067  s << cost_map.get_pair_at(loc).first;
2068  s << " / ";
2069  s << cost_map.get_pair_at(loc).second;
2070  game_display_->labels().set_label(loc, s.str());
2071  }
2072  }
2073  }
2074 
2075  // create return value
2076  lua_createtable(L, location_set.size(), 0);
2077  int counter = 1;
2078  for (const map_location& loc : location_set)
2079  {
2080  lua_createtable(L, 4, 0);
2081 
2082  lua_pushinteger(L, loc.wml_x());
2083  lua_rawseti(L, -2, 1);
2084 
2085  lua_pushinteger(L, loc.wml_y());
2086  lua_rawseti(L, -2, 2);
2087 
2088  lua_pushinteger(L, cost_map.get_pair_at(loc).first);
2089  lua_rawseti(L, -2, 3);
2090 
2091  lua_pushinteger(L, cost_map.get_pair_at(loc).second);
2092  lua_rawseti(L, -2, 4);
2093 
2094  lua_rawseti(L, -2, counter);
2095  ++counter;
2096  }
2097  return 1;
2098 }
2099 
2101  vconfig cfg(luaW_checkvconfig(L, 1));
2102 
2103  // Remove any old message.
2104  static int floating_label = 0;
2105  if (floating_label)
2106  font::remove_floating_label(floating_label);
2107 
2108  // Display a message on-screen
2109  std::string text = cfg["text"];
2110  if(text.empty() || !game_display_)
2111  return 0;
2112 
2113  int size = cfg["size"].to_int(font::SIZE_SMALL);
2114  int lifetime = cfg["duration"].to_int(50);
2115 
2116  color_t color = font::LABEL_COLOR;
2117 
2118  if(!cfg["color"].empty()) {
2119  color = color_t::from_rgb_string(cfg["color"]);
2120  } else if(cfg.has_attribute("red") || cfg.has_attribute("green") || cfg.has_attribute("blue")) {
2121  color = color_t(cfg["red"], cfg["green"], cfg["blue"]);
2122  }
2123 
2124  const SDL_Rect& rect = game_display_->map_outside_area();
2125 
2126  font::floating_label flabel(text);
2127  flabel.set_font_size(size);
2128  flabel.set_color(color);
2129  flabel.set_position(rect.x + rect.w/2, rect.y + rect.h/2);
2130  flabel.set_lifetime(lifetime);
2131  flabel.set_clip_rect(rect);
2132 
2133  floating_label = font::add_floating_label(flabel);
2134 
2135  return 0;
2136 }
2137 
2139 {
2140  if(game_display_) {
2141  game_display_->invalidate(loc);
2142  }
2143 
2144  units().erase(loc);
2145  resources::whiteboard->on_kill_unit();
2146 }
2147 
2148 /**
2149  * Places a unit on the map.
2150  * - Arg 1: (optional) location.
2151  * - Arg 2: Unit (WML table or proxy), or nothing/nil to delete.
2152  * OR
2153  * - Arg 1: Unit (WML table or proxy)
2154  * - Arg 2: (optional) location
2155  * - Arg 3: (optional) boolean
2156  */
2158 {
2159  if(map_locked_) {
2160  return luaL_error(L, "Attempted to move a unit while the map is locked");
2161  }
2162 
2163  map_location loc;
2164  if (luaW_tolocation(L, 2, loc)) {
2165  if (!map().on_board(loc)) {
2166  return luaL_argerror(L, 2, "invalid location");
2167  }
2168  }
2169 
2170  if((luaW_isunit(L, 1))) {
2171  lua_unit& u = *luaW_checkunit_ref(L, 1);
2172  if(u.on_map() && u->get_location() == loc) {
2173  return 0;
2174  }
2175  if (!loc.valid()) {
2176  loc = u->get_location();
2177  if (!map().on_board(loc))
2178  return luaL_argerror(L, 1, "invalid location");
2179  }
2180 
2181  put_unit_helper(loc);
2182  u.put_map(loc);
2183  u.get_shared()->anim_comp().set_standing();
2184  } else if(!lua_isnoneornil(L, 1)) {
2185  const vconfig* vcfg = nullptr;
2186  config cfg = luaW_checkconfig(L, 1, vcfg);
2187  if (!map().on_board(loc)) {
2188  loc.set_wml_x(cfg["x"]);
2189  loc.set_wml_y(cfg["y"]);
2190  if (!map().on_board(loc))
2191  return luaL_argerror(L, 2, "invalid location");
2192  }
2193 
2194  unit_ptr u = unit::create(cfg, true, vcfg);
2195  put_unit_helper(loc);
2196  u->set_location(loc);
2197  units().insert(u);
2198  }
2199 
2200  // Fire event if using the deprecated version or if the final argument is not false
2201  // If the final boolean argument is omitted, the actual final argument (the unit or location) will always yield true.
2202  if(luaW_toboolean(L, -1)) {
2203  play_controller_.pump().fire("unit_placed", loc);
2204  }
2205  return 0;
2206 }
2207 
2208 /**
2209  * Erases a unit from the map
2210  * - Arg 1: Unit to erase OR Location to erase unit
2211  */
2213 {
2214  if(map_locked_) {
2215  return luaL_error(L, "Attempted to remove a unit while the map is locked");
2216  }
2217  map_location loc;
2218 
2219  if(luaW_isunit(L, 1)) {
2220  lua_unit& u = *luaW_checkunit_ref(L, 1);
2221  if (u.on_map()) {
2222  loc = u->get_location();
2223  if (!map().on_board(loc)) {
2224  return luaL_argerror(L, 1, "invalid location");
2225  }
2226  } else if (int side = u.on_recall_list()) {
2227  team &t = board().get_team(side);
2228  // Should it use underlying ID instead?
2230  } else {
2231  return luaL_argerror(L, 1, "can't erase private units");
2232  }
2233  } else if (luaW_tolocation(L, 1, loc)) {
2234  if (!map().on_board(loc)) {
2235  return luaL_argerror(L, 1, "invalid location");
2236  }
2237  } else {
2238  return luaL_argerror(L, 1, "expected unit or location");
2239  }
2240 
2241  units().erase(loc);
2242  resources::whiteboard->on_kill_unit();
2243  return 0;
2244 }
2245 
2246 /**
2247  * Puts a unit on a recall list.
2248  * - Arg 1: WML table or unit.
2249  * - Arg 2: (optional) side.
2250  */
2252 {
2253  if(map_locked_) {
2254  return luaL_error(L, "Attempted to move a unit while the map is locked");
2255  }
2256  lua_unit *lu = nullptr;
2257  unit_ptr u = unit_ptr();
2258  int side = lua_tointeger(L, 2);
2259  if (static_cast<unsigned>(side) > teams().size()) side = 0;
2260 
2261  if(luaW_isunit(L, 1)) {
2262  lu = luaW_checkunit_ref(L, 1);
2263  u = lu->get_shared();
2264  if(lu->on_recall_list() && lu->on_recall_list() == side) {
2265  return luaL_argerror(L, 1, "unit already on recall list");
2266  }
2267  } else {
2268  const vconfig* vcfg = nullptr;
2269  config cfg = luaW_checkconfig(L, 1, vcfg);
2270  u = unit::create(cfg, true, vcfg);
2271  }
2272 
2273  if (!side) {
2274  side = u->side();
2275  } else {
2276  u->set_side(side);
2277  }
2278  team &t = board().get_team(side);
2279  // Avoid duplicates in the recall list.
2280  std::size_t uid = u->underlying_id();
2282  t.recall_list().add(u);
2283  if (lu) {
2284  if (lu->on_map()) {
2285  units().erase(u->get_location());
2286  resources::whiteboard->on_kill_unit();
2287  u->anim_comp().clear_haloes();
2288  }
2289  lu->lua_unit::~lua_unit();
2290  new(lu) lua_unit(side, uid);
2291  }
2292 
2293  return 0;
2294 }
2295 
2296 /**
2297  * Extracts a unit from the map or a recall list and gives it to Lua.
2298  * - Arg 1: unit userdata.
2299  */
2301 {
2302  if(map_locked_) {
2303  return luaL_error(L, "Attempted to remove a unit while the map is locked");
2304  }
2305  lua_unit* lu = luaW_checkunit_ref(L, 1);
2306  unit_ptr u = lu->get_shared();
2307 
2308  if (lu->on_map()) {
2309  u = units().extract(u->get_location());
2310  assert(u);
2311  u->anim_comp().clear_haloes();
2312  } else if (int side = lu->on_recall_list()) {
2313  team &t = board().get_team(side);
2314  unit_ptr v = u->clone();
2315  t.recall_list().erase_if_matches_id(u->id());
2316  u = v;
2317  } else {
2318  return 0;
2319  }
2320 
2321  lu->lua_unit::~lua_unit();
2322  new(lu) lua_unit(u);
2323  return 0;
2324 }
2325 
2326 /**
2327  * Finds a vacant tile.
2328  * - Arg 1: location.
2329  * - Arg 2: optional unit for checking movement type.
2330  * - Rets 1,2: location.
2331  */
2333 {
2334  map_location loc = luaW_checklocation(L, 1);
2335 
2336  unit_ptr u;
2337  if (!lua_isnoneornil(L, 2)) {
2338  if(luaW_isunit(L, 2)) {
2339  u = luaW_checkunit_ptr(L, 2, false);
2340  } else {
2341  const vconfig* vcfg = nullptr;
2342  config cfg = luaW_checkconfig(L, 2, vcfg);
2343  u = unit::create(cfg, false, vcfg);
2344  }
2345  }
2346 
2347  map_location res = find_vacant_tile(loc, pathfind::VACANT_ANY, u.get());
2348 
2349  if (!res.valid()) return 0;
2350  lua_pushinteger(L, res.wml_x());
2351  lua_pushinteger(L, res.wml_y());
2352  return 2;
2353 }
2354 
2355 /**
2356  * Floats some text on the map.
2357  * - Arg 1: location.
2358  * - Arg 2: string.
2359  * - Arg 3: color.
2360  */
2362 {
2363  map_location loc = luaW_checklocation(L, 1);
2364  color_t color = font::LABEL_COLOR;
2365 
2366  t_string text = luaW_checktstring(L, 2);
2367  if (!lua_isnoneornil(L, 3)) {
2369  }
2370 
2371  if (game_display_) {
2372  game_display_->float_label(loc, text, color);
2373  }
2374  return 0;
2375 }
2376 
2377 /**
2378  * Creates a unit from its WML description.
2379  * - Arg 1: WML table.
2380  * - Ret 1: unit userdata.
2381  */
2383 {
2384  const vconfig* vcfg = nullptr;
2385  config cfg = luaW_checkconfig(L, 1, vcfg);
2386  unit_ptr u = unit::create(cfg, true, vcfg);
2387  luaW_pushunit(L, u);
2388  return 1;
2389 }
2390 
2391 /**
2392  * Copies a unit.
2393  * - Arg 1: unit userdata.
2394  * - Ret 1: unit userdata.
2395  */
2397 {
2398  unit& u = luaW_checkunit(L, 1);
2399  luaW_pushunit(L, u.clone());
2400  return 1;
2401 }
2402 
2403 /**
2404  * Returns unit resistance against a given attack type.
2405  * - Arg 1: unit userdata.
2406  * - Arg 2: string containing the attack type.
2407  * - Arg 3: boolean indicating if attacker.
2408  * - Arg 4: optional location.
2409  * - Ret 1: integer.
2410  */
2412 {
2413  const unit& u = luaW_checkunit(L, 1);
2414  char const *m = luaL_checkstring(L, 2);
2415  bool a = false;
2416  map_location loc = u.get_location();
2417 
2418  if(lua_isboolean(L, 3)) {
2419  a = luaW_toboolean(L, 3);
2420  if(!lua_isnoneornil(L, 4)) {
2421  loc = luaW_checklocation(L, 4);
2422  }
2423  } else if(!lua_isnoneornil(L, 3)) {
2424  loc = luaW_checklocation(L, 3);
2425  }
2426 
2427  lua_pushinteger(L, 100 - u.resistance_against(m, a, loc));
2428  return 1;
2429 }
2430 
2431 /**
2432  * Returns unit movement cost on a given terrain.
2433  * - Arg 1: unit userdata.
2434  * - Arg 2: string containing the terrain type.
2435  * - Ret 1: integer.
2436  */
2438 {
2439  const unit& u = luaW_checkunit(L, 1);
2441  map_location loc;
2442  if(luaW_tolocation(L, 2, loc)) {
2443  t = resources::gameboard->map()[loc];
2444  } else if(lua_isstring(L, 2)) {
2445  char const *m = luaL_checkstring(L, 2);
2447  } else return luaW_type_error(L, 2, "location or terrain string");
2448  lua_pushinteger(L, u.movement_cost(t));
2449  return 1;
2450 }
2451 
2452 /**
2453  * Returns unit vision cost on a given terrain.
2454  * - Arg 1: unit userdata.
2455  * - Arg 2: string containing the terrain type.
2456  * - Ret 1: integer.
2457  */
2459 {
2460  const unit& u = luaW_checkunit(L, 1);
2462  map_location loc;
2463  if(luaW_tolocation(L, 2, loc)) {
2464  t = resources::gameboard->map()[loc];
2465  } else if(lua_isstring(L, 2)) {
2466  char const *m = luaL_checkstring(L, 2);
2468  } else return luaW_type_error(L, 2, "location or terrain string");
2469  lua_pushinteger(L, u.vision_cost(t));
2470  return 1;
2471 }
2472 
2473 /**
2474  * Returns unit jamming cost on a given terrain.
2475  * - Arg 1: unit userdata.
2476  * - Arg 2: string containing the terrain type.
2477  * - Ret 1: integer.
2478  */
2480 {
2481  const unit& u = luaW_checkunit(L, 1);
2483  map_location loc;
2484  if(luaW_tolocation(L, 2, loc)) {
2485  t = resources::gameboard->map()[loc];
2486  } else if(lua_isstring(L, 2)) {
2487  char const *m = luaL_checkstring(L, 2);
2489  } else return luaW_type_error(L, 2, "location or terrain string");
2490  lua_pushinteger(L, u.jamming_cost(t));
2491  return 1;
2492 }
2493 
2494 /**
2495  * Returns unit defense on a given terrain.
2496  * - Arg 1: unit userdata.
2497  * - Arg 2: string containing the terrain type.
2498  * - Ret 1: integer.
2499  */
2501 {
2502  const unit& u = luaW_checkunit(L, 1);
2504  map_location loc;
2505  if(luaW_tolocation(L, 2, loc)) {
2506  t = resources::gameboard->map()[loc];
2507  } else if(lua_isstring(L, 2)) {
2508  char const *m = luaL_checkstring(L, 2);
2510  } else return luaW_type_error(L, 2, "location or terrain string");
2511  lua_pushinteger(L, 100 - u.defense_modifier(t));
2512  return 1;
2513 }
2514 
2515 /**
2516  * Returns true if the unit has the given ability enabled.
2517  * - Arg 1: unit userdata.
2518  * - Arg 2: string.
2519  * - Ret 1: boolean.
2520  */
2522 {
2523  const unit& u = luaW_checkunit(L, 1);
2524  char const *m = luaL_checkstring(L, 2);
2526  return 1;
2527 }
2528 
2529 /**
2530  * Changes a unit to the given unit type.
2531  * - Arg 1: unit userdata.
2532  * - Arg 2: unit type name
2533  * - Arg 3: (optional) unit variation name
2534  */
2536 {
2537  unit& u = luaW_checkunit(L, 1);
2538  char const *m = luaL_checkstring(L, 2);
2539  const unit_type *utp = unit_types.find(m);
2540  if (!utp) return luaL_argerror(L, 2, "unknown unit type");
2541  if(lua_isstring(L, 3)) {
2542  const std::string& m2 = lua_tostring(L, 3);
2543  if(!utp->has_variation(m2)) return luaL_argerror(L, 2, "unknown unit variation");
2544  utp = &utp->get_variation(m2);
2545  }
2546  u.advance_to(*utp);
2547 
2548  return 0;
2549 }
2550 
2551 /**
2552  * Puts a table at the top of the stack with some combat result.
2553  */
2554 static void luaW_pushsimdata(lua_State *L, const combatant &cmb)
2555 {
2556  int n = cmb.hp_dist.size();
2557  lua_createtable(L, 0, 4);
2558  lua_pushnumber(L, cmb.poisoned);
2559  lua_setfield(L, -2, "poisoned");
2560  lua_pushnumber(L, cmb.slowed);
2561  lua_setfield(L, -2, "slowed");
2562  lua_pushnumber(L, cmb.untouched);
2563  lua_setfield(L, -2, "untouched");
2564  lua_pushnumber(L, cmb.average_hp());
2565  lua_setfield(L, -2, "average_hp");
2566  lua_createtable(L, n, 0);
2567  for (int i = 0; i < n; ++i) {
2568  lua_pushnumber(L, cmb.hp_dist[i]);
2569  lua_rawseti(L, -2, i);
2570  }
2571  lua_setfield(L, -2, "hp_chance");
2572 }
2573 
2574 /**
2575  * Puts a table at the top of the stack with information about the combatants' weapons.
2576  */
2578 {
2579 
2580  lua_createtable(L, 0, 16);
2581 
2582  lua_pushnumber(L, bcustats.num_blows);
2583  lua_setfield(L, -2, "num_blows");
2584  lua_pushnumber(L, bcustats.damage);
2585  lua_setfield(L, -2, "damage");
2586  lua_pushnumber(L, bcustats.chance_to_hit);
2587  lua_setfield(L, -2, "chance_to_hit");
2588  lua_pushboolean(L, bcustats.poisons);
2589  lua_setfield(L, -2, "poisons");
2590  lua_pushboolean(L, bcustats.slows);
2591  lua_setfield(L, -2, "slows");
2592  lua_pushboolean(L, bcustats.petrifies);
2593  lua_setfield(L, -2, "petrifies");
2594  lua_pushboolean(L, bcustats.plagues);
2595  lua_setfield(L, -2, "plagues");
2596  lua_pushstring(L, bcustats.plague_type.c_str());
2597  lua_setfield(L, -2, "plague_type");
2598  lua_pushboolean(L, bcustats.backstab_pos);
2599  lua_setfield(L, -2, "backstabs");
2600  lua_pushnumber(L, bcustats.rounds);
2601  lua_setfield(L, -2, "rounds");
2602  lua_pushboolean(L, bcustats.firststrike);
2603  lua_setfield(L, -2, "firststrike");
2604  lua_pushboolean(L, bcustats.drains);
2605  lua_setfield(L, -2, "drains");
2606  lua_pushnumber(L, bcustats.drain_constant);
2607  lua_setfield(L, -2, "drain_constant");
2608  lua_pushnumber(L, bcustats.drain_percent);
2609  lua_setfield(L, -2, "drain_percent");
2610 
2611 
2612  //if we called simulate_combat without giving an explicit weapon this can be useful.
2613  lua_pushnumber(L, bcustats.attack_num);
2614  lua_setfield(L, -2, "attack_num"); // DEPRECATED
2615  lua_pushnumber(L, bcustats.attack_num + 1);
2616  lua_setfield(L, -2, "number");
2617  //this is nullptr when there is no counter weapon
2618  if(bcustats.weapon != nullptr)
2619  {
2620  lua_pushstring(L, bcustats.weapon->id().c_str());
2621  lua_setfield(L, -2, "name");
2622  luaW_pushweapon(L, bcustats.weapon);
2623  lua_setfield(L, -2, "weapon");
2624  }
2625 
2626 }
2627 
2628 /**
2629  * Simulates a combat between two units.
2630  * - Arg 1: attacker userdata.
2631  * - Arg 2: optional weapon index.
2632  * - Arg 3: defender userdata.
2633  * - Arg 4: optional weapon index.
2634  *
2635  * - Ret 1: attacker results.
2636  * - Ret 2: defender results.
2637  * - Ret 3: info about the attacker weapon.
2638  * - Ret 4: info about the defender weapon.
2639  */
2641 {
2642  int arg_num = 1, att_w = -1, def_w = -1;
2643 
2644  unit_const_ptr att = luaW_checkunit(L, arg_num).shared_from_this();
2645  ++arg_num;
2646  if (lua_isnumber(L, arg_num)) {
2647  att_w = lua_tointeger(L, arg_num) - 1;
2648  if (att_w < 0 || att_w >= static_cast<int>(att->attacks().size()))
2649  return luaL_argerror(L, arg_num, "weapon index out of bounds");
2650  ++arg_num;
2651  }
2652 
2653  unit_const_ptr def = luaW_checkunit(L, arg_num).shared_from_this();
2654  ++arg_num;
2655  if (lua_isnumber(L, arg_num)) {
2656  def_w = lua_tointeger(L, arg_num) - 1;
2657  if (def_w < 0 || def_w >= static_cast<int>(def->attacks().size()))
2658  return luaL_argerror(L, arg_num, "weapon index out of bounds");
2659  ++arg_num;
2660  }
2661 
2662  battle_context context(units(), att->get_location(),
2663  def->get_location(), att_w, def_w, 0.0, nullptr, att.get(), def.get());
2664 
2665  luaW_pushsimdata(L, context.get_attacker_combatant());
2666  luaW_pushsimdata(L, context.get_defender_combatant());
2667  luaW_pushsimweapon(L, context.get_attacker_stats());
2668  luaW_pushsimweapon(L, context.get_defender_stats());
2669  return 4;
2670 }
2671 
2672 /**
2673  * Modifies the music playlist.
2674  * - Arg 1: WML table, or nil to force changes.
2675  */
2677 {
2678  deprecated_message("wesnoth.set_music", DEP_LEVEL::INDEFINITE, "", "Use the wesnoth.playlist table instead!");
2679  if (lua_isnoneornil(L, 1)) {
2681  return 0;
2682  }
2683 
2684  config cfg = luaW_checkconfig(L, 1);
2686  return 0;
2687 }
2688 
2689 /**
2690  * Plays a sound, possibly repeated.
2691  * - Arg 1: string.
2692  * - Arg 2: optional integer.
2693  */
2695 {
2696  char const *m = luaL_checkstring(L, 1);
2697  if (play_controller_.is_skipping_replay()) return 0;
2698  int repeats = lua_tointeger(L, 2);
2699  sound::play_sound(m, sound::SOUND_FX, repeats);
2700  return 0;
2701 }
2702 
2703 /**
2704  * Gets/sets the current sound volume
2705  * - Arg 1: (optional) New volume to set
2706  * - Return: Original volume
2707  */
2709 {
2710  int vol = preferences::sound_volume();
2711  lua_pushnumber(L, sound::get_sound_volume() * 100.0 / vol);
2712  if(lua_isnumber(L, 1)) {
2713  float rel = lua_tonumber(L, 1);
2714  if(rel < 0.0f || rel > 100.0f) {
2715  return luaL_argerror(L, 1, "volume must be in range 0..100");
2716  }
2717  vol = static_cast<int>(rel*vol / 100.0f);
2719  }
2720  return 1;
2721 }
2722 
2723 /**
2724  * Scrolls to given tile.
2725  * - Arg 1: location.
2726  * - Arg 2: boolean preventing scroll to fog.
2727  * - Arg 3: boolean specifying whether to warp instantly.
2728  * - Arg 4: boolean specifying whether to skip if already onscreen
2729  */
2731 {
2732  map_location loc = luaW_checklocation(L, 1);
2733  bool check_fogged = luaW_toboolean(L, 2);
2735  ? luaW_toboolean(L, 3)
2738  : luaW_toboolean(L, 3)
2741  ;
2742  if (game_display_) {
2743  game_display_->scroll_to_tile(loc, scroll, check_fogged);
2744  }
2745  return 0;
2746 }
2747 
2749 {
2750  events::command_disabler command_disabler;
2751  deprecated_message("wesnoth.select_hex", DEP_LEVEL::PREEMPTIVE, {1, 15, 0}, "Use wesnoth.units.select and/or wesnoth.interface.highlight_hex instead.");
2752 
2753  // Need this because check_location may change the stack
2754  // By doing this now, we ensure that it won't do so when
2755  // intf_select_unit and intf_highlight_hex call it.
2756  const map_location loc = luaW_checklocation(L, 1);
2757  luaW_pushlocation(L, loc);
2758  lua_replace(L, 1);
2759 
2760  intf_select_unit(L);
2761  if(!lua_isnoneornil(L, 2) && luaW_toboolean(L,2)) {
2762  intf_highlight_hex(L);
2763  }
2764  return 0;
2765 }
2766 
2767 /**
2768  * Selects and highlights the given location on the map.
2769  * - Arg 1: location.
2770  * - Args 2,3: booleans
2771  */
2773 {
2774  events::command_disabler command_disabler;
2775  if(lua_isnoneornil(L, 1)) {
2776  play_controller_.get_mouse_handler_base().select_hex(map_location::null_location(), false, false, false);
2777  return 0;
2778  }
2779  const map_location loc = luaW_checklocation(L, 1);
2780  if(!map().on_board(loc)) return luaL_argerror(L, 1, "not on board");
2781  bool highlight = true;
2782  if(!lua_isnoneornil(L, 2))
2783  highlight = luaW_toboolean(L, 2);
2784  const bool fire_event = luaW_toboolean(L, 3);
2785  play_controller_.get_mouse_handler_base().select_hex(
2786  loc, false, highlight, fire_event);
2787  return 0;
2788 }
2789 
2790 /**
2791  * Deselects any highlighted hex on the map.
2792  * No arguments or return values
2793  */
2795 {
2796  if(game_display_) {
2797  game_display_->highlight_hex(map_location::null_location());
2798  }
2799 
2800  return 0;
2801 }
2802 
2803 /**
2804  * Return true if a replay is in progress but the player has chosen to skip it
2805  */
2807 {
2808  bool skipping = play_controller_.is_skipping_replay() || play_controller_.is_skipping_story();
2809  if (!skipping) {
2810  skipping = game_state_.events_manager_->pump().context_skip_messages();
2811  }
2812  lua_pushboolean(L, skipping);
2813  return 1;
2814 }
2815 
2816 /**
2817  * Set whether to skip messages
2818  * Arg 1 (optional) - boolean
2819  */
2821 {
2822  bool skip = true;
2823  if (!lua_isnone(L, 1)) {
2824  skip = luaW_toboolean(L, 1);
2825  }
2826  game_state_.events_manager_->pump().context_skip_messages(skip);
2827  return 0;
2828 }
2829 
2830 namespace
2831 {
2832  struct lua_synchronize : mp_sync::user_choice
2833  {
2834  lua_State *L;
2835  int user_choice_index;
2836  int random_choice_index;
2837  int ai_choice_index;
2838  std::string desc;
2839  lua_synchronize(lua_State *l, const std::string& descr, int user_index, int random_index = 0, int ai_index = 0)
2840  : L(l)
2841  , user_choice_index(user_index)
2842  , random_choice_index(random_index)
2843  , ai_choice_index(ai_index != 0 ? ai_index : user_index)
2844  , desc(descr)
2845  {}
2846 
2847  virtual config query_user(int side) const override
2848  {
2849  bool is_local_ai = lua_kernel_base::get_lua_kernel<game_lua_kernel>(L).board().get_team(side).is_local_ai();
2850  config cfg;
2851  query_lua(side, is_local_ai ? ai_choice_index : user_choice_index, cfg);
2852  return cfg;
2853  }
2854 
2855  virtual config random_choice(int side) const override
2856  {
2857  config cfg;
2858  if(random_choice_index != 0 && lua_isfunction(L, random_choice_index)) {
2859  query_lua(side, random_choice_index, cfg);
2860  }
2861  return cfg;
2862  }
2863 
2864  virtual std::string description() const override
2865  {
2866  return desc;
2867  }
2868 
2869  void query_lua(int side, int function_index, config& cfg) const
2870  {
2871  assert(cfg.empty());
2872  lua_pushvalue(L, function_index);
2873  lua_pushnumber(L, side);
2874  if (luaW_pcall(L, 1, 1, false)) {
2875  if(!luaW_toconfig(L, -1, cfg)) {
2876  lua_kernel_base::get_lua_kernel<game_lua_kernel>(L).log_error("function returned to wesnoth.synchronize_choice a table which was partially invalid");
2877  }
2878  }
2879  }
2880  //Although lua's sync_choice can show a dialog, (and will in most cases)
2881  //we return false to enable other possible things that do not contain UI things.
2882  //it's in the responsibility of the umc dev to not show dialogs during prestart events.
2883  virtual bool is_visible() const override { return false; }
2884  };
2885 }//unnamed namespace for lua_synchronize
2886 
2887 /**
2888  * Ensures a value is synchronized among all the clients.
2889  * - Arg 1: optional string specifying the type id of the choice.
2890  * - Arg 2: function to compute the value, called if the client is the master.
2891  * - Arg 3: optional function, called instead of the first function if the user is not human.
2892  * - Arg 4: optional integer specifying, on which side the function should be evaluated.
2893  * - Ret 1: WML table returned by the function.
2894  */
2896 {
2897  std::string tagname = "input";
2898  t_string desc = _("input");
2899  int human_func = 0;
2900  int ai_func = 0;
2901  int side_for;
2902 
2903  int nextarg = 1;
2904  if(!lua_isfunction(L, nextarg) && luaW_totstring(L, nextarg, desc) ) {
2905  ++nextarg;
2906  }
2907  if(lua_isfunction(L, nextarg)) {
2908  human_func = nextarg++;
2909  }
2910  else {
2911  return luaL_argerror(L, nextarg, "expected a function");
2912  }
2913  if(lua_isfunction(L, nextarg)) {
2914  ai_func = nextarg++;
2915  }
2916  side_for = lua_tointeger(L, nextarg);
2917 
2918  config cfg = mp_sync::get_user_choice(tagname, lua_synchronize(L, desc, human_func, 0, ai_func), side_for);
2919  luaW_pushconfig(L, cfg);
2920  return 1;
2921 }
2922 /**
2923  * Ensures a value is synchronized among all the clients.
2924  * - Arg 1: optional string the id of this type of user input, may only contain characters a-z and '_'
2925  * - Arg 2: function to compute the value, called if the client is the master.
2926  * - Arg 3: an optional function to compute the value, if the side was null/empty controlled.
2927  * - Arg 4: an array of integers specifying, on which side the function should be evaluated.
2928  * - Ret 1: a map int -> WML tabls.
2929  */
2931 {
2932  std::string tagname = "input";
2933  t_string desc = _("input");
2934  int human_func = 0;
2935  int null_func = 0;
2936  std::vector<int> sides_for;
2937 
2938  int nextarg = 1;
2939  if(!lua_isfunction(L, nextarg) && luaW_totstring(L, nextarg, desc) ) {
2940  ++nextarg;
2941  }
2942  if(lua_isfunction(L, nextarg)) {
2943  human_func = nextarg++;
2944  }
2945  else {
2946  return luaL_argerror(L, nextarg, "expected a function");
2947  }
2948  if(lua_isfunction(L, nextarg)) {
2949  null_func = nextarg++;
2950  };
2951  sides_for = lua_check<std::vector<int>>(L, nextarg++);
2952 
2953  lua_push(L, mp_sync::get_user_choice_multiple_sides(tagname, lua_synchronize(L, desc, human_func, null_func), std::set<int>(sides_for.begin(), sides_for.end())));
2954  return 1;
2955 }
2956 
2957 
2958 /**
2959  * Calls a function in an unsynced context (this specially means that all random calls used by that function will be unsynced).
2960  * This is usually used together with an unsynced if like 'if controller != network'
2961  * - Arg 1: function that will be called during the unsynced context.
2962  */
2964 {
2965  set_scontext_unsynced sync;
2966  lua_pushvalue(L, 1);
2967  luaW_pcall(L, 0, 0, false);
2968  return 0;
2969 }
2970 
2971 /**
2972  * Gets all the locations matching a given filter.
2973  * - Arg 1: WML table.
2974  * - Arg 2: Optional reference unit (teleport_unit)
2975  * - Ret 1: array of integer pairs.
2976  */
2978 {
2979  vconfig filter = luaW_checkvconfig(L, 1);
2980 
2981  std::set<map_location> res;
2982  filter_context & fc = game_state_;
2983  const terrain_filter t_filter(filter, &fc);
2984  if(luaW_isunit(L, 2)) {
2985  t_filter.get_locations(res, *luaW_tounit(L, 2), true);
2986  } else {
2987  t_filter.get_locations(res, true);
2988  }
2989 
2990  lua_createtable(L, res.size(), 0);
2991  int i = 1;
2992  for (const map_location& loc : res)
2993  {
2994  lua_createtable(L, 2, 0);
2995  lua_pushinteger(L, loc.wml_x());
2996  lua_rawseti(L, -2, 1);
2997  lua_pushinteger(L, loc.wml_y());
2998  lua_rawseti(L, -2, 2);
2999  lua_rawseti(L, -2, i);
3000  ++i;
3001  }
3002  return 1;
3003 }
3004 
3005 /**
3006  * Gets all the villages matching a given filter, or all the villages on the map if no filter is given.
3007  * - Arg 1: WML table (optional).
3008  * - Ret 1: array of integer pairs.
3009  */
3011 {
3012  std::vector<map_location> locs = map().villages();
3013  lua_newtable(L);
3014  int i = 1;
3015 
3016  vconfig filter = luaW_checkvconfig(L, 1);
3017 
3018  filter_context & fc = game_state_;
3019  for(std::vector<map_location>::const_iterator it = locs.begin(); it != locs.end(); ++it) {
3020  bool matches = terrain_filter(filter, &fc).match(*it);
3021  if (matches) {
3022  lua_createtable(L, 2, 0);
3023  lua_pushinteger(L, it->wml_x());
3024  lua_rawseti(L, -2, 1);
3025  lua_pushinteger(L, it->wml_y());
3026  lua_rawseti(L, -2, 2);
3027  lua_rawseti(L, -2, i);
3028  ++i;
3029  }
3030  }
3031  return 1;
3032 }
3033 
3034 /**
3035  * Matches a location against the given filter.
3036  * - Arg 1: location.
3037  * - Arg 2: WML table.
3038  * - Arg 3: Optional reference unit (teleport_unit)
3039  * - Ret 1: boolean.
3040  */
3042 {
3043  map_location loc = luaW_checklocation(L, 1);
3044  vconfig filter = luaW_checkvconfig(L, 2, true);
3045 
3046  if (filter.null()) {
3047  lua_pushboolean(L, true);
3048  return 1;
3049  }
3050 
3051  filter_context & fc = game_state_;
3052  const terrain_filter t_filter(filter, &fc);
3053  if(luaW_isunit(L, 3)) {
3054  lua_pushboolean(L, t_filter.match(loc, *luaW_tounit(L, 3)));
3055  } else {
3056  lua_pushboolean(L, t_filter.match(loc));
3057  }
3058  return 1;
3059 }
3060 
3061 
3062 
3063 /**
3064  * Matches a side against the given filter.
3065  * - Args 1: side number.
3066  * - Arg 2: WML table.
3067  * - Ret 1: boolean.
3068  */
3070 {
3071  vconfig filter = luaW_checkvconfig(L, 2, true);
3072 
3073  if (filter.null()) {
3074  lua_pushboolean(L, true);
3075  return 1;
3076  }
3077 
3078  filter_context & fc = game_state_;
3079  side_filter s_filter(filter, &fc);
3080 
3081  if(team* t = luaW_toteam(L, 1)) {
3082  lua_pushboolean(L, s_filter.match(*t));
3083  } else {
3084  unsigned side = luaL_checkinteger(L, 1) - 1;
3085  if (side >= teams().size()) return 0;
3086  lua_pushboolean(L, s_filter.match(side + 1));
3087  }
3088  return 1;
3089 }
3090 
3092 {
3093  int team_i;
3094  if(team* t = luaW_toteam(L, 1)) {
3095  team_i = t->side();
3096  } else {
3097  team_i = luaL_checkinteger(L, 1);
3098  }
3099  std::string flag = luaL_optlstring(L, 2, "", nullptr);
3100  std::string color = luaL_optlstring(L, 3, "", nullptr);
3101 
3102  if(flag.empty() && color.empty()) {
3103  return 0;
3104  }
3105  if(team_i < 1 || static_cast<std::size_t>(team_i) > teams().size()) {
3106  return luaL_error(L, "set_side_id: side number %d out of range", team_i);
3107  }
3108  team& side = board().get_team(team_i);
3109 
3110  if(!color.empty()) {
3111  side.set_color(color);
3112  }
3113  if(!flag.empty()) {
3114  side.set_flag(flag);
3115  }
3116 
3117  game_display_->reinit_flags_for_team(side);
3118  return 0;
3119 }
3120 
3121 static int intf_modify_ai(lua_State *L, const char* action)
3122 {
3123  int side_num;
3124  if(team* t = luaW_toteam(L, 1)) {
3125  side_num = t->side();
3126  } else {
3127  side_num = luaL_checkinteger(L, 1);
3128  }
3129  std::string path = luaL_checkstring(L, 2);
3130  config cfg {
3131  "action", action,
3132  "path", path
3133  };
3134  if(strcmp(action, "delete") == 0) {
3136  return 0;
3137  }
3138  config component = luaW_checkconfig(L, 3);
3139  std::size_t len = std::string::npos, open_brak = path.find_last_of('[');
3140  std::size_t dot = path.find_last_of('.');
3141  if(open_brak != len) {
3142  len = open_brak - dot - 1;
3143  }
3144  cfg.add_child(path.substr(dot + 1, len), component);
3146  return 0;
3147 }
3148 
3150 {
3151  int side_num;
3152  if(team* t = luaW_toteam(L, 1)) {
3153  side_num = t->side();
3154  } else {
3155  side_num = luaL_checkinteger(L, 1);
3156  }
3157  if(lua_isstring(L, 2)) {
3158  std::string file = luaL_checkstring(L, 2);
3159  if(!ai::manager::get_singleton().add_ai_for_side_from_file(side_num, file)) {
3160  std::string err = formatter() << "Could not load AI for side " << side_num << " from file " << file;
3161  lua_pushlstring(L, err.c_str(), err.length());
3162  return lua_error(L);
3163  }
3164  } else {
3166  }
3167  return 0;
3168 }
3169 
3171 {
3172  int side_num;
3173  if(team* t = luaW_toteam(L, 1)) {
3174  side_num = t->side();
3175  } else {
3176  side_num = luaL_checkinteger(L, 1);
3177  }
3178  config cfg = luaW_checkconfig(L, 2);
3179  if(!cfg.has_child("ai")) {
3180  cfg = config {"ai", cfg};
3181  }
3182  bool added_dummy_stage = false;
3183  if(!cfg.child("ai").has_child("stage")) {
3184  added_dummy_stage = true;
3185  cfg.child("ai").add_child("stage", config {"name", "empty"});
3186  }
3188  if(added_dummy_stage) {
3189  for(auto iter = cfg.ordered_begin(); iter != cfg.ordered_end(); iter++) {
3190  if(iter->key == "stage" && iter->cfg["name"] == "empty") {
3191  iter = cfg.erase(iter);
3192  }
3193  }
3194  }
3196  return 0;
3197 }
3198 
3200 {
3201  unsigned i = luaL_checkinteger(L, 1);
3202  if(i < 1 || i > teams().size()) return 0;
3203  luaW_pushteam(L, board().get_team(i));
3204  return 1;
3205 }
3206 
3207 /**
3208  * Returns a proxy table array for all sides matching the given SSF.
3209  * - Arg 1: SSF
3210  * - Ret 1: proxy table array
3211  */
3213 {
3214  LOG_LUA << "intf_get_sides called: this = " << std::hex << this << std::dec << " myname = " << my_name() << std::endl;
3215  std::vector<int> sides;
3216  const vconfig ssf = luaW_checkvconfig(L, 1, true);
3217  if(ssf.null()) {
3218  for (unsigned side_number = 1; side_number <= teams().size(); ++side_number) {
3219  sides.push_back(side_number);
3220  }
3221  } else {
3222  filter_context & fc = game_state_;
3223 
3224  side_filter filter(ssf, &fc);
3225  sides = filter.get_teams();
3226  }
3227 
3228  lua_settop(L, 0);
3229  lua_createtable(L, sides.size(), 0);
3230  unsigned index = 1;
3231  for(int side : sides) {
3232  luaW_pushteam(L, board().get_team(side));
3233  lua_rawseti(L, -2, index);
3234  ++index;
3235  }
3236 
3237  return 1;
3238 }
3239 
3240 /**
3241  * .Returns information about the global traits known to the engine.
3242  * - Ret 1: Table with named fields holding wml tables describing the traits.
3243  */
3245 {
3246  lua_newtable(L);
3247  for(const config& trait : unit_types.traits()) {
3248  const std::string& id = trait["id"];
3249  //It seems the engine does nowhere check the id field for emptyness or duplicates
3250  //(also not later on).
3251  //However, the worst thing to happen is that the trait read later overwrites the older one,
3252  //and this is not the right place for such checks.
3253  lua_pushstring(L, id.c_str());
3254  luaW_pushconfig(L, trait);
3255  lua_rawset(L, -3);
3256  }
3257  return 1;
3258 }
3259 
3260 /**
3261  * Adds a modification to a unit.
3262  * - Arg 1: unit.
3263  * - Arg 2: string.
3264  * - Arg 3: WML table.
3265  * - Arg 4: (optional) Whether to add to [modifications] - default true
3266  */
3268 {
3269  unit& u = luaW_checkunit(L, 1);
3270  char const *m = luaL_checkstring(L, 2);
3271  std::string sm = m;
3272  if (sm == "advance") { // Maintain backwards compatibility
3273  sm = "advancement";
3274  deprecated_message("\"advance\" modification type", DEP_LEVEL::PREEMPTIVE, {1, 15, 0}, "Use \"advancement\" instead.");
3275  }
3276  if (sm != "advancement" && sm != "object" && sm != "trait") {
3277  return luaL_argerror(L, 2, "unknown modification type");
3278  }
3279  bool write_to_mods = true;
3280  if (!lua_isnone(L, 4)) {
3281  write_to_mods = luaW_toboolean(L, 4);
3282  }
3283  if(sm.empty()) {
3284  write_to_mods = false;
3285  }
3286 
3287  config cfg = luaW_checkconfig(L, 3);
3288  u.add_modification(sm, cfg, !write_to_mods);
3289  return 0;
3290 }
3291 
3292 /**
3293  * Removes modifications from a unit
3294  * - Arg 1: unit
3295  * - Arg 2: table (filter as [filter_wml])
3296  * - Arg 3: type of modification (default "object")
3297  */
3299 {
3300  unit& u = luaW_checkunit(L, 1);
3301  config filter = luaW_checkconfig(L, 2);
3302  std::string tag = luaL_optstring(L, 3, "object");
3303  //TODO
3304  if(filter.attribute_count() == 1 && filter.all_children_count() == 0 && filter.attribute_range().front().first == "duration") {
3305  u.expire_modifications(filter["duration"]);
3306  } else {
3307  for(config& obj : u.get_modifications().child_range(tag)) {
3308  if(obj.matches(filter)) {
3309  obj["duration"] = "now";
3310  }
3311  }
3312  u.expire_modifications("now");
3313  }
3314  return 0;
3315 }
3316 
3317 /**
3318  * Advances a unit if the unit has enough xp.
3319  * - Arg 1: unit.
3320  * - Arg 2: optional boolean whether to animate the advancement.
3321  * - Arg 3: optional boolean whether to fire advancement events.
3322  */
3324 {
3325  events::command_disabler command_disabler;
3326  unit& u = luaW_checkunit(L, 1, true);
3328  if(lua_isboolean(L, 2)) {
3329  par.animate(luaW_toboolean(L, 2));
3330  }
3331  if(lua_isboolean(L, 3)) {
3332  par.fire_events(luaW_toboolean(L, 3));
3333  }
3334  advance_unit_at(par);
3335  return 0;
3336 }
3337 
3338 
3339 /**
3340  * Adds a new known unit type to the help system.
3341  * - Arg 1: string.
3342  */
3344 {
3345  char const *ty = luaL_checkstring(L, 1);
3346  if(!unit_types.find(ty))
3347  {
3348  std::stringstream ss;
3349  ss << "unknown unit type: '" << ty << "'";
3350  return luaL_argerror(L, 1, ss.str().c_str());
3351  }
3352  preferences::encountered_units().insert(ty);
3353  return 0;
3354 }
3355 
3356 /**
3357  * Adds an overlay on a tile.
3358  * - Arg 1: location.
3359  * - Arg 2: WML table.
3360  */
3362 {
3363  map_location loc = luaW_checklocation(L, 1);
3364  vconfig cfg = luaW_checkvconfig(L, 2);
3365  const vconfig &ssf = cfg.child("filter_team");
3366 
3367  std::string team_name;
3368  if (!ssf.null()) {
3369  const std::vector<int>& teams = side_filter(ssf, &game_state_).get_teams();
3370  std::vector<std::string> team_names;
3371  std::transform(teams.begin(), teams.end(), std::back_inserter(team_names),
3372  [&](int team) { return game_state_.get_disp_context().get_team(team).team_name(); });
3373  team_name = utils::join(team_names);
3374  } else {
3375  team_name = cfg["team_name"].str();
3376  }
3377 
3378  if (game_display_) {
3379  game_display_->add_overlay(loc, cfg["image"], cfg["halo"],
3380  team_name, cfg["name"], cfg["visible_in_fog"].to_bool(true), cfg["z_order"].to_double(0));
3381  }
3382  return 0;
3383 }
3384 
3385 /**
3386  * Removes an overlay from a tile.
3387  * - Arg 1: location.
3388  * - Arg 2: optional string.
3389  */
3391 {
3392  map_location loc = luaW_checklocation(L, 1);
3393  char const *m = lua_tostring(L, 2);
3394 
3395  if (m) {
3396  if (game_display_) {
3397  game_display_->remove_single_overlay(loc, m);
3398  }
3399  } else {
3400  if (game_display_) {
3401  game_display_->remove_overlay(loc);
3402  }
3403  }
3404  return 0;
3405 }
3406 
3408 {
3409  replay& recorder = play_controller_.get_replay();
3410  const int nargs = lua_gettop(L);
3411  if(nargs < 2 || nargs > 3) {
3412  return luaL_error(L, "Wrong number of arguments to ai.log_replay() - should be 2 or 3 arguments.");
3413  }
3414  const std::string key = nargs == 2 ? luaL_checkstring(L, 1) : luaL_checkstring(L, 2);
3415  config cfg;
3416  if(nargs == 2) {
3417  recorder.add_log_data(key, luaL_checkstring(L, 2));
3418  } else if(luaW_toconfig(L, 3, cfg)) {
3419  recorder.add_log_data(luaL_checkstring(L, 1), key, cfg);
3420  } else if(!lua_isstring(L, 3)) {
3421  return luaL_argerror(L, 3, "accepts only string or config");
3422  } else {
3423  recorder.add_log_data(luaL_checkstring(L, 1), key, luaL_checkstring(L, 3));
3424  }
3425  return 0;
3426 }
3427 
3428 /// Adding new events
3430 {
3431  vconfig cfg(luaW_checkvconfig(L, 1));
3432  game_events::manager & man = *game_state_.events_manager_;
3433 
3434  if (!cfg["delayed_variable_substitution"].to_bool(true)) {
3436  } else {
3437  man.add_event_handler(cfg.get_config());
3438  }
3439  return 0;
3440 }
3441 
3443 {
3444  game_state_.events_manager_->remove_event_handler(luaL_checkstring(L, 1));
3445  return 0;
3446 }
3447 
3449 {
3450  if (game_display_) {
3451  vconfig cfg(luaW_checkvconfig(L, 1));
3452 
3453  game_display_->adjust_color_overlay(cfg["red"], cfg["green"], cfg["blue"]);
3454  game_display_->invalidate_all();
3455  game_display_->draw(true,true);
3456  }
3457  return 0;
3458 }
3459 
3460 /**
3461  * Delays engine for a while.
3462  * - Arg 1: integer.
3463  * - Arg 2: boolean (optional).
3464  */
3466 {
3467  if(gamedata().phase() == game_data::PRELOAD || gamedata().phase() == game_data::PRESTART || gamedata().phase() == game_data::INITIAL) {
3468  //don't call play_slice if the game ui is not active yet.
3469  return 0;
3470  }
3471  events::command_disabler command_disabler;
3472  lua_Integer delay = luaL_checkinteger(L, 1);
3473  if(delay == 0) {
3474  play_controller_.play_slice(false);
3475  return 0;
3476  }
3477  if(luaW_toboolean(L, 2) && game_display_ && game_display_->turbo_speed() > 0) {
3478  delay /= game_display_->turbo_speed();
3479  }
3480  const unsigned final = SDL_GetTicks() + delay;
3481  do {
3482  play_controller_.play_slice(false);
3483  CVideo::delay(10);
3484  } while (static_cast<int>(final - SDL_GetTicks()) > 0);
3485  return 0;
3486 }
3487 
3489 {
3490  if (game_display_) {
3491  vconfig cfg(luaW_checkvconfig(L, 1));
3492 
3493  game_display &screen = *game_display_;
3494 
3495  terrain_label label(screen.labels(), cfg.get_config());
3496 
3497  screen.labels().set_label(label.location(), label.text(), label.creator(), label.team_name(), label.color(),
3498  label.visible_in_fog(), label.visible_in_shroud(), label.immutable(), label.category(), label.tooltip());
3499  }
3500  return 0;
3501 }
3502 
3504 {
3505  if (game_display_) {
3506  game_display & screen = *game_display_;
3507 
3508  vconfig cfg(luaW_checkvconfig(L, 1));
3509  bool clear_shroud(luaW_toboolean(L, 2));
3510 
3511  // We do this twice so any applicable redraws happen both before and after
3512  // any events caused by redrawing shroud are fired
3513  bool result = screen.maybe_rebuild();
3514  if (!result) {
3515  screen.invalidate_all();
3516  }
3517 
3518  if (clear_shroud) {
3519  side_filter filter(cfg, &game_state_);
3520  for (const int side : filter.get_teams()){
3521  actions::clear_shroud(side);
3522  }
3523  screen.recalculate_minimap();
3524  }
3525 
3526  result = screen.maybe_rebuild();
3527  if (!result) {
3528  screen.invalidate_all();
3529  }
3530 
3531  screen.draw(true,true);
3532  }
3533  return 0;
3534 }
3535 
3536 /**
3537  * Lua frontend to the modify_ai functionality
3538  * - Arg 1: config.
3539  */
3541 {
3542  config cfg;
3543  luaW_toconfig(L, 1, cfg);
3544  int side = cfg["side"];
3545  deprecated_message("wesnoth.modify_ai", DEP_LEVEL::PREEMPTIVE, {1, 15, 0}, "Use wesnoth.sides.add_ai_component, wesnoth.sides.delete_ai_component, or wesnoth.sides.change_ai_component.");
3547  return 0;
3548 }
3549 
3551 {
3552  bool exec = luaW_toboolean(L, -1);
3553  lua_pop(L, 1);
3554 
3555  lua_getfield(L, -1, "ca_ptr");
3556 
3557  ai::candidate_action *ca = static_cast<ai::candidate_action*>(lua_touserdata(L, -1));
3558  lua_pop(L, 2);
3559  if (exec) {
3560  ca->execute();
3561  return 0;
3562  }
3563  lua_pushinteger(L, ca->evaluate());
3564  return 1;
3565 }
3566 
3568 {
3569  lua_getfield(L, -1, "stg_ptr");
3570  ai::stage *stg = static_cast<ai::stage*>(lua_touserdata(L, -1));
3571  lua_pop(L, 2);
3572  stg->play_stage();
3573  return 0;
3574 }
3575 
3576 static void push_component(lua_State *L, ai::component* c, const std::string &ct = "")
3577 {
3578  lua_createtable(L, 0, 0); // Table for a component
3579 
3580  lua_pushstring(L, "name");
3581  lua_pushstring(L, c->get_name().c_str());
3582  lua_rawset(L, -3);
3583 
3584  lua_pushstring(L, "engine");
3585  lua_pushstring(L, c->get_engine().c_str());
3586  lua_rawset(L, -3);
3587 
3588  lua_pushstring(L, "id");
3589  lua_pushstring(L, c->get_id().c_str());
3590  lua_rawset(L, -3);
3591 
3592  if (ct == "candidate_action") {
3593  lua_pushstring(L, "ca_ptr");
3594  lua_pushlightuserdata(L, c);
3595  lua_rawset(L, -3);
3596 
3597  lua_pushstring(L, "exec");
3599  lua_rawset(L, -3);
3600  }
3601 
3602  if (ct == "stage") {
3603  lua_pushstring(L, "stg_ptr");
3604  lua_pushlightuserdata(L, c);
3605  lua_rawset(L, -3);
3606 
3607  lua_pushstring(L, "exec");
3609  lua_rawset(L, -3);
3610  }
3611 
3612 
3613  std::vector<std::string> c_types = c->get_children_types();
3614 
3615  for (std::vector<std::string>::const_iterator t = c_types.begin(); t != c_types.end(); ++t)
3616  {
3617  std::vector<ai::component*> children = c->get_children(*t);
3618  std::string type = *t;
3619  if (type == "aspect" || type == "goal" || type == "engine")
3620  {
3621  continue;
3622  }
3623 
3624  lua_pushstring(L, type.c_str());
3625  lua_createtable(L, 0, 0); // this table will be on top of the stack during recursive calls
3626 
3627  for (std::vector<ai::component*>::const_iterator i = children.begin(); i != children.end(); ++i)
3628  {
3629  lua_pushstring(L, (*i)->get_name().c_str());
3630  push_component(L, *i, type);
3631  lua_rawset(L, -3);
3632 
3633  //if (type == "candidate_action")
3634  //{
3635  // ai::candidate_action *ca = dynamic_cast<ai::candidate_action*>(*i);
3636  // ca->execute();
3637  //}
3638  }
3639 
3640  lua_rawset(L, -3); // setting the child table
3641  }
3642 
3643 
3644 }
3645 
3646 /**
3647  * Debug access to the ai tables
3648  * - Arg 1: int
3649  * - Ret 1: ai table
3650  */
3651 static int intf_debug_ai(lua_State *L)
3652 {
3653  if (!game_config::debug) { // This function works in debug mode only
3654  return 0;
3655  }
3656  int side;
3657  if(team* t = luaW_toteam(L, 1)) {
3658  side = t->side();
3659  } else {
3660  side = luaL_checkinteger(L, 1);
3661  }
3662  lua_pop(L, 1);
3663 
3665 
3666  // Bad, but works
3667  std::vector<ai::component*> engines = c->get_children("engine");
3668  ai::engine_lua* lua_engine = nullptr;
3669  for (std::vector<ai::component*>::const_iterator i = engines.begin(); i != engines.end(); ++i)
3670  {
3671  if ((*i)->get_name() == "lua")
3672  {
3673  lua_engine = dynamic_cast<ai::engine_lua *>(*i);
3674  }
3675  }
3676 
3677  // Better way, but doesn't work
3678  //ai::component* e = ai::manager::get_singleton().get_active_ai_holder_for_side_dbg(side).get_component(c, "engine[lua]");
3679  //ai::engine_lua* lua_engine = dynamic_cast<ai::engine_lua *>(e);
3680 
3681  if (lua_engine == nullptr)
3682  {
3683  //no lua engine is defined for this side.
3684  //so set up a dummy engine
3685 
3686  ai::ai_composite * ai_ptr = dynamic_cast<ai::ai_composite *>(c);
3687 
3688  assert(ai_ptr);
3689 
3690  ai::ai_context& ai_context = ai_ptr->get_ai_context();
3692 
3693  lua_engine = new ai::engine_lua(ai_context, cfg);
3694  LOG_LUA << "Created new dummy lua-engine for debug_ai(). \n";
3695 
3696  //and add the dummy engine as a component
3697  //to the manager, so we could use it later
3698  cfg.add_child("engine", lua_engine->to_config());
3699  ai::component_manager::add_component(c, "engine[]", cfg);
3700  }
3701 
3702  lua_engine->push_ai_table(); // stack: [-1: ai_context]
3703 
3704  lua_pushstring(L, "components");
3705  push_component(L, c); // stack: [-1: component tree; -2: ai context]
3706  lua_rawset(L, -3);
3707 
3708  return 1;
3709 }
3710 
3711 /// Allow undo sets the flag saying whether the event has mutated the game to false.
3713 {
3714  bool allow;
3715  t_string reason;
3716  // The extra iststring is required to prevent totstring from converting a bool value
3717  if(luaW_iststring(L, 1) && luaW_totstring(L, 1, reason)) {
3718  allow = false;
3719  } else {
3720  allow = luaW_toboolean(L, 1);
3721  luaW_totstring(L, 2, reason);
3722  }
3723  gamedata().set_allow_end_turn(allow, reason);
3724  return 0;
3725 }
3726 
3727 /// Allow undo sets the flag saying whether the event has mutated the game to false.
3729 {
3730  if(lua_isboolean(L, 1)) {
3731  play_controller_.pump().set_undo_disabled(!luaW_toboolean(L, 1));
3732  }
3733  else {
3734  play_controller_.pump().set_undo_disabled(false);
3735  }
3736  return 0;
3737 }
3738 
3740 {
3741  play_controller_.pump().set_action_canceled();
3742  return 0;
3743 }
3744 
3745 /// Adding new time_areas dynamically with Standard Location Filters.
3747 {
3748  log_scope("time_area");
3749 
3750  vconfig cfg(luaW_checkvconfig(L, 1));
3751  const std::string id = cfg["id"];
3752 
3753  std::set<map_location> locs;
3754  const terrain_filter filter(cfg, &game_state_);
3755  filter.get_locations(locs, true);
3756  config parsed_cfg = cfg.get_parsed_config();
3757  tod_man().add_time_area(id, locs, parsed_cfg);
3758  LOG_LUA << "Lua inserted time_area '" << id << "'\n";
3759  return 0;
3760 }
3761 
3762 /// Removing new time_areas dynamically with Standard Location Filters.
3764 {
3765  log_scope("remove_time_area");
3766 
3767  const char * id = luaL_checkstring(L, 1);
3768  tod_man().remove_time_area(id);
3769  LOG_LUA << "Lua removed time_area '" << id << "'\n";
3770 
3771  return 0;
3772 }
3773 
3774 /// Replacing the current time of day schedule.
3776 {
3777  vconfig cfg = luaW_checkvconfig(L, 1);
3778 
3779  if(cfg.get_children("time").empty()) {
3780  ERR_LUA << "attempted to to replace ToD schedule with empty schedule" << std::endl;
3781  } else {
3782  tod_man().replace_schedule(cfg.get_parsed_config());
3783  if (game_display_) {
3784  game_display_->new_turn();
3785  }
3786  LOG_LUA << "replaced ToD schedule\n";
3787  }
3788  return 0;
3789 }
3790 
3792 {
3793  if(!game_display_) {
3794  return 0;
3795  }
3796  std::string area_id;
3797  std::size_t area_i = 0;
3798  if (lua_isstring(L, 2)) {
3799  area_id = lua_tostring(L, 1);
3800  std::vector<std::string> area_ids = tod_man().get_area_ids();
3801  area_i = std::distance(area_ids.begin(), std::find(area_ids.begin(), area_ids.end(), area_id));
3802  if(area_i >= area_ids.size()) {
3803  return luaL_argerror(L, 1, "invalid time area ID");
3804  }
3805  }
3806  int is_num = false;
3807  int new_time = lua_tonumberx(L, 1, &is_num) - 1;
3808  const std::vector<time_of_day>& times = area_id.empty()
3809  ? tod_man().times()
3810  : tod_man().times(area_i);
3811  int num_times = times.size();
3812  if(!is_num) {
3813  std::string time_id = luaL_checkstring(L, 1);
3814  new_time = 0;
3815  for(const time_of_day& time : times) {
3816  if(time_id == time.id) {
3817  break;
3818  }
3819  new_time++;
3820  }
3821  if(new_time >= num_times) {
3822  return luaL_argerror(L, 1, "invalid time of day ID");
3823  }
3824  }
3825 
3826  if(new_time == 0 && num_times == 0) {
3827  //ignore this case, because we don't want code like set_current_time(get_current_time()) to fail if num_times is 0.
3828  return 0;
3829  }
3830  if(new_time < 0 || new_time >= num_times) {
3831  return luaL_argerror(L, 1, "invalid time of day index");
3832  }
3833 
3834  if(area_id.empty()) {
3835  tod_man().set_current_time(new_time);
3836  } else {
3837  tod_man().set_current_time(new_time, area_i);
3838  }
3839  return 0;
3840 }
3841 
3843 {
3844  int x = luaL_checkinteger(L, 1), y = luaL_checkinteger(L, 2);
3845 
3846  if (game_display_) {
3847  game_display_->scroll(x, y, true);
3848  game_display_->draw(true, true);
3849  }
3850 
3851  return 0;
3852 }
3853 
3854 namespace {
3855  struct lua_report_generator : reports::generator
3856  {
3857  lua_State *mState;
3858  std::string name;
3859  lua_report_generator(lua_State *L, const std::string &n)
3860  : mState(L), name(n) {}
3861  virtual config generate(reports::context & rc);
3862  };
3863 
3864  config lua_report_generator::generate(reports::context & /*rc*/)
3865  {
3866  lua_State *L = mState;
3867  config cfg;
3868  if (!luaW_getglobal(L, "wesnoth", "theme_items", name))
3869  return cfg;
3870  if (!luaW_pcall(L, 0, 1)) return cfg;
3871  luaW_toconfig(L, -1, cfg);
3872  lua_pop(L, 1);
3873  return cfg;
3874  }
3875 }//unnamed namespace for lua_report_generator
3876 
3877 /**
3878  * Executes its upvalue as a theme item generator.
3879  */
3881 {
3882  reports::context temp_context = reports::context(board(), *game_display_, tod_man(), play_controller_.get_whiteboard(), play_controller_.get_mouse_handler_base());
3883  luaW_pushconfig(L, reports_.generate_report(m.c_str(), temp_context , true));
3884  return 1;
3885 }
3886 
3887 /**
3888  * Creates a field of the theme_items table and returns it (__index metamethod).
3889  */
3891 {
3892  char const *m = luaL_checkstring(L, 2);
3893  lua_cpp::push_closure(L, std::bind(&game_lua_kernel::impl_theme_item, this, _1, std::string(m)), 0);
3894  lua_pushvalue(L, 2);
3895  lua_pushvalue(L, -2);
3896  lua_rawset(L, 1);
3897  reports_.register_generator(m, new lua_report_generator(L, m));
3898  return 1;
3899 }
3900 
3901 /**
3902  * Sets a field of the theme_items table (__newindex metamethod).
3903  */
3905 {
3906  char const *m = luaL_checkstring(L, 2);
3907  lua_pushvalue(L, 2);
3908  lua_pushvalue(L, 3);
3909  lua_rawset(L, 1);
3910  reports_.register_generator(m, new lua_report_generator(L, m));
3911  return 0;
3912 }
3913 
3914 /**
3915  * Gets all the WML variables currently set.
3916  * - Ret 1: WML table
3917  */
3919  luaW_pushconfig(L, gamedata().get_variables());
3920  return 1;
3921 }
3922 
3923 /**
3924  * Teeleports a unit to a location.
3925  * Arg 1: unit
3926  * Arg 2: target location
3927  * Arg 3: bool (ignore_passability)
3928  * Arg 4: bool (clear_shroud)
3929  * Arg 5: bool (animate)
3930  */
3932 {
3933  events::command_disabler command_disabler;
3934  unit_ptr u = luaW_checkunit_ptr(L, 1, true);
3935  map_location dst = luaW_checklocation(L, 2);
3936  bool check_passability = !luaW_toboolean(L, 3);
3937  bool clear_shroud = luaW_toboolean(L, 4);
3938  bool animate = luaW_toboolean(L, 5);
3939 
3940  if (dst == u->get_location() || !map().on_board(dst)) {
3941  return 0;
3942  }
3943  const map_location vacant_dst = find_vacant_tile(dst, pathfind::VACANT_ANY, check_passability ? u.get() : nullptr);
3944  if (!map().on_board(vacant_dst)) {
3945  return 0;
3946  }
3947  // Clear the destination hex before the move (so the animation can be seen).
3948  actions::shroud_clearer clearer;
3949  if ( clear_shroud ) {
3950  clearer.clear_dest(vacant_dst, *u);
3951  }
3952 
3953  map_location src_loc = u->get_location();
3954 
3955  std::vector<map_location> teleport_path;
3956  teleport_path.push_back(src_loc);
3957  teleport_path.push_back(vacant_dst);
3958  unit_display::move_unit(teleport_path, u, animate);
3959 
3960  units().move(src_loc, vacant_dst);
3962 
3963  u = &*units().find(vacant_dst);
3964  u->anim_comp().set_standing();
3965 
3966  if ( clear_shroud ) {
3967  // Now that the unit is visibly in position, clear the shroud.
3968  clearer.clear_unit(vacant_dst, *u);
3969  }
3970 
3971  if (map().is_village(vacant_dst)) {
3972  actions::get_village(vacant_dst, u->side());
3973  }
3974 
3975  game_display_->invalidate_unit_after_move(src_loc, vacant_dst);
3976  game_display_->draw();
3977 
3978  // Sighted events.
3979  clearer.fire_events();
3980  return 0;
3981 }
3982 
3983 /**
3984  * Removes a sound source by its ID
3985  * Arg 1: sound source ID
3986  */
3988 {
3989  soundsource::manager* man = play_controller_.get_soundsource_man();
3990  std::string id = luaL_checkstring(L, 1);
3991  man->remove(id);
3992  return 0;
3993 }
3994 
3995 /**
3996  * Add a new sound source
3997  * Arg 1: Table containing keyword arguments
3998  */
4000 {
4001  soundsource::manager* man = play_controller_.get_soundsource_man();
4002  config cfg = luaW_checkconfig(L, 1);
4003  try {
4004  soundsource::sourcespec spec(cfg);
4005  man->add(spec);
4006  man->update();
4007  } catch (const bad_lexical_cast &) {
4008  ERR_LUA << "Error when parsing sound_source config: invalid parameter." << std::endl;
4009  ERR_LUA << "sound_source config was: " << cfg.debug() << std::endl;
4010  ERR_LUA << "Skipping this sound source..." << std::endl;
4011  }
4012  return 0;
4013 }
4014 
4015 /**
4016  * Get an existing sound source
4017  * Arg 1: The sound source ID
4018  * Return: Config of sound source info, or nil if it didn't exist
4019  * This is a copy of the sound source info, so you need to call
4020  * add_sound_source again after changing it.
4021  */
4023 {
4024  soundsource::manager* man = play_controller_.get_soundsource_man();
4025  std::string id = luaL_checkstring(L, 1);
4026  config cfg = man->get(id);
4027  if(cfg.empty()) {
4028  return 0;
4029  }
4030  // Sound sources do not know their own string ID
4031  // Thus, we need to add this manually
4032  cfg["id"] = id;
4033  luaW_pushconfig(L, cfg);
4034  return 1;
4035 }
4036 
4037 /**
4038  * Logs a message
4039  * Arg 1: (optional) Logger; "wml" for WML errors or deprecations
4040  * Arg 2: Message
4041  * Arg 3: Whether to print to chat (always true if arg 1 is "wml")
4042  */
4044 {
4045  const std::string& logger = lua_isstring(L, 2) ? luaL_checkstring(L, 1) : "";
4046  const std::string& msg = lua_isstring(L, 2) ? luaL_checkstring(L, 2) : luaL_checkstring(L, 1);
4047 
4048  if(logger == "wml" || logger == "WML") {
4049  lg::wml_error() << msg << '\n';
4050  } else {
4051  bool in_chat = luaW_toboolean(L, -1);
4052  game_state_.events_manager_->pump().put_wml_message(logger,msg,in_chat);
4053  }
4054  return 0;
4055 }
4056 
4058 {
4059  int side = luaL_checknumber(L, 1);
4060  map_location loc = luaW_checklocation(L, 2);
4061  if(side < 1 || static_cast<std::size_t>(side) > teams().size()) {
4062  std::string error = "side " + std::to_string(side) + " does not exist";
4063  return luaL_argerror(L, 1, error.c_str());
4064  }
4065 
4066  team& t = board().get_team(side);
4067  lua_pushboolean(L, fog ? t.fogged(loc) : t.shrouded(loc));
4068  return 1;
4069 }
4070 
4071 /**
4072  * Implements the lifting and resetting of fog via WML.
4073  * Keeping affect_normal_fog as false causes only the fog override to be affected.
4074  * Otherwise, fog lifting will be implemented similar to normal sight (cannot be
4075  * individually reset and ends at the end of the turn), and fog resetting will, in
4076  * addition to removing overrides, extend the specified teams' normal fog to all
4077  * hexes.
4078  *
4079  * Arg 1: (optional) Side number, or list of side numbers
4080  * Arg 2: List of locations; each is a two-element array or a table with x and y keys
4081  * Arg 3: (optional) boolean
4082  */
4084 {
4085  bool affect_normal_fog = false;
4086  if(lua_isboolean(L, -1)) {
4087  affect_normal_fog = luaW_toboolean(L, -1);
4088  }
4089  std::set<int> sides;
4090  if(lua_isnumber(L, 1)) {
4091  sides.insert(lua_tonumber(L, 1));
4092  } else if(lua_istable(L, 1) && lua_istable(L, 2)) {
4093  const auto& v = lua_check<std::vector<int>>(L, 1);
4094  sides.insert(v.begin(), v.end());
4095  } else {
4096  for(const team& t : teams()) {
4097  sides.insert(t.side()+1);
4098  }
4099  }
4100  const auto& v_locs = lua_check<std::vector<map_location>>(L, lua_istable(L, 2) ? 2 : 1);
4101  std::set<map_location> locs(v_locs.begin(), v_locs.end());
4102 
4103  for(const int &side_num : sides) {
4104  if(side_num < 1 || static_cast<std::size_t>(side_num) > teams().size()) {
4105  continue;
4106  }
4107  team &t = board().get_team(side_num);
4108  if(!clear) {
4109  // Extend fog.
4110  t.remove_fog_override(locs);
4111  if(affect_normal_fog) {
4112  t.refog();
4113  }
4114  } else if(!affect_normal_fog) {
4115  // Force the locations clear of fog.
4116  t.add_fog_override(locs);
4117  } else {
4118  // Simply clear fog from the locations.
4119  for(const map_location &hex : locs) {
4120  t.clear_fog(hex);
4121  }
4122  }
4123  }
4124 
4125  // Flag a screen update.
4126  game_display_->recalculate_minimap();
4127  game_display_->invalidate_all();
4128  return 0;
4129 }
4130 
4131 // Invokes a synced command
4133 {
4134  const std::string name = luaL_checkstring(L, 1);
4135  auto it = synced_command::registry().find(name);
4136  config cmd;
4137  if(it == synced_command::registry().end()) {
4138  // Custom command
4139  if(!luaW_getglobal(L, "wesnoth", "custom_synced_commands", name)) {
4140  return luaL_argerror(L, 1, "Unknown synced command");
4141  }
4142  config& cmd_tag = cmd.child_or_add("custom_command");
4143  cmd_tag["name"] = name;
4144  if(!lua_isnoneornil(L, 2)) {
4145  cmd_tag.add_child("data", luaW_checkconfig(L, 2));
4146  }
4147  } else {
4148  // Built-in command
4149  cmd.add_child(name, luaW_checkconfig(L, 2));
4150  }
4151  // Now just forward to the WML action.
4152  luaW_getglobal(L, "wesnoth", "wml_actions", "do_command");
4153  luaW_pushconfig(L, cmd);
4154  luaW_pcall(L, 1, 0);
4155  return 0;
4156 }
4157 
4158 // END CALLBACK IMPLEMENTATION
4159 
4161  return game_state_.board_;
4162 }
4163 
4165  return game_state_.board_.units_;
4166 }
4167 
4168 std::vector<team> & game_lua_kernel::teams() {
4169  return game_state_.board_.teams_;
4170 }
4171 
4173  return game_state_.board_.map();
4174 }
4175 
4177  return game_state_.gamedata_;
4178 }
4179 
4181  return game_state_.tod_manager_;
4182 }
4183 
4185  return *queued_events_.top();
4186 }
4187 
4188 
4190  : lua_kernel_base()
4191  , game_display_(nullptr)
4192  , game_state_(gs)
4193  , play_controller_(pc)
4194  , reports_(reports_object)
4195  , level_lua_()
4196  , queued_events_()
4197  , map_locked_(0)
4198 {
4199  static game_events::queued_event default_queued_event("_from_lua", "", map_location(), map_location(), config());
4200  queued_events_.push(&default_queued_event);
4201 
4202  lua_State *L = mState;
4203 
4204  cmd_log_ << "Registering game-specific wesnoth lib functions...\n";
4205 
4206  // Put some callback functions in the scripting environment.
4207  static luaL_Reg const callbacks[] {
4208  { "add_known_unit", &intf_add_known_unit },
4209  { "create_animator", &dispatch<&game_lua_kernel::intf_create_animator> },
4210  { "eval_conditional", &intf_eval_conditional },
4211  { "get_era", &intf_get_era },
4212  { "get_resource", &intf_get_resource },
4213  { "get_traits", &intf_get_traits },
4214  { "get_viewing_side", &intf_get_viewing_side },
4215  { "invoke_synced_command", &intf_invoke_synced_command },
4216  { "modify_ai", &intf_modify_ai_old },
4217  { "set_music", &intf_set_music },
4218  { "sound_volume", &intf_sound_volume },
4219  { "unsynced", &intf_do_unsynced },
4220  { "add_event_handler", &dispatch<&game_lua_kernel::intf_add_event > },
4221  { "add_fog", &dispatch2<&game_lua_kernel::intf_toggle_fog, false > },
4222  { "add_time_area", &dispatch<&game_lua_kernel::intf_add_time_area > },
4223  { "add_sound_source", &dispatch<&game_lua_kernel::intf_add_sound_source > },
4224  { "allow_end_turn", &dispatch<&game_lua_kernel::intf_allow_end_turn > },
4225  { "allow_undo", &dispatch<&game_lua_kernel::intf_allow_undo > },
4226  { "cancel_action", &dispatch<&game_lua_kernel::intf_cancel_action > },
4227  { "clear_messages", &dispatch<&game_lua_kernel::intf_clear_messages > },
4228  { "end_turn", &dispatch<&game_lua_kernel::intf_end_turn > },
4229  { "end_level", &dispatch<&game_lua_kernel::intf_end_level > },
4230  { "find_cost_map", &dispatch<&game_lua_kernel::intf_find_cost_map > },
4231  { "find_path", &dispatch<&game_lua_kernel::intf_find_path > },
4232  { "find_reach", &dispatch<&game_lua_kernel::intf_find_reach > },
4233  { "find_vacant_tile", &dispatch<&game_lua_kernel::intf_find_vacant_tile > },
4234  { "fire_event", &dispatch2<&game_lua_kernel::intf_fire_event, false > },
4235  { "fire_event_by_id", &dispatch2<&game_lua_kernel::intf_fire_event, true > },
4236  { "get_all_vars", &dispatch<&game_lua_kernel::intf_get_all_vars > },
4237  { "get_end_level_data", &dispatch<&game_lua_kernel::intf_get_end_level_data > },
4238  { "get_locations", &dispatch<&game_lua_kernel::intf_get_locations > },
4239  { "get_map_size", &dispatch<&game_lua_kernel::intf_get_map_size > },
4240  { "get_sound_source", &dispatch<&game_lua_kernel::intf_get_sound_source > },
4241  { "get_terrain", &dispatch<&game_lua_kernel::intf_get_terrain > },
4242  { "get_terrain_info", &dispatch<&game_lua_kernel::intf_get_terrain_info > },
4243  { "get_time_of_day", &dispatch<&game_lua_kernel::intf_get_time_of_day > },
4244  { "get_max_liminal_bonus", &dispatch<&game_lua_kernel::intf_get_max_liminal_bonus > },
4245  { "get_variable", &dispatch<&game_lua_kernel::intf_get_variable > },
4246  { "get_villages", &dispatch<&game_lua_kernel::intf_get_villages > },
4247  { "get_village_owner", &dispatch<&game_lua_kernel::intf_get_village_owner > },
4248  { "label", &dispatch<&game_lua_kernel::intf_label > },
4249  { "log_replay", &dispatch<&game_lua_kernel::intf_log_replay > },
4250  { "log", &dispatch<&game_lua_kernel::intf_log > },
4251  { "match_location", &dispatch<&game_lua_kernel::intf_match_location > },
4252  { "message", &dispatch<&game_lua_kernel::intf_message > },
4253  { "open_help", &dispatch<&game_lua_kernel::intf_open_help > },
4254  { "play_sound", &dispatch<&game_lua_kernel::intf_play_sound > },
4255  { "print", &dispatch<&game_lua_kernel::intf_print > },
4256  { "redraw", &dispatch<&game_lua_kernel::intf_redraw > },
4257  { "remove_event_handler", &dispatch<&game_lua_kernel::intf_remove_event > },
4258  { "remove_fog", &dispatch2<&game_lua_kernel::intf_toggle_fog, true > },
4259  { "remove_time_area", &dispatch<&game_lua_kernel::intf_remove_time_area > },
4260  { "remove_sound_source", &dispatch<&game_lua_kernel::intf_remove_sound_source > },
4261  { "replace_schedule", &dispatch<&game_lua_kernel::intf_replace_schedule > },
4262  { "select_hex", &dispatch<&game_lua_kernel::intf_select_hex > },
4263  { "set_time_of_day", &dispatch<&game_lua_kernel::intf_set_time_of_day > },
4264  { "is_fogged", &dispatch2<&game_lua_kernel::intf_get_fog_or_shroud, true > },
4265  { "is_shrouded", &dispatch2<&game_lua_kernel::intf_get_fog_or_shroud, false > },
4266  { "set_end_campaign_credits", &dispatch<&game_lua_kernel::intf_set_end_campaign_credits > },
4267  { "set_end_campaign_text", &dispatch<&game_lua_kernel::intf_set_end_campaign_text > },
4268  { "create_side", &dispatch<&game_lua_kernel::intf_create_side > },
4269  { "set_next_scenario", &dispatch<&game_lua_kernel::intf_set_next_scenario > },
4270  { "set_terrain", &dispatch<&game_lua_kernel::intf_set_terrain > },
4271  { "set_variable", &dispatch<&game_lua_kernel::intf_set_variable > },
4272  { "set_village_owner", &dispatch<&game_lua_kernel::intf_set_village_owner > },
4273  { "simulate_combat", &dispatch<&game_lua_kernel::intf_simulate_combat > },
4274  { "synchronize_choice", &intf_synchronize_choice },
4275  { "synchronize_choices", &intf_synchronize_choices },
4276  { "terrain_mask", &dispatch<&game_lua_kernel::intf_terrain_mask > },
4277  { "teleport", &dispatch<&game_lua_kernel::intf_teleport > },
4278  { "place_shroud", &dispatch2<&game_lua_kernel::intf_shroud_op, true > },
4279  { "remove_shroud", &dispatch2<&game_lua_kernel::intf_shroud_op, false > },
4280  { nullptr, nullptr }
4281  };lua_getglobal(L, "wesnoth");
4282  if (!lua_istable(L,-1)) {
4283  lua_newtable(L);
4284  }
4285  luaL_setfuncs(L, callbacks, 0);
4286 
4287  if(play_controller_.get_classification().campaign_type == game_classification::CAMPAIGN_TYPE::TEST) {
4288  static luaL_Reg const test_callbacks[] {
4289  { "fire_wml_menu_item", &dispatch<&game_lua_kernel::intf_fire_wml_menu_item > },
4290  { nullptr, nullptr }
4291  };
4292  luaL_setfuncs(L, test_callbacks , 0);
4293  }
4294 
4295  lua_setglobal(L, "wesnoth");
4296 
4297  lua_getglobal(L, "gui");
4298  lua_pushcfunction(L, &dispatch<&game_lua_kernel::intf_gamestate_inspector>);
4299  lua_setfield(L, -2, "show_inspector");
4300  lua_pop(L, 1);
4301 
4302  // Create the getside metatable.
4304 
4305  // Create the gettype metatable.
4307 
4308  //Create the getrace metatable
4310 
4311  //Create the unit metatables
4314 
4315  // Create the vconfig metatable.
4317 
4318  // Create the unit_types table
4320 
4321  // Create the ai elements table.
4322  cmd_log_ << "Adding ai elements table...\n";
4323 
4325 
4326  // Create the current variable with its metatable.
4327  cmd_log_ << "Adding wesnoth current table...\n";
4328 
4329  lua_getglobal(L, "wesnoth");
4330  lua_newuserdata(L, 0);
4331  lua_createtable(L, 0, 2);
4332  lua_pushcfunction(L, &dispatch<&game_lua_kernel::impl_current_get>);
4333  lua_setfield(L, -2, "__index");
4334  lua_pushstring(L, "current config");
4335  lua_setfield(L, -2, "__metatable");
4336  lua_setmetatable(L, -2);
4337  lua_setfield(L, -2, "current");
4338  lua_pop(L, 1);
4339 
4340  // Add tovconfig to the WML module
4341  lua_getglobal(L, "wml");
4343  lua_setfield(L, -2, "tovconfig");
4344  lua_pop(L, 1);
4345 
4346  // Create the units module
4347  cmd_log_ << "Adding units module...\n";
4348  static luaL_Reg const unit_callbacks[] {
4349  {"advance", &intf_advance_unit},
4350  {"clone", &intf_copy_unit},
4351  {"erase", &dispatch<&game_lua_kernel::intf_erase_unit>},
4352  {"extract", &dispatch<&game_lua_kernel::intf_extract_unit>},
4353  {"matches", &dispatch<&game_lua_kernel::intf_match_unit>},
4354  {"select", &dispatch<&game_lua_kernel::intf_select_unit>},
4355  {"to_map", &dispatch<&game_lua_kernel::intf_put_unit>},
4356  {"to_recall", &dispatch<&game_lua_kernel::intf_put_recall_unit>},
4357  {"transform", &intf_transform_unit},
4358 
4359  {"ability", &dispatch<&game_lua_kernel::intf_unit_ability>},
4360  {"defense_on", &intf_unit_defense},
4361  {"jamming_on", &intf_unit_jamming_cost},
4362  {"movement_on", &intf_unit_movement_cost},
4363  {"resistance_against", intf_unit_resistance},
4364  {"vision_on", &intf_unit_vision_cost},
4365 
4366  {"add_modification", &intf_add_modification},
4367  {"remove_modifications", &intf_remove_modifications},
4368  // Static functions
4369  {"create", &intf_create_unit},
4370  {"find_on_map", &dispatch<&game_lua_kernel::intf_get_units>},
4371  {"find_on_recall", &dispatch<&game_lua_kernel::intf_get_recall_units>},
4372  {"get", &dispatch<&game_lua_kernel::intf_get_unit>},
4373  {"get_hovered", &dispatch<&game_lua_kernel::intf_get_displayed_unit>},
4374  { nullptr, nullptr }
4375  };
4376  lua_getglobal(L, "wesnoth");
4377  lua_newtable(L);
4378  luaL_setfuncs(L, unit_callbacks, 0);
4379  lua_setfield(L, -2, "units");
4380  lua_pop(L, 1);
4381 
4382  // Create sides module
4383  cmd_log_ << "Adding sides module...\n";
4384  static luaL_Reg const side_callbacks[] {
4385  { "is_enemy", &dispatch<&game_lua_kernel::intf_is_enemy> },
4386  { "matches", &dispatch<&game_lua_kernel::intf_match_side> },
4387  { "set_id", &dispatch<&game_lua_kernel::intf_set_side_id> },
4388  { "append_ai", &intf_append_ai },
4389  { "debug_ai", &intf_debug_ai },
4390  { "switch_ai", &intf_switch_ai },
4391  // Static functions
4392  { "find", &dispatch<&game_lua_kernel::intf_get_sides> },
4393  { "get", &dispatch<&game_lua_kernel::intf_get_side> },
4394  { nullptr, nullptr }
4395  };
4396  std::vector<lua_cpp::Reg> const cpp_side_callbacks {
4397  {"add_ai_component", std::bind(intf_modify_ai, _1, "add")},
4398  {"delete_ai_component", std::bind(intf_modify_ai, _1, "delete")},
4399  {"change_ai_component", std::bind(intf_modify_ai, _1, "change")},
4400  {nullptr, nullptr}
4401  };
4402 
4403  lua_getglobal(L, "wesnoth");
4404  lua_newtable(L);
4405  luaL_setfuncs(L, side_callbacks, 0);
4406  lua_cpp::set_functions(L, cpp_side_callbacks);
4407  lua_setfield(L, -2, "sides");
4408  lua_pop(L, 1);
4409 
4410  // Create the interface module
4411  cmd_log_ << "Adding interface module...\n";
4412  static luaL_Reg const intf_callbacks[] {
4413  {"add_hex_overlay", &dispatch<&game_lua_kernel::intf_add_tile_overlay>},
4414  {"remove_hex_overlay", &dispatch<&game_lua_kernel::intf_remove_tile_overlay>},
4415  {"color_adjust", &dispatch<&game_lua_kernel::intf_color_adjust>},
4416  {"delay", &dispatch<&game_lua_kernel::intf_delay>},
4417  {"deselect_hex", &dispatch<&game_lua_kernel::intf_deselect_hex>},
4418  {"highlight_hex", &dispatch<&game_lua_kernel::intf_highlight_hex>},
4419  {"float_label", &dispatch<&game_lua_kernel::intf_float_label>},
4420  {"get_displayed_unit", &dispatch<&game_lua_kernel::intf_get_displayed_unit>},
4421  {"get_hovered_hex", &dispatch<&game_lua_kernel::intf_get_mouseover_tile>},
4422  {"get_selected_hex", &dispatch<&game_lua_kernel::intf_get_selected_tile>},
4423  {"lock", &dispatch<&game_lua_kernel::intf_lock_view>},
4424  {"is_locked", &dispatch<&game_lua_kernel::intf_view_locked>},
4425  {"scroll", &dispatch<&game_lua_kernel::intf_scroll>},
4426  {"scroll_to_hex", &dispatch<&game_lua_kernel::intf_scroll_to_tile>},
4427  {"skip_messages", &dispatch<&game_lua_kernel::intf_skip_messages>},
4428  {"is_skipping_messages", &dispatch<&game_lua_kernel::intf_is_skipping_messages>},
4429  {"zoom", &dispatch<&game_lua_kernel::intf_zoom>},
4430  {"clear_menu_item", &dispatch<&game_lua_kernel::intf_clear_menu_item>},
4431  {"set_menu_item", &dispatch<&game_lua_kernel::intf_set_menu_item>},
4432  { nullptr, nullptr }
4433  };
4434  lua_getglobal(L, "wesnoth");
4435  lua_newtable(L);
4436  luaL_setfuncs(L, intf_callbacks, 0);
4437  lua_setfield(L, -2, "interface");
4438  lua_pop(L, 1);
4439 
4440  // Create the playlist table with its metatable
4442 
4443  // Create the wml_actions table.
4444  cmd_log_ << "Adding wml_actions table...\n";
4445 
4446  lua_getglobal(L, "wesnoth");
4447  lua_newtable(L);
4448  lua_setfield(L, -2, "wml_actions");
4449  lua_pop(L, 1);
4450 
4451  // Create the wml_conditionals table.
4452  cmd_log_ << "Adding wml_conditionals table...\n";
4453 
4454  lua_getglobal(L, "wesnoth");
4455  lua_newtable(L);
4456  lua_setfield(L, -2, "wml_conditionals");
4457  lua_pop(L, 1);
4461 
4462  // Create the effects table.
4463  cmd_log_ << "Adding effects table...\n";
4464 
4465  lua_getglobal(L, "wesnoth");
4466  lua_newtable(L);
4467  lua_setfield(L, -2, "effects");
4468  lua_pop(L, 1);
4469 
4470  // Create the custom_synced_commands table.
4471  cmd_log_ << "Adding custom_synced_commands table...\n";
4472 
4473  lua_getglobal(L, "wesnoth");
4474  lua_newtable(L);
4475  lua_setfield(L, -2, "custom_synced_commands");
4476  lua_pop(L, 1);
4477 
4478  // Create the game_events table.
4479  cmd_log_ << "Adding game_events table...\n";
4480 
4481  lua_getglobal(L, "wesnoth");
4482  lua_newtable(L);
4483  lua_setfield(L, -2, "game_events");
4485  lua_setfield(L, -2, "special_locations");
4486  lua_pop(L, 1);
4487 
4488  // Create the theme_items table.
4489  cmd_log_ << "Adding game_display table...\n";
4490 
4491  luaW_getglobal(L, "wesnoth", "interface");
4492  lua_newtable(L);
4493  lua_createtable(L, 0, 2);
4494  lua_pushcfunction(L, &dispatch<&game_lua_kernel::impl_theme_items_get>);
4495  lua_setfield(L, -2, "__index");
4496  lua_pushcfunction(L, &dispatch<&game_lua_kernel::impl_theme_items_set>);
4497  lua_setfield(L, -2, "__newindex");
4498  lua_setmetatable(L, -2);
4499  lua_setfield(L, -2, "game_display");
4500  lua_pop(L, 1);
4501 
4502  lua_settop(L, 0);
4503 
4504  for(const auto& handler : game_events::wml_action::registry())
4505  {
4506  set_wml_action(handler.first, handler.second);
4507  }
4508  luaW_getglobal(L, "wesnoth", "effects");
4509  for(const std::string& effect : unit::builtin_effects) {
4510  lua_pushstring(L, effect.c_str());
4512  lua_rawset(L, -3);
4513  }
4514  lua_settop(L, 0);
4515 }
4516 
4518 {
4519  lua_State *L = mState;
4520  assert(level_lua_.empty());
4521  level_lua_.append_children(level, "lua");
4522 
4523  //Create the races table.
4524  cmd_log_ << "Adding races table...\n";
4525 
4526  lua_settop(L, 0);
4527  lua_getglobal(L, "wesnoth");
4528  luaW_pushracetable(L);
4529  lua_setfield(L, -2, "races");
4530  lua_pop(L, 1);
4531 
4532  // Execute the preload scripts.
4533  cmd_log_ << "Running preload scripts...\n";
4534 
4535  game_config::load_config(game_lua_kernel::preload_config);
4536  for (const config &cfg : game_lua_kernel::preload_scripts) {
4537  run_lua_tag(cfg);
4538  }
4539  for (const config &cfg : level_lua_.child_range("lua")) {
4540  run_lua_tag(cfg);
4541  }
4542 }
4543 
4545  game_display_ = gd;
4546 }
4547 
4548 /// These are the child tags of [scenario] (and the like) that are handled
4549 /// elsewhere (in the C++ code).
4550 /// Any child tags not in this list will be passed to Lua's on_load event.
4551 static const std::array<std::string, 24> handled_file_tags {{
4552  "color_palette",
4553  "color_range",
4554  "display",
4555  "end_level_data",
4556  "era",
4557  "event",
4558  "generator",
4559  "label",
4560  "lua",
4561  "map",
4562  "menu_item",
4563  "modification",
4564  "modify_unit_type",
4565  "music",
4566  "options",
4567  "side",
4568  "sound_source",
4569  "story",
4570  "terrain_graphics",
4571  "time",
4572  "time_area",
4573  "tunnel",
4574  "undo_stack",
4575  "variables"
4576 }};
4577 
4578 static bool is_handled_file_tag(const std::string& s)
4579 {
4580  for(const std::string& t : handled_file_tags) {
4581  if (s == t) return true;
4582  }
4583 
4584  return false;
4585 }
4586 
4587 /**
4588  * Executes the game_events.on_load function and passes to it all the
4589  * scenario tags not yet handled.
4590  */
4592 {
4593  lua_State *L = mState;
4594 
4595  if (!luaW_getglobal(L, "wesnoth", "game_events", "on_load"))
4596  return;
4597 
4598  lua_newtable(L);
4599  int k = 1;
4600  for (const config::any_child &v : level.all_children_range())
4601  {
4602  if (is_handled_file_tag(v.key)) continue;
4603  lua_createtable(L, 2, 0);
4604  lua_pushstring(L, v.key.c_str());
4605  lua_rawseti(L, -2, 1);
4606  luaW_pushconfig(L, v.cfg);
4607  lua_rawseti(L, -2, 2);
4608  lua_rawseti(L, -2, k++);
4609  }
4610 
4611  luaW_pcall(L, 1, 0, true);
4612 }
4613 
4614 /**
4615  * Executes the game_events.on_save function and adds to @a cfg the
4616  * returned tags. Also flushes the [lua] tags.
4617  */
4619 {
4620  lua_State *L = mState;
4621 
4622  if (!luaW_getglobal(L, "wesnoth", "game_events", "on_save"))
4623  return;
4624 
4625  if (!luaW_pcall(L, 0, 1, false))
4626  return;
4627 
4628  config v;
4629  luaW_toconfig(L, -1, v);
4630  lua_pop(L, 1);
4631 
4632  for (;;)
4633  {
4635  if (i == v.ordered_end()) break;
4636  if (is_handled_file_tag(i->key))
4637  {
4638  /*
4639  * It seems the only tags appearing in the config v variable here
4640  * are the core-lua-handled (currently [item] and [objectives])
4641  * and the extra UMC ones.
4642  */
4643  const std::string m = "Tag is already used: [" + i->key + "]";
4644  log_error(m.c_str());
4645  v.erase(i);
4646  continue;
4647  }
4648  cfg.splice_children(v, i->key);
4649  }
4650 }
4651 
4652 /**
4653  * Executes the game_events.on_event function.
4654  * Returns false if there was no lua handler for this event
4655  */
4657 {
4658  lua_State *L = mState;
4659 
4660  if (!luaW_getglobal(L, "wesnoth", "game_events", "on_event"))
4661  return false;
4662 
4663  queued_event_context dummy(&ev, queued_events_);
4664  lua_pushstring(L, ev.name.c_str());
4665  luaW_pcall(L, 1, 0, false);
4666  return true;
4667 }
4668 
4669 void game_lua_kernel::custom_command(const std::string& name, const config& cfg)
4670 {
4671  lua_State *L = mState;
4672 
4673  if (!luaW_getglobal(L, "wesnoth", "custom_synced_commands", name)) {
4674  return;
4675  }
4676  luaW_pushconfig(L, cfg);
4677  luaW_pcall(L, 1, 0, false);
4678 }
4679 
4680 /**
4681  * Applies its upvalue as an effect
4682  * Arg 1: The unit to apply to
4683  * Arg 3: The [effect] tag contents
4684  * Arg 3: If false, only build description
4685  * Return: The description of the effect
4686  */
4688 {
4689  std::string which_effect = lua_tostring(L, lua_upvalueindex(1));
4690  bool need_apply = luaW_toboolean(L, lua_upvalueindex(2));
4691  // Argument 1 is the implicit "self" argument, which isn't needed here
4692  lua_unit u(luaW_checkunit(L, 2));
4693  config cfg = luaW_checkconfig(L, 3);
4694 
4695  // The times= key is supposed to be ignored by the effect function.
4696  // However, just in case someone doesn't realize this, we will set it to 1 here.
4697  cfg["times"] = 1;
4698 
4699  if(need_apply) {
4700  u->apply_builtin_effect(which_effect, cfg);
4701  return 0;
4702  } else {
4703  std::string description = u->describe_builtin_effect(which_effect, cfg);
4704  lua_pushstring(L, description.c_str());
4705  return 1;
4706  }
4707 }
4708 
4709 /**
4710 * Registers a function for use as an effect handler.
4711 */
4713 {
4714  lua_State *L = mState;
4715 
4716  // The effect name is at the top of the stack
4717  int str_i = lua_gettop(L);
4718  lua_newtable(L); // The functor table
4719  lua_newtable(L); // The functor metatable
4720  lua_pushstring(L, "__call");
4721  lua_pushvalue(L, str_i);
4722  lua_pushboolean(L, true);
4723  lua_pushcclosure(L, &dispatch<&game_lua_kernel::cfun_builtin_effect>, 2);
4724  lua_rawset(L, -3); // Set the call metafunction
4725  lua_pushstring(L, "__descr");
4726  lua_pushvalue(L, str_i);
4727  lua_pushboolean(L, false);
4728  lua_pushcclosure(L, &dispatch<&game_lua_kernel::cfun_builtin_effect>, 2);
4729  lua_rawset(L, -3); // Set the descr "metafunction"
4730  lua_setmetatable(L, -2); // Apply the metatable to the functor table
4731 }
4732 
4733 
4734 /**
4735  * Executes its upvalue as a wml action.
4736  */
4738 {
4741 
4742  vconfig vcfg = luaW_checkvconfig(L, 1);
4743  h(get_event_info(), vcfg);
4744  return 0;
4745 }
4746 
4747 /**
4748  * Registers a function for use as an action handler.
4749  */
4751 {
4752  lua_State *L = mState;
4753 
4754  lua_getglobal(L, "wesnoth");
4755  lua_pushstring(L, "wml_actions");
4756  lua_rawget(L, -2);
4757  lua_pushstring(L, cmd.c_str());
4758  lua_pushlightuserdata(L, reinterpret_cast<void *>(h));
4759  lua_pushcclosure(L, &dispatch<&game_lua_kernel::cfun_wml_action>, 1);
4760  lua_rawset(L, -3);
4761  lua_pop(L, 2);
4762 }
4763 
4764 using wml_conditional_handler = bool(*)(const vconfig&);
4765 
4766 /**
4767  * Executes its upvalue as a wml condition and returns the result.
4768  */
4770 {
4773 
4774  vconfig vcfg = luaW_checkvconfig(L, 1);
4775  lua_pushboolean(L, h(vcfg));
4776  return 1;
4777 }
4778 
4779 /**
4780  * Registers a function for use as a conditional handler.
4781  */
4783 {
4784  lua_State *L = mState;
4785 
4786  lua_getglobal(L, "wesnoth");
4787  lua_pushstring(L, "wml_conditionals");
4788  lua_rawget(L, -2);
4789  lua_pushstring(L, cmd.c_str());
4790  lua_pushlightuserdata(L, reinterpret_cast<void *>(h));
4792  lua_rawset(L, -3);
4793  lua_pop(L, 2);
4794 }
4795 
4796 /**
4797  * Runs a command from an event handler.
4798  * @return true if there is a handler for the command.
4799  * @note @a cfg should be either volatile or long-lived since the Lua
4800  * code may grab it for an arbitrary long time.
4801  */
4802 bool game_lua_kernel::run_wml_action(const std::string& cmd, const vconfig& cfg,
4803  const game_events::queued_event& ev)
4804 {
4805  lua_State *L = mState;
4806 
4807 
4808  if (!luaW_getglobal(L, "wesnoth", "wml_actions", cmd))
4809  return false;
4810 
4811  queued_event_context dummy(&ev, queued_events_);
4812  luaW_pushvconfig(L, cfg);
4813  luaW_pcall(L, 1, 0, true);
4814  return true;
4815 }
4816 
4817 
4818 /**
4819  * Evaluates a WML conidition.
4820  *
4821  * @returns Whether the condition passed.
4822  * @note @a cfg should be either volatile or long-lived since the Lua
4823  * code may grab it for an arbitrarily long time.
4824  */
4825 bool game_lua_kernel::run_wml_conditional(const std::string& cmd, const vconfig& cfg)
4826 {
4827  lua_State* L = mState;
4828 
4829  // If an invalid coniditional tag is used, consider it a pass.
4830  if(!luaW_getglobal(L, "wesnoth", "wml_conditionals", cmd)) {
4831  lg::wml_error() << "unknown conditional wml: [" << cmd << "]\n";
4832  return true;
4833  }
4834 
4835  luaW_pushvconfig(L, cfg);
4836 
4837  // Any runtime error is considered a fail.
4838  if(!luaW_pcall(L, 1, 1, true)) {
4839  return false;
4840  }
4841 
4842  bool b = luaW_toboolean(L, -1);
4843 
4844  lua_pop(L, 1);
4845  return b;
4846 }
4847 
4848 
4849 /**
4850 * Runs a script from a location filter.
4851 * The script is an already compiled function given by its name.
4852 */
4853 bool game_lua_kernel::run_filter(char const *name, const map_location& l)
4854 {
4857  return run_filter(name, 2);
4858 }
4859 
4860 /**
4861 * Runs a script from a location filter.
4862 * The script is an already compiled function given by its name.
4863 */
4864 bool game_lua_kernel::run_filter(char const *name, const team& t)
4865 {
4866  //TODO: instead of passing the lua team object we coudl also jsut pass its
4867  // number. then we wouldn't need this const cast.
4868  luaW_pushteam(mState, const_cast<team&>(t));
4869  return run_filter(name, 1);
4870 }
4871 /**
4872 * Runs a script from a unit filter.
4873 * The script is an already compiled function given by its name.
4874 */
4875 bool game_lua_kernel::run_filter(char const *name, const unit& u)
4876 {
4877  lua_State *L = mState;
4878  lua_unit* lu = luaW_pushlocalunit(L, const_cast<unit&>(u));
4879  // stack: unit
4880  // put the unit to the stack twice to prevent gc.
4881  lua_pushvalue(L, -1);
4882  // stack: unit, unit
4883  bool res = run_filter(name, 1);
4884  // stack: unit
4885  lu->clear_ref();
4886  lua_pop(L, 1);
4887  return res;
4888 }
4889 /**
4890 * Runs a script from a filter.
4891 * The script is an already compiled function given by its name.
4892 */
4893 bool game_lua_kernel::run_filter(char const *name, int nArgs)
4894 {
4895  map_locker(this);
4896  lua_State *L = mState;
4897  // Get the user filter by name.
4898  const std::vector<std::string>& path = utils::split(name, '.', utils::STRIP_SPACES);
4899  if (!luaW_getglobal(L, path))
4900  {
4901  std::string message = std::string() + "function " + name + " not found";
4902  log_error(message.c_str(), "Lua SUF Error");
4903  //we pushed nothing and can safeley return.
4904  return false;
4905  }
4906  lua_insert(L, -nArgs - 1);
4907 
4908  if (!luaW_pcall(L, nArgs, 1)) return false;
4909 
4910  bool b = luaW_toboolean(L, -1);
4911  lua_pop(L, 1);
4912  return b;
4913 }
4914 
4915 std::string game_lua_kernel::apply_effect(const std::string& name, unit& u, const config& cfg, bool need_apply)
4916 {
4917  lua_State *L = mState;
4918  int top = lua_gettop(L);
4919  std::string descr;
4920  // Stack: nothing
4921  lua_unit* lu = luaW_pushlocalunit(L, u);
4922  // Stack: unit
4923  // (Note: The unit needs to be on the stack twice to prevent untimely GC.)
4924  luaW_pushconfig(L, cfg);
4925  // Stack: unit, cfg
4926  if(luaW_getglobal(L, "wesnoth", "effects", name)) {
4927  map_locker(this);
4928  // Stack: unit, cfg, effect
4929  if(lua_istable(L, -1)) {
4930  // Effect is implemented by a table with __call and __descr
4931  if(need_apply) {
4932  lua_pushvalue(L, -1);
4933  // Stack: unit, cfg, effect, effect
4934  lua_pushvalue(L, top + 1);
4935  // Stack: unit, cfg, effect, effect, unit
4936  lua_pushvalue(L, top + 2);
4937  // Stack: unit, cfg, effect, effect, unit, cfg
4938  luaW_pcall(L, 2, 0);
4939  // Stack: unit, cfg, effect
4940  }
4941  if(luaL_getmetafield(L, -1, "__descr")) {
4942  // Stack: unit, cfg, effect, __descr
4943  if(lua_isstring(L, -1)) {
4944  // __descr was a static string
4945  descr = lua_tostring(L, -1);
4946  } else {
4947  lua_pushvalue(L, -2);
4948  // Stack: unit, cfg, effect, __descr, effect
4949  lua_pushvalue(L, top + 1);
4950  // Stack: unit, cfg, effect, __descr, effect, unit
4951  lua_pushvalue(L, top + 2);
4952  // Stack: unit, cfg, effect, __descr, effect, unit, cfg
4953  luaW_pcall(L, 3, 1);
4954  if(lua_isstring(L, -1) && !lua_isnumber(L, -1)) {
4955  descr = lua_tostring(L, -1);
4956  } else {
4957  ERR_LUA << "Effect __descr metafunction should have returned a string, but instead returned ";
4958  if(lua_isnone(L, -1)) {
4959  ERR_LUA << "nothing";
4960  } else {
4961  ERR_LUA << lua_typename(L, lua_type(L, -1));
4962  }
4963  }
4964  }
4965  }
4966  } else if(need_apply) {
4967  // Effect is assumed to be a simple function; no description is provided
4968  lua_pushvalue(L, top + 1);
4969  // Stack: unit, cfg, effect, unit
4970  lua_pushvalue(L, top + 2);
4971  // Stack: unit, cfg, effect, unit, cfg
4972  luaW_pcall(L, 2, 0);
4973  // Stack: unit, cfg
4974  }
4975  }
4976  lua_settop(L, top);
4977  lu->clear_ref();
4978  return descr;
4979 }
4980 
4982 {
4983  return ai::lua_ai_context::create(mState,code,engine);
4984 }
4985 
4987 {
4988  return ai::lua_ai_action_handler::create(mState,code,context);
4989 }
4990 
4992 {
4993  lua_State *L = mState;
4994 
4995  if (!luaW_getglobal(L, "wesnoth", "game_events", "on_mouse_move")) {
4996  return;
4997  }
4998  lua_push(L, loc.wml_x());
4999  lua_push(L, loc.wml_y());
5000  luaW_pcall(L, 2, 0, false);
5001  return;
5002 }
5003 
5005 {
5006  lua_State *L = mState;
5007 
5008  if (!luaW_getglobal(L, "wesnoth", "game_events", "on_mouse_action")) {
5009  return;
5010  }
5011  lua_push(L, loc.wml_x());
5012  lua_push(L, loc.wml_y());
5013  luaW_pcall(L, 2, 0, false);
5014  return;
5015 }
const_attack_ptr weapon
The weapon used by the unit to attack the opponent, or nullptr if there is none.
Definition: attack.hpp:51
void set_wml_y(int v)
Definition: location.hpp:161
bool luaW_checkvariable(lua_State *L, variable_access_create &v, int n)
Definition: lua_common.cpp:923
int dispatch(lua_State *L)
#define modify_bool_attrib(name, accessor)
Definition: lua_common.hpp:339
bool luaW_tableget(lua_State *L, int index, const char *key)
Definition: lua_common.cpp:966
play_controller * controller
Definition: resources.cpp:21
boost::intrusive_ptr< const unit > unit_const_ptr
Definition: ptr.hpp:30
int intf_get_terrain_info(lua_State *L)
Gets details about a terrain.
static int intf_transform_unit(lua_State *L)
Changes a unit to the given unit type.
#define lua_isnoneornil(L, n)
Definition: lua.h:359
void wait_for_end() const
Definition: animation.cpp:1442
unsigned int end_text_duration
for how long the end-of-campaign text is shown
bool empty() const
Tests for an attribute that either was never set or was set to "".
LUA_API void lua_pushlightuserdata(lua_State *L, void *p)
Definition: lapi.cpp:565
static int impl_end_level_data_get(lua_State *L)
LUALIB_API void * luaL_checkudata(lua_State *L, int ud, const char *tname)
Definition: lauxlib.cpp:333
config get_user_choice(const std::string &name, const user_choice &uch, int side=0)
std::stack< game_events::queued_event const *> queued_events_
Game board class.
Definition: game_board.hpp:50
LUA_API void lua_createtable(lua_State *L, int narray, int nrec)
Definition: lapi.cpp:684
#define lua_pushcfunction(L, f)
Definition: lua.h:350
static int intf_advance_unit(lua_State *L)
Advances a unit if the unit has enough xp.
static int intf_get_era(lua_State *L)
Gets a table for an era tag.
static int special_locations_pairs(lua_State *L)
virtual std::string get_id() const =0
utils::string_view luaW_tostring(lua_State *L, int index)
Definition: lua_common.cpp:978
int map_locked_
A value != 0 means that the shouldn&#39;t remove any units from the map, usually because we are currently...
std::string apply_effect(const std::string &name, unit &u, const config &cfg, bool need_apply)
bool is_odd(T num)
Definition: math.hpp:35
config & child(config_key_type key, int n=0)
Returns the nth child with the given key, or a reference to an invalid config if there is none...
Definition: config.cpp:420
lua_unit * luaW_pushunit(lua_State *L, Args... args)
Definition: lua_unit.hpp:115
bool on_map() const
Definition: lua_unit.hpp:99
int h() const
Effective map height, in hexes.
Definition: map.hpp:128
bool end_credits
whether to show the standard credits at the end
void set_shroud(bool shroud)
Definition: team.hpp:326
bool is_castle() const
Definition: terrain.hpp:142
double untouched
Resulting chance we were not hit by this opponent (important if it poisons)
std::vector< double > hp_dist
Resulting probability distribution (might be not as large as max_hp)
bool update_locked() const
Whether the screen has been &#39;locked&#39; or not.
Definition: video.cpp:344
void show_help(const std::string &show_topic, int xloc, int yloc)
Open the help browser, show topic with id show_topic.
Definition: help.cpp:114
entity_location loc2
Definition: pump.hpp:65
LUA_API lua_Number lua_tonumberx(lua_State *L, int idx, int *pisnum)
Definition: lapi.cpp:345
static display * get_singleton()
Returns the display object if a display object exists.
Definition: display.hpp:88
int intf_remove_sound_source(lua_State *L)
Removes a sound source by its ID Arg 1: sound source ID.
int intf_allow_end_turn(lua_State *)
Allow undo sets the flag saying whether the event has mutated the game to false.
const_all_children_itors all_children_range() const
In-order iteration over all children.
Definition: config.cpp:921
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
void start_animations()
Definition: animation.cpp:1383
int intf_find_path(lua_State *L)
Finds a path between two locations.
const terrain_code NONE_TERRAIN
Definition: translation.hpp:59
bool luaW_tovconfig(lua_State *L, int index, vconfig &vcfg)
Gets an optional vconfig from either a table or a userdata.
Definition: lua_common.cpp:836
std::string register_metatables(lua_State *L)
Definition: lua_unit.cpp:656
vconfig child(const std::string &key) const
Returns a child of *this whose key is key.
Definition: variable.cpp:288
int intf_set_end_campaign_credits(lua_State *L)
void reshroud()
Definition: team.hpp:324
const t_string & description() const
Definition: terrain.hpp:49
LUALIB_API lua_Number luaL_checknumber(lua_State *L, int arg)
Definition: lauxlib.cpp:408
game_display * game_display_
void luaW_pushconfig(lua_State *L, const config &cfg)
Converts a config object to a Lua table pushed at the top of the stack.
Definition: lua_common.cpp:730
LUA_API void lua_settop(lua_State *L, int idx)
Definition: lapi.cpp:172
int intf_fire_event(lua_State *L, const bool by_id)
Fires an event.
#define lua_isnone(L, n)
Definition: lua.h:358
int intf_get_time_of_day(lua_State *L)
Gets time of day information.
int intf_get_unit(lua_State *)
Gets the unit at the given location or with the given id.
LUA_API int lua_type(lua_State *L, int idx)
Definition: lapi.cpp:251
int village_support
Definition: game_config.cpp:55
bool luaW_pcall(lua_State *L, int nArgs, int nRets, bool allow_wml_error)
Calls a Lua function stored below its nArgs arguments at the top of the stack.
void luaW_pushteam(lua_State *L, team &tm)
Create a full userdata containing a pointer to the team.
Definition: lua_team.cpp:340
std::string era()
Definition: game.cpp:723
std::string plague_type
The plague type used by the attack, if any.
Definition: attack.hpp:83
This class represents a single unit of a specific type.
Definition: unit.hpp:129
int dummy
Definition: lstrlib.cpp:1125
game_classification * classification
Definition: resources.cpp:34
int intf_get_variable(lua_State *L)
Gets a WML variable.
tod_color color
The color modifications that should be made to the game board to reflect the time of day...
int movement_cost(const t_translation::terrain_code &terrain) const
Get the unit&#39;s movement cost on a particular terrain.
Definition: unit.hpp:1419
int intf_match_location(lua_State *L)
Matches a location against the given filter.
std::string join(const T &v, const std::string &s=",")
Generates a new string joining container items in a list.
void advance_to(const unit_type &t, bool use_traits=false)
Advances this unit to another type.
Definition: unit.cpp:922
std::vector< int > get_sides_vector(const vconfig &cfg)
Gets a vector of sides from side= attribute in a given config node.
Various functions implementing vision (through fog of war and shroud).
int luaW_type_error(lua_State *L, int narg, const char *tname)
bool run_filter(char const *name, const unit &u)
Runs a script from a unit filter.
int impl_theme_items_get(lua_State *L)
Creates a field of the theme_items table and returns it (__index metamethod).
int intf_replace_schedule(lua_State *l)
Replacing the current time of day schedule.
static int special_locations_len(lua_State *L)
bool play_stage()
Play the turn - strategy.
Definition: stage.cpp:56
void set_clip_rect(const SDL_Rect &r)
unit & luaW_checkunit(lua_State *L, int index, bool only_on_map)
Converts a Lua value to a unit pointer.
Definition: lua_unit.cpp:194
static manager & get_singleton()
Definition: manager.hpp:151
config_array_view traits() const
Definition: types.hpp:378
LUA_API void lua_pushboolean(lua_State *L, int b)
Definition: lapi.cpp:557
LUA_API int lua_rawgeti(lua_State *L, int idx, lua_Integer n)
Definition: lapi.cpp:658
Various functions that implement attacks and attack calculations.
int impl_end_level_data_set(lua_State *)
Variant for storing WML attributes.
int intf_view_locked(lua_State *L)
Gets whether gamemap scrolling is disabled for the user.
Add a special kind of assert to validate whether the input from WML doesn&#39;t contain any problems that...
bool luaW_isunit(lua_State *L, int index)
Test if a Lua value is a unit.
Definition: lua_unit.cpp:116
void set_next_scenario(const std::string &next_scenario)
Definition: game_data.hpp:94
bool clear_fog(const map_location &loc)
Definition: team.hpp:323
void add_log_data(const std::string &key, const std::string &var)
Definition: replay.cpp:310
virtual std::vector< component * > get_children(const std::string &type)
Definition: component.cpp:111
std::vector< team > & teams()
static const char animatorKey[]
static l_noret error(LoadState *S, const char *why)
Definition: lundump.cpp:39
int intf_set_terrain(lua_State *L)
Sets a terrain code.
int intf_log(lua_State *L)
Logs a message Arg 1: (optional) Logger; "wml" for WML errors or deprecations Arg 2: Message Arg 3: W...
logger & info()
Definition: log.cpp:90
#define a
config_array_view child_range(config_key_type key) const
static map & registry()
using static function variable instead of static member variable to prevent static initialization fia...
int intf_clear_messages(lua_State *)
Removes all messages from the chat window.
Definition: video.hpp:31
bool has_child(config_key_type key) const
Determine whether a config has a child or not.
Definition: config.cpp:412
void refog()
Definition: team.hpp:325
int intf_play_sound(lua_State *L)
Plays a sound, possibly repeated.
int next_player_number_
Definition: game_state.hpp:58
int intf_terrain_mask(lua_State *L)
Reaplces part of the map.
static int impl_animator_get(lua_State *L)
bool have_location(const vconfig &cfg)
int intf_label(lua_State *L)
void add_animation(const unit *animated_unit, const unit_animation *animation, const map_location &src=map_location::null_location(), bool with_bars=false, const std::string &text="", const color_t text_color={0, 0, 0})
Definition: animation.cpp:1325
static int special_locations_newindex(lua_State *L)
bool has_attribute(const std::string &key) const
< Synonym for operator[]
Definition: variable.hpp:106
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
LUA_API void lua_rawseti(lua_State *L, int idx, lua_Integer n)
Definition: lapi.cpp:817
LUALIB_API int luaL_getmetafield(lua_State *L, int obj, const char *event)
Definition: lauxlib.cpp:772
LUA_API int lua_gettop(lua_State *L)
Definition: lapi.cpp:167
child_itors child_range(config_key_type key)
Definition: config.cpp:362
std::string register_table(lua_State *L)
std::string id
Definition: time_of_day.hpp:91
int border_size() const
Size of the map border.
Definition: map.hpp:131
int intf_extract_unit(lua_State *L)
Extracts a unit from the map or a recall list and gives it to Lua.
double average_hp(unsigned int healing=0) const
What&#39;s the average hp (weighted average of hp_dist).
const map_location & filter_loc() const
bool luaW_pushvariable(lua_State *L, variable_access_const &v)
Definition: lua_common.cpp:895
static int intf_copy_unit(lua_State *L)
Copies a unit.
void remove_floating_label(int handle)
removes the floating label given by &#39;handle&#39; from the screen
std::string register_metatable(lua_State *L)
static int special_locations_next(lua_State *L)
int intf_get_all_vars(lua_State *L)
Gets all the WML variables currently set.
LUA_API int lua_getglobal(lua_State *L, const char *name)
Definition: lapi.cpp:605
int intf_find_cost_map(lua_State *L)
Is called with one or more units and builds a cost map.
void clear(const std::string &key)
Definition: general.cpp:206
virtual const gamemap & map() const override
Definition: game_board.hpp:109
int lawful_bonus
The % bonus lawful units receive.
Definition: time_of_day.hpp:84
#define return_string_attrib(name, accessor)
Definition: lua_common.hpp:217
dest_vect destinations
Definition: pathfind.hpp:99
unit_ptr clone() const
Definition: unit.hpp:204
#define lua_tointeger(L, i)
Definition: lua.h:342
int intf_set_time_of_day(lua_State *L)
int wml_x() const
Definition: location.hpp:157
virtual config to_config() const
Serialize to config.
Definition: engine_lua.cpp:388
A terrain string which is converted to a terrain is a string with 1 or 2 layers the layers are separa...
Definition: translation.hpp:50
static int special_locations_index(lua_State *L)
static lua_ai_context * create(lua_State *L, char const *code, engine_lua *engine)
Definition: core.cpp:995
LUA_API int lua_rawget(lua_State *L, int idx)
Definition: lapi.cpp:647
Composite AI stages.
std::string image
The image to be displayed in the game status.
Definition: time_of_day.hpp:88
unit_type_data unit_types
Definition: types.cpp:1376
void set_wml_x(int v)
Definition: location.hpp:160
int intf_get_fog_or_shroud(lua_State *L, bool fog)
static int cfun_wml_condition(lua_State *L)
Executes its upvalue as a wml condition and returns the result.
bool prescenario_save
Should a prescenario be created the next game?
int intf_set_village_owner(lua_State *L)
Sets the owner of a village.
lua_unit * luaW_pushlocalunit(lua_State *L, unit &u)
Pushes a private unit on the stack.
Definition: lua_unit.cpp:215
const color_t LABEL_COLOR
int intf_unit_ability(lua_State *L)
Returns true if the unit has the given ability enabled.
int intf_match_unit(lua_State *L)
Matches a unit against the given filter.
int intf_set_next_scenario(lua_State *L)
void push_builtin_effect()
Registers a function for use as an effect handler.
static CVideo & get_singleton()
Definition: video.hpp:48
std::string name
Definition: pump.hpp:62
Replay control code.
#define h
static void msg(const char *act, debug_info &i, const char *to="", const char *result="")
Definition: debugger.cpp:109
#define lua_tonumber(L, i)
Definition: lua.h:341
config & child_or_add(config_key_type key)
Definition: config.cpp:466
advance_unit_params & fire_events(bool value)
Definition: advancement.hpp:45
bool replay_save
Should a replay save be made?
void remove(const std::string &id)
Definition: soundsource.cpp:65
std::string save_id_or_number() const
Definition: team.hpp:232
void custom_command(const std::string &, const config &)
Additional functionality for a non-const variable_info.
bool slows
Attack slows opponent when it hits.
Definition: attack.hpp:56
int intf_skip_messages(lua_State *L)
Set whether to skip messages Arg 1 (optional) - boolean.
void set_font_size(int font_size)
LUA_API int lua_isuserdata(lua_State *L, int idx)
Definition: lapi.cpp:289
const std::string & editor_image() const
Definition: terrain.hpp:46
LUA_API void lua_pushcclosure(lua_State *L, lua_CFunction fn, int n)
Definition: lapi.cpp:532
int intf_scroll(lua_State *L)
virtual void draw()
Draws invalidated items.
Definition: display.cpp:2482
int impl_theme_items_set(lua_State *L)
Sets a field of the theme_items table (__newindex metamethod).
void append_children(const config &cfg)
Adds children from cfg.
Definition: config.cpp:241
#define return_vector_string_attrib(name, accessor)
Definition: lua_common.hpp:268
int intf_get_max_liminal_bonus(lua_State *L)
Gets the max liminal bonus.
static bool is_handled_file_tag(const std::string &s)
int intf_get_sides(lua_State *L)
Returns a proxy table array for all sides matching the given SSF.
void lua_push(lua_State *L, const T &val)
Definition: push_check.hpp:371
void add_unit(const unit &u, bool use_max_moves=true)
Adds a units cost map to cost_map (increments the elements in cost_map)
Definition: pathfind.cpp:911
int drain_constant
Base HP drained regardless of damage dealt.
Definition: attack.hpp:78
an object to leave the synced context during draw or unsynced wml items when we don’t know whether w...
int(game_lua_kernel::* member_callback2)(lua_State *, bool)
int intf_gamestate_inspector(lua_State *)
-file sdl_utils.hpp
int impl_game_config_set(lua_State *L) override
Sets some game_config data (__newindex metamethod).
void(* handler)(const queued_event &, const vconfig &)
Definition: action_wml.hpp:49
map_location luaW_checklocation(lua_State *L, int index)
Converts an optional table or pair of integers to a map location object.
Definition: lua_common.cpp:722
Definitions for the interface to Wesnoth Markup Language (WML).
bool empty() const
Definition: variable.hpp:107
const game_events::queued_event & get_event_info()
LUA_API int lua_absindex(lua_State *L, int idx)
Definition: lapi.cpp:160
std::vector< std::string > split(const std::string &val, const char c, const int flags)
Splits a (comma-)separated string into a vector of pieces.
void load_config(const config &v)
static synced_state get_synced_state()
unsigned int chance_to_hit
Effective chance to hit as a percentage (all factors accounted for).
Definition: attack.hpp:74
int rest_heal_amount
Definition: game_config.cpp:61
std::map< int, config > get_user_choice_multiple_sides(const std::string &name, const user_choice &uch, std::set< int > sides)
Performs a choice for multiple sides for WML events.
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
const_attr_itors attribute_range() const
Definition: config.cpp:809
LUA_API void * lua_newuserdata(lua_State *L, size_t size)
Definition: lapi.cpp:1184
A single unit type that the player may recruit.
Definition: types.hpp:44
int intf_get_locations(lua_State *L)
Gets all the locations matching a given filter.
game_data * gamedata
Definition: resources.cpp:22
int intf_log_replay(lua_State *L)
advance_unit_params & animate(bool value)
Definition: advancement.hpp:46
Unit and team statistics.
#define lua_pop(L, n)
Definition: lua.h:344
void play_sound(const std::string &files, channel_group group, unsigned int repeats)
Definition: sound.cpp:1020
void append_active_ai_for_side(ai::side_number side, const config &cfg)
Appends AI parameters to active AI of the given side.
Definition: manager.cpp:677
#define return_cfgref_attrib(name, accessor)
Definition: lua_common.hpp:260
bool clear_dest(const map_location &dest, const unit &viewer)
Clears shroud (and fog) at the provided location and its immediate neighbors.
Definition: vision.cpp:494
bool reveal_map
Should we reveal map when game is ended? (Multiplayer only)
bool have_unit(const vconfig &cfg)
#define b
bool is_village() const
Definition: terrain.hpp:141
bool clear_unit(const map_location &view_loc, team &view_team, std::size_t viewer_id, int sight_range, bool slowed, const movetype::terrain_costs &costs, const map_location &real_loc, const std::set< map_location > *known_units=nullptr, std::size_t *enemy_count=nullptr, std::size_t *friend_count=nullptr, move_unit_spectator *spectator=nullptr, bool instant=true)
Clears shroud (and fog) around the provided location for view_team based on sight_range, costs, and slowed.
Definition: vision.cpp:330
int intf_find_reach(lua_State *L)
Finds all the locations reachable by a unit.
config to_config() const
void set_game_display(game_display *gd)
bool poisons
Attack poisons opponent when it hits.
Definition: attack.hpp:60
int vision_cost(const t_translation::terrain_code &terrain) const
Get the unit&#39;s vision cost on a particular terrain.
Definition: unit.hpp:1429
int intf_set_variable(lua_State *L)
Sets a WML variable.
bool fog()
Definition: game.cpp:563
LUALIB_API const char * luaL_optlstring(lua_State *L, int arg, const char *def, size_t *len)
Definition: lauxlib.cpp:397
std::string register_metatable(lua_State *L)
Definition: lua_team.cpp:305
void set_flag(const std::string &flag)
Definition: team.hpp:305
int intf_delay(lua_State *L)
Delays engine for a while.