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