The Battle for Wesnoth  1.15.12+dev
lua_pathfind_cost_calculator.hpp
Go to the documentation of this file.
1 /*
2  Copyright (C) 2017-2018 by the Battle for Wesnoth Project https://www.wesnoth.org/
3 
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,
9  but WITHOUT ANY WARRANTY.
10 
11  See the COPYING file for more details.
12 */
13 
14 #pragma once
15 #include "lua/lua.h"
16 #include "map/location.hpp"
17 #include "pathfind/pathfind.hpp"
18 
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  /**
28  * @param L_ the pointer to the lua interpreter.
29  * @param i the stack position of the lua function to calculate the cost.
30  */
31  lua_pathfind_cost_calculator(lua_State *L_, int i): L(L_), index(i) {}
32  double cost(const map_location &loc, const double so_far) const
33  {
34  // Copy the user function and push the location and current cost.
35  lua_pushvalue(L, index);
36  lua_pushinteger(L, loc.wml_x());
37  lua_pushinteger(L, loc.wml_y());
38  lua_pushnumber(L, so_far);
39  // Execute the user function.
40  if (!luaW_pcall(L, 3, 1)) {
41  return 1.;
42  }
43  // Return a cost of at least 1 mp to avoid issues in pathfinder.
44  // (Condition is inverted to detect NaNs.)
45  double cost = lua_tonumber(L, -1);
46  lua_pop(L, 1);
47  return !(cost >= 1.) ? 1. : cost;
48  }
49 };
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:152
#define lua_tonumber(L, i)
Definition: lua.h:361
lua_pathfind_cost_calculator(lua_State *L_, int i)
#define lua_pop(L, n)
Definition: lua.h:364
int wml_y() const
Definition: location.hpp:153
LUA_API void lua_pushnumber(lua_State *L, lua_Number n)
Definition: lapi.cpp:481
Encapsulates the map of the game.
Definition: location.hpp:37
Cost function object relying on a Lua function.
std::size_t i
Definition: function.cpp:940
LUA_API void lua_pushvalue(lua_State *L, int idx)
Definition: lapi.cpp:246
LUA_API void lua_pushinteger(lua_State *L, lua_Integer n)
Definition: lapi.cpp:489
This module contains various pathfinding functions and utilities.