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