The Battle for Wesnoth  1.17.6+dev
lua_pathfind_cost_calculator.hpp
Go to the documentation of this file.
1 /*
2  Copyright (C) 2017 - 2022
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 #pragma once
16 
17 #include "lua/lua.h"
18 #include "map/location.hpp"
19 #include "pathfind/pathfind.hpp"
20 
21 /**
22  * Cost function object relying on a Lua function.
23  * @note The stack index of the Lua function must be valid each time the cost is computed.
24  */
26 {
27  lua_State *L;
28  int index;
29  /**
30  * @param L_ the pointer to the lua interpreter.
31  * @param i the stack position of the lua function to calculate the cost.
32  */
33  lua_pathfind_cost_calculator(lua_State *L_, int i): L(L_), index(i) {}
34  double cost(const map_location &loc, const double so_far) const
35  {
36  // Copy the user function and push the location and current cost.
37  lua_pushvalue(L, index);
38  lua_pushinteger(L, loc.wml_x());
39  lua_pushinteger(L, loc.wml_y());
40  lua_pushnumber(L, so_far);
41  // Execute the user function.
42  if (!luaW_pcall(L, 3, 1)) {
43  return 1.;
44  }
45  // Return a cost of at least 1 mp to avoid issues in pathfinder.
46  // (Condition is inverted to detect NaNs.)
47  double cost = lua_tonumber(L, -1);
48  lua_pop(L, 1);
49  return !(cost >= 1.) ? 1. : cost;
50  }
51 };
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:153
lua_pathfind_cost_calculator(lua_State *L_, int i)
int wml_y() const
Definition: location.hpp:154
Encapsulates the map of the game.
Definition: location.hpp:38
Cost function object relying on a Lua function.
std::size_t i
Definition: function.cpp:967
This module contains various pathfinding functions and utilities.