]> git.lizzy.rs Git - dragonfireclient.git/blob - src/script/cpp_api/s_base.cpp
Order es_DrawType exactly like enum NodeDrawType in nodedef.h (#5946)
[dragonfireclient.git] / src / script / cpp_api / s_base.cpp
1 /*
2 Minetest
3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #include "cpp_api/s_base.h"
21 #include "cpp_api/s_internal.h"
22 #include "cpp_api/s_security.h"
23 #include "lua_api/l_object.h"
24 #include "common/c_converter.h"
25 #include "serverobject.h"
26 #include "filesys.h"
27 #include "mods.h"
28 #include "porting.h"
29 #include "util/string.h"
30 #include "server.h"
31 #ifndef SERVER
32 #include "client.h"
33 #endif
34
35
36 extern "C" {
37 #include "lualib.h"
38 #if USE_LUAJIT
39         #include "luajit.h"
40 #endif
41 }
42
43 #include <stdio.h>
44 #include <cstdarg>
45 #include "script/common/c_content.h"
46 #include <sstream>
47
48
49 class ModNameStorer
50 {
51 private:
52         lua_State *L;
53 public:
54         ModNameStorer(lua_State *L_, const std::string &mod_name):
55                 L(L_)
56         {
57                 // Store current mod name in registry
58                 lua_pushstring(L, mod_name.c_str());
59                 lua_rawseti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_CURRENT_MOD_NAME);
60         }
61         ~ModNameStorer()
62         {
63                 // Clear current mod name from registry
64                 lua_pushnil(L);
65                 lua_rawseti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_CURRENT_MOD_NAME);
66         }
67 };
68
69
70 /*
71         ScriptApiBase
72 */
73
74 ScriptApiBase::ScriptApiBase() :
75         m_luastackmutex(),
76         m_gamedef(NULL)
77 {
78 #ifdef SCRIPTAPI_LOCK_DEBUG
79         m_lock_recursion_count = 0;
80 #endif
81
82         m_luastack = luaL_newstate();
83         FATAL_ERROR_IF(!m_luastack, "luaL_newstate() failed");
84
85         lua_atpanic(m_luastack, &luaPanic);
86
87         luaL_openlibs(m_luastack);
88
89         // Make the ScriptApiBase* accessible to ModApiBase
90         lua_pushlightuserdata(m_luastack, this);
91         lua_rawseti(m_luastack, LUA_REGISTRYINDEX, CUSTOM_RIDX_SCRIPTAPI);
92
93         // Add and save an error handler
94         lua_pushcfunction(m_luastack, script_error_handler);
95         lua_rawseti(m_luastack, LUA_REGISTRYINDEX, CUSTOM_RIDX_ERROR_HANDLER);
96
97         // If we are using LuaJIT add a C++ wrapper function to catch
98         // exceptions thrown in Lua -> C++ calls
99 #if USE_LUAJIT
100         lua_pushlightuserdata(m_luastack, (void*) script_exception_wrapper);
101         luaJIT_setmode(m_luastack, -1, LUAJIT_MODE_WRAPCFUNC | LUAJIT_MODE_ON);
102         lua_pop(m_luastack, 1);
103 #endif
104
105         // Add basic globals
106         lua_newtable(m_luastack);
107         lua_setglobal(m_luastack, "core");
108
109         lua_pushstring(m_luastack, DIR_DELIM);
110         lua_setglobal(m_luastack, "DIR_DELIM");
111
112         lua_pushstring(m_luastack, porting::getPlatformName());
113         lua_setglobal(m_luastack, "PLATFORM");
114
115         // m_secure gets set to true inside
116         // ScriptApiSecurity::initializeSecurity(), if neccessary.
117         // Default to false otherwise
118         m_secure = false;
119
120         m_environment = NULL;
121         m_guiengine = NULL;
122 }
123
124 ScriptApiBase::~ScriptApiBase()
125 {
126         lua_close(m_luastack);
127 }
128
129 int ScriptApiBase::luaPanic(lua_State *L)
130 {
131         std::ostringstream oss;
132         oss << "LUA PANIC: unprotected error in call to Lua API ("
133                 << lua_tostring(L, -1) << ")";
134         FATAL_ERROR(oss.str().c_str());
135         // NOTREACHED
136         return 0;
137 }
138
139 void ScriptApiBase::loadMod(const std::string &script_path,
140                 const std::string &mod_name)
141 {
142         ModNameStorer mod_name_storer(getStack(), mod_name);
143
144         loadScript(script_path);
145 }
146
147 void ScriptApiBase::loadScript(const std::string &script_path)
148 {
149         verbosestream << "Loading and running script from " << script_path << std::endl;
150
151         lua_State *L = getStack();
152
153         int error_handler = PUSH_ERROR_HANDLER(L);
154
155         bool ok;
156         if (m_secure) {
157                 ok = ScriptApiSecurity::safeLoadFile(L, script_path.c_str());
158         } else {
159                 ok = !luaL_loadfile(L, script_path.c_str());
160         }
161         ok = ok && !lua_pcall(L, 0, 0, error_handler);
162         if (!ok) {
163                 std::string error_msg = lua_tostring(L, -1);
164                 lua_pop(L, 2); // Pop error message and error handler
165                 throw ModError("Failed to load and run script from " +
166                                 script_path + ":\n" + error_msg);
167         }
168         lua_pop(L, 1); // Pop error handler
169 }
170
171 // Push the list of callbacks (a lua table).
172 // Then push nargs arguments.
173 // Then call this function, which
174 // - runs the callbacks
175 // - replaces the table and arguments with the return value,
176 //     computed depending on mode
177 // This function must only be called with scriptlock held (i.e. inside of a
178 // code block with SCRIPTAPI_PRECHECKHEADER declared)
179 void ScriptApiBase::runCallbacksRaw(int nargs,
180                 RunCallbacksMode mode, const char *fxn)
181 {
182 #ifdef SCRIPTAPI_LOCK_DEBUG
183         assert(m_lock_recursion_count > 0);
184 #endif
185         lua_State *L = getStack();
186         FATAL_ERROR_IF(lua_gettop(L) < nargs + 1, "Not enough arguments");
187
188         // Insert error handler
189         PUSH_ERROR_HANDLER(L);
190         int error_handler = lua_gettop(L) - nargs - 1;
191         lua_insert(L, error_handler);
192
193         // Insert run_callbacks between error handler and table
194         lua_getglobal(L, "core");
195         lua_getfield(L, -1, "run_callbacks");
196         lua_remove(L, -2);
197         lua_insert(L, error_handler + 1);
198
199         // Insert mode after table
200         lua_pushnumber(L, (int)mode);
201         lua_insert(L, error_handler + 3);
202
203         // Stack now looks like this:
204         // ... <error handler> <run_callbacks> <table> <mode> <arg#1> <arg#2> ... <arg#n>
205
206         int result = lua_pcall(L, nargs + 2, 1, error_handler);
207         if (result != 0)
208                 scriptError(result, fxn);
209
210         lua_remove(L, error_handler);
211 }
212
213 void ScriptApiBase::realityCheck()
214 {
215         int top = lua_gettop(m_luastack);
216         if (top >= 30) {
217                 dstream << "Stack is over 30:" << std::endl;
218                 stackDump(dstream);
219                 std::string traceback = script_get_backtrace(m_luastack);
220                 throw LuaError("Stack is over 30 (reality check)\n" + traceback);
221         }
222 }
223
224 void ScriptApiBase::scriptError(int result, const char *fxn)
225 {
226         script_error(getStack(), result, m_last_run_mod.c_str(), fxn);
227 }
228
229 void ScriptApiBase::stackDump(std::ostream &o)
230 {
231         int top = lua_gettop(m_luastack);
232         for (int i = 1; i <= top; i++) {  /* repeat for each level */
233                 int t = lua_type(m_luastack, i);
234                 switch (t) {
235                         case LUA_TSTRING:  /* strings */
236                                 o << "\"" << lua_tostring(m_luastack, i) << "\"";
237                                 break;
238                         case LUA_TBOOLEAN:  /* booleans */
239                                 o << (lua_toboolean(m_luastack, i) ? "true" : "false");
240                                 break;
241                         case LUA_TNUMBER:  /* numbers */ {
242                                 char buf[10];
243                                 snprintf(buf, 10, "%lf", lua_tonumber(m_luastack, i));
244                                 o << buf;
245                                 break;
246                         }
247                         default:  /* other values */
248                                 o << lua_typename(m_luastack, t);
249                                 break;
250                 }
251                 o << " ";
252         }
253         o << std::endl;
254 }
255
256 void ScriptApiBase::setOriginDirect(const char *origin)
257 {
258         m_last_run_mod = origin ? origin : "??";
259 }
260
261 void ScriptApiBase::setOriginFromTableRaw(int index, const char *fxn)
262 {
263 #ifdef SCRIPTAPI_DEBUG
264         lua_State *L = getStack();
265
266         m_last_run_mod = lua_istable(L, index) ?
267                 getstringfield_default(L, index, "mod_origin", "") : "";
268         //printf(">>>> running %s for mod: %s\n", fxn, m_last_run_mod.c_str());
269 #endif
270 }
271
272 void ScriptApiBase::addObjectReference(ServerActiveObject *cobj)
273 {
274         SCRIPTAPI_PRECHECKHEADER
275         //infostream<<"scriptapi_add_object_reference: id="<<cobj->getId()<<std::endl;
276
277         // Create object on stack
278         ObjectRef::create(L, cobj); // Puts ObjectRef (as userdata) on stack
279         int object = lua_gettop(L);
280
281         // Get core.object_refs table
282         lua_getglobal(L, "core");
283         lua_getfield(L, -1, "object_refs");
284         luaL_checktype(L, -1, LUA_TTABLE);
285         int objectstable = lua_gettop(L);
286
287         // object_refs[id] = object
288         lua_pushnumber(L, cobj->getId()); // Push id
289         lua_pushvalue(L, object); // Copy object to top of stack
290         lua_settable(L, objectstable);
291 }
292
293 void ScriptApiBase::removeObjectReference(ServerActiveObject *cobj)
294 {
295         SCRIPTAPI_PRECHECKHEADER
296         //infostream<<"scriptapi_rm_object_reference: id="<<cobj->getId()<<std::endl;
297
298         // Get core.object_refs table
299         lua_getglobal(L, "core");
300         lua_getfield(L, -1, "object_refs");
301         luaL_checktype(L, -1, LUA_TTABLE);
302         int objectstable = lua_gettop(L);
303
304         // Get object_refs[id]
305         lua_pushnumber(L, cobj->getId()); // Push id
306         lua_gettable(L, objectstable);
307         // Set object reference to NULL
308         ObjectRef::set_null(L);
309         lua_pop(L, 1); // pop object
310
311         // Set object_refs[id] = nil
312         lua_pushnumber(L, cobj->getId()); // Push id
313         lua_pushnil(L);
314         lua_settable(L, objectstable);
315 }
316
317 // Creates a new anonymous reference if cobj=NULL or id=0
318 void ScriptApiBase::objectrefGetOrCreate(lua_State *L,
319                 ServerActiveObject *cobj)
320 {
321         if (cobj == NULL || cobj->getId() == 0) {
322                 ObjectRef::create(L, cobj);
323         } else {
324                 push_objectRef(L, cobj->getId());
325         }
326 }
327
328 Server* ScriptApiBase::getServer()
329 {
330         return dynamic_cast<Server *>(m_gamedef);
331 }
332 #ifndef SERVER
333 Client* ScriptApiBase::getClient()
334 {
335         return dynamic_cast<Client *>(m_gamedef);
336 }
337 #endif