The Battle for Wesnoth  1.15.5+dev
Go to the documentation of this file.
1 /*
2  Copyright (C) 2017-2018 by the Battle for Wesnoth Project
4  This program is free software; you can redistribute it and/or modify
5  it under the terms of the GNU General Public License as published by
6  the Free Software Foundation; either version 2 of the License, or
7  (at your option) any later version.
8  This program is distributed in the hope that it will be useful,
11  See the COPYING file for more details.
12 */
14 #pragma once
15 #include "lua/lua.h"
16 #include "map/location.hpp"
17 #include "pathfind/pathfind.hpp"
19 /**
20  * Cost function object relying on a Lua function.
21  * @note The stack index of the Lua function must be valid each time the cost is computed.
22  */
24 {
26  int index;
27  /// @param i the stack position of the lua function to calculate the cost.
28  lua_pathfind_cost_calculator(lua_State *L_, int i): L(L_), index(i) {}
29  double cost(const map_location &loc, const double so_far) const
30  {
31  // Copy the user function and push the location and current cost.
32  lua_pushvalue(L, index);
33  lua_pushinteger(L, loc.wml_x());
34  lua_pushinteger(L, loc.wml_y());
35  lua_pushnumber(L, so_far);
36  // Execute the user function.
37  if (!luaW_pcall(L, 3, 1)) {
38  return 1.;
39  }
40  // Return a cost of at least 1 mp to avoid issues in pathfinder.
41  // (Condition is inverted to detect NaNs.)
42  double cost = lua_tonumber(L, -1);
43  lua_pop(L, 1);
44  return !(cost >= 1.) ? 1. : cost;
45  }
46 };
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.
double cost(const map_location &loc, const double so_far) const
int wml_x() const
Definition: location.hpp:157
#define lua_tonumber(L, i)
Definition: lua.h:341
lua_pathfind_cost_calculator(lua_State *L_, int i)
#define lua_pop(L, n)
Definition: lua.h:344
int wml_y() const
Definition: location.hpp:158
LUA_API void lua_pushnumber(lua_State *L, lua_Number n)
Definition: lapi.cpp:458
Encapsulates the map of the game.
Definition: location.hpp:42
Cost function object relying on a Lua function.
std::size_t i
Definition: function.cpp:933
LUA_API void lua_pushvalue(lua_State *L, int idx)
Definition: lapi.cpp:237
LUA_API void lua_pushinteger(lua_State *L, lua_Integer n)
Definition: lapi.cpp:466
This module contains various pathfinding functions and utilities.