]> git.lizzy.rs Git - dragonfireclient.git/blob - src/scriptapi.cpp
Add one more curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
[dragonfireclient.git] / src / scriptapi.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 "scriptapi.h"
21
22 #include <iostream>
23 #include <list>
24 extern "C" {
25 #include <lua.h>
26 #include <lualib.h>
27 #include <lauxlib.h>
28 }
29
30 #include "log.h"
31 #include "server.h"
32 #include "porting.h"
33 #include "filesys.h"
34 #include "serverobject.h"
35 #include "script.h"
36 #include "object_properties.h"
37 #include "content_sao.h" // For LuaEntitySAO and PlayerSAO
38 #include "itemdef.h"
39 #include "nodedef.h"
40 #include "biome.h"
41 #include "craftdef.h"
42 #include "main.h" // For g_settings
43 #include "settings.h" // For accessing g_settings
44 #include "nodemetadata.h"
45 #include "mapblock.h" // For getNodeBlockPos
46 #include "content_nodemeta.h"
47 #include "tool.h"
48 #include "daynightratio.h"
49 #include "noise.h" // PseudoRandom for LuaPseudoRandom
50 #include "util/pointedthing.h"
51 #include "rollback.h"
52 #include "treegen.h"
53
54 static void stackDump(lua_State *L, std::ostream &o)
55 {
56   int i;
57   int top = lua_gettop(L);
58   for (i = 1; i <= top; i++) {  /* repeat for each level */
59         int t = lua_type(L, i);
60         switch (t) {
61
62           case LUA_TSTRING:  /* strings */
63                 o<<"\""<<lua_tostring(L, i)<<"\"";
64                 break;
65
66           case LUA_TBOOLEAN:  /* booleans */
67                 o<<(lua_toboolean(L, i) ? "true" : "false");
68                 break;
69
70           case LUA_TNUMBER:  /* numbers */ {
71                 char buf[10];
72                 snprintf(buf, 10, "%g", lua_tonumber(L, i));
73                 o<<buf;
74                 break; }
75
76           default:  /* other values */
77                 o<<lua_typename(L, t);
78                 break;
79
80         }
81         o<<" ";
82   }
83   o<<std::endl;
84 }
85
86 static void realitycheck(lua_State *L)
87 {
88         int top = lua_gettop(L);
89         if(top >= 30){
90                 dstream<<"Stack is over 30:"<<std::endl;
91                 stackDump(L, dstream);
92                 script_error(L, "Stack is over 30 (reality check)");
93         }
94 }
95
96 class StackUnroller
97 {
98 private:
99         lua_State *m_lua;
100         int m_original_top;
101 public:
102         StackUnroller(lua_State *L):
103                 m_lua(L),
104                 m_original_top(-1)
105         {
106                 m_original_top = lua_gettop(m_lua); // store stack height
107         }
108         ~StackUnroller()
109         {
110                 lua_settop(m_lua, m_original_top); // restore stack height
111         }
112 };
113
114 class ModNameStorer
115 {
116 private:
117         lua_State *L;
118 public:
119         ModNameStorer(lua_State *L_, const std::string modname):
120                 L(L_)
121         {
122                 // Store current modname in registry
123                 lua_pushstring(L, modname.c_str());
124                 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_current_modname");
125         }
126         ~ModNameStorer()
127         {
128                 // Clear current modname in registry
129                 lua_pushnil(L);
130                 lua_setfield(L, LUA_REGISTRYINDEX, "minetest_current_modname");
131         }
132 };
133
134 /*
135         Getters for stuff in main tables
136 */
137
138 static Server* get_server(lua_State *L)
139 {
140         // Get server from registry
141         lua_getfield(L, LUA_REGISTRYINDEX, "minetest_server");
142         Server *server = (Server*)lua_touserdata(L, -1);
143         lua_pop(L, 1);
144         return server;
145 }
146
147 static ServerEnvironment* get_env(lua_State *L)
148 {
149         // Get environment from registry
150         lua_getfield(L, LUA_REGISTRYINDEX, "minetest_env");
151         ServerEnvironment *env = (ServerEnvironment*)lua_touserdata(L, -1);
152         lua_pop(L, 1);
153         return env;
154 }
155
156 static void objectref_get(lua_State *L, u16 id)
157 {
158         // Get minetest.object_refs[i]
159         lua_getglobal(L, "minetest");
160         lua_getfield(L, -1, "object_refs");
161         luaL_checktype(L, -1, LUA_TTABLE);
162         lua_pushnumber(L, id);
163         lua_gettable(L, -2);
164         lua_remove(L, -2); // object_refs
165         lua_remove(L, -2); // minetest
166 }
167
168 static void luaentity_get(lua_State *L, u16 id)
169 {
170         // Get minetest.luaentities[i]
171         lua_getglobal(L, "minetest");
172         lua_getfield(L, -1, "luaentities");
173         luaL_checktype(L, -1, LUA_TTABLE);
174         lua_pushnumber(L, id);
175         lua_gettable(L, -2);
176         lua_remove(L, -2); // luaentities
177         lua_remove(L, -2); // minetest
178 }
179
180 /*
181         Table field getters
182 */
183
184 static bool getstringfield(lua_State *L, int table,
185                 const char *fieldname, std::string &result)
186 {
187         lua_getfield(L, table, fieldname);
188         bool got = false;
189         if(lua_isstring(L, -1)){
190                 size_t len = 0;
191                 const char *ptr = lua_tolstring(L, -1, &len);
192                 result.assign(ptr, len);
193                 got = true;
194         }
195         lua_pop(L, 1);
196         return got;
197 }
198
199 static bool getintfield(lua_State *L, int table,
200                 const char *fieldname, int &result)
201 {
202         lua_getfield(L, table, fieldname);
203         bool got = false;
204         if(lua_isnumber(L, -1)){
205                 result = lua_tonumber(L, -1);
206                 got = true;
207         }
208         lua_pop(L, 1);
209         return got;
210 }
211
212 static bool getfloatfield(lua_State *L, int table,
213                 const char *fieldname, float &result)
214 {
215         lua_getfield(L, table, fieldname);
216         bool got = false;
217         if(lua_isnumber(L, -1)){
218                 result = lua_tonumber(L, -1);
219                 got = true;
220         }
221         lua_pop(L, 1);
222         return got;
223 }
224
225 static bool getboolfield(lua_State *L, int table,
226                 const char *fieldname, bool &result)
227 {
228         lua_getfield(L, table, fieldname);
229         bool got = false;
230         if(lua_isboolean(L, -1)){
231                 result = lua_toboolean(L, -1);
232                 got = true;
233         }
234         lua_pop(L, 1);
235         return got;
236 }
237
238 static std::string checkstringfield(lua_State *L, int table,
239                 const char *fieldname)
240 {
241         lua_getfield(L, table, fieldname);
242         std::string s = luaL_checkstring(L, -1);
243         lua_pop(L, 1);
244         return s;
245 }
246
247 static std::string getstringfield_default(lua_State *L, int table,
248                 const char *fieldname, const std::string &default_)
249 {
250         std::string result = default_;
251         getstringfield(L, table, fieldname, result);
252         return result;
253 }
254
255 static int getintfield_default(lua_State *L, int table,
256                 const char *fieldname, int default_)
257 {
258         int result = default_;
259         getintfield(L, table, fieldname, result);
260         return result;
261 }
262
263 static float getfloatfield_default(lua_State *L, int table,
264                 const char *fieldname, float default_)
265 {
266         float result = default_;
267         getfloatfield(L, table, fieldname, result);
268         return result;
269 }
270
271 static bool getboolfield_default(lua_State *L, int table,
272                 const char *fieldname, bool default_)
273 {
274         bool result = default_;
275         getboolfield(L, table, fieldname, result);
276         return result;
277 }
278
279 struct EnumString
280 {
281         int num;
282         const char *str;
283 };
284
285 static bool string_to_enum(const EnumString *spec, int &result,
286                 const std::string &str)
287 {
288         const EnumString *esp = spec;
289         while(esp->str){
290                 if(str == std::string(esp->str)){
291                         result = esp->num;
292                         return true;
293                 }
294                 esp++;
295         }
296         return false;
297 }
298
299 /*static bool enum_to_string(const EnumString *spec, std::string &result,
300                 int num)
301 {
302         const EnumString *esp = spec;
303         while(esp){
304                 if(num == esp->num){
305                         result = esp->str;
306                         return true;
307                 }
308                 esp++;
309         }
310         return false;
311 }*/
312
313 static int getenumfield(lua_State *L, int table,
314                 const char *fieldname, const EnumString *spec, int default_)
315 {
316         int result = default_;
317         string_to_enum(spec, result,
318                         getstringfield_default(L, table, fieldname, ""));
319         return result;
320 }
321
322 static void setintfield(lua_State *L, int table,
323                 const char *fieldname, int value)
324 {
325         lua_pushinteger(L, value);
326         if(table < 0)
327                 table -= 1;
328         lua_setfield(L, table, fieldname);
329 }
330
331 static void setfloatfield(lua_State *L, int table,
332                 const char *fieldname, float value)
333 {
334         lua_pushnumber(L, value);
335         if(table < 0)
336                 table -= 1;
337         lua_setfield(L, table, fieldname);
338 }
339
340 static void setboolfield(lua_State *L, int table,
341                 const char *fieldname, bool value)
342 {
343         lua_pushboolean(L, value);
344         if(table < 0)
345                 table -= 1;
346         lua_setfield(L, table, fieldname);
347 }
348
349 static void warn_if_field_exists(lua_State *L, int table,
350                 const char *fieldname, const std::string &message)
351 {
352         lua_getfield(L, table, fieldname);
353         if(!lua_isnil(L, -1)){
354                 infostream<<script_get_backtrace(L)<<std::endl;
355                 infostream<<"WARNING: field \""<<fieldname<<"\": "
356                                 <<message<<std::endl;
357         }
358         lua_pop(L, 1);
359 }
360
361 /*
362         EnumString definitions
363 */
364
365 struct EnumString es_ItemType[] =
366 {
367         {ITEM_NONE, "none"},
368         {ITEM_NODE, "node"},
369         {ITEM_CRAFT, "craft"},
370         {ITEM_TOOL, "tool"},
371         {0, NULL},
372 };
373
374 struct EnumString es_DrawType[] =
375 {
376         {NDT_NORMAL, "normal"},
377         {NDT_AIRLIKE, "airlike"},
378         {NDT_LIQUID, "liquid"},
379         {NDT_FLOWINGLIQUID, "flowingliquid"},
380         {NDT_GLASSLIKE, "glasslike"},
381         {NDT_ALLFACES, "allfaces"},
382         {NDT_ALLFACES_OPTIONAL, "allfaces_optional"},
383         {NDT_TORCHLIKE, "torchlike"},
384         {NDT_SIGNLIKE, "signlike"},
385         {NDT_PLANTLIKE, "plantlike"},
386         {NDT_FENCELIKE, "fencelike"},
387         {NDT_RAILLIKE, "raillike"},
388         {NDT_NODEBOX, "nodebox"},
389         {0, NULL},
390 };
391
392 struct EnumString es_ContentParamType[] =
393 {
394         {CPT_NONE, "none"},
395         {CPT_LIGHT, "light"},
396         {0, NULL},
397 };
398
399 struct EnumString es_ContentParamType2[] =
400 {
401         {CPT2_NONE, "none"},
402         {CPT2_FULL, "full"},
403         {CPT2_FLOWINGLIQUID, "flowingliquid"},
404         {CPT2_FACEDIR, "facedir"},
405         {CPT2_WALLMOUNTED, "wallmounted"},
406         {0, NULL},
407 };
408
409 struct EnumString es_LiquidType[] =
410 {
411         {LIQUID_NONE, "none"},
412         {LIQUID_FLOWING, "flowing"},
413         {LIQUID_SOURCE, "source"},
414         {0, NULL},
415 };
416
417 struct EnumString es_NodeBoxType[] =
418 {
419         {NODEBOX_REGULAR, "regular"},
420         {NODEBOX_FIXED, "fixed"},
421         {NODEBOX_WALLMOUNTED, "wallmounted"},
422         {0, NULL},
423 };
424
425 struct EnumString es_CraftMethod[] =
426 {
427         {CRAFT_METHOD_NORMAL, "normal"},
428         {CRAFT_METHOD_COOKING, "cooking"},
429         {CRAFT_METHOD_FUEL, "fuel"},
430         {0, NULL},
431 };
432
433 struct EnumString es_TileAnimationType[] =
434 {
435         {TAT_NONE, "none"},
436         {TAT_VERTICAL_FRAMES, "vertical_frames"},
437         {0, NULL},
438 };
439
440 struct EnumString es_BiomeTerrainType[] =
441 {
442         {BIOME_TERRAIN_NORMAL, "normal"},
443         {BIOME_TERRAIN_LIQUID, "liquid"},
444         {BIOME_TERRAIN_NETHER, "nether"},
445         {BIOME_TERRAIN_AETHER, "aether"},
446         {BIOME_TERRAIN_FLAT,   "flat"},
447         {0, NULL},
448 };
449
450 /*
451         C struct <-> Lua table converter functions
452 */
453
454 static void push_v3f(lua_State *L, v3f p)
455 {
456         lua_newtable(L);
457         lua_pushnumber(L, p.X);
458         lua_setfield(L, -2, "x");
459         lua_pushnumber(L, p.Y);
460         lua_setfield(L, -2, "y");
461         lua_pushnumber(L, p.Z);
462         lua_setfield(L, -2, "z");
463 }
464
465 static v2s16 read_v2s16(lua_State *L, int index)
466 {
467         v2s16 p;
468         luaL_checktype(L, index, LUA_TTABLE);
469         lua_getfield(L, index, "x");
470         p.X = lua_tonumber(L, -1);
471         lua_pop(L, 1);
472         lua_getfield(L, index, "y");
473         p.Y = lua_tonumber(L, -1);
474         lua_pop(L, 1);
475         return p;
476 }
477
478 static v2f read_v2f(lua_State *L, int index)
479 {
480         v2f p;
481         luaL_checktype(L, index, LUA_TTABLE);
482         lua_getfield(L, index, "x");
483         p.X = lua_tonumber(L, -1);
484         lua_pop(L, 1);
485         lua_getfield(L, index, "y");
486         p.Y = lua_tonumber(L, -1);
487         lua_pop(L, 1);
488         return p;
489 }
490
491 static v3f read_v3f(lua_State *L, int index)
492 {
493         v3f pos;
494         luaL_checktype(L, index, LUA_TTABLE);
495         lua_getfield(L, index, "x");
496         pos.X = lua_tonumber(L, -1);
497         lua_pop(L, 1);
498         lua_getfield(L, index, "y");
499         pos.Y = lua_tonumber(L, -1);
500         lua_pop(L, 1);
501         lua_getfield(L, index, "z");
502         pos.Z = lua_tonumber(L, -1);
503         lua_pop(L, 1);
504         return pos;
505 }
506
507 static v3f check_v3f(lua_State *L, int index)
508 {
509         v3f pos;
510         luaL_checktype(L, index, LUA_TTABLE);
511         lua_getfield(L, index, "x");
512         pos.X = luaL_checknumber(L, -1);
513         lua_pop(L, 1);
514         lua_getfield(L, index, "y");
515         pos.Y = luaL_checknumber(L, -1);
516         lua_pop(L, 1);
517         lua_getfield(L, index, "z");
518         pos.Z = luaL_checknumber(L, -1);
519         lua_pop(L, 1);
520         return pos;
521 }
522
523 static void pushFloatPos(lua_State *L, v3f p)
524 {
525         p /= BS;
526         push_v3f(L, p);
527 }
528
529 static v3f checkFloatPos(lua_State *L, int index)
530 {
531         return check_v3f(L, index) * BS;
532 }
533
534 static void push_v3s16(lua_State *L, v3s16 p)
535 {
536         lua_newtable(L);
537         lua_pushnumber(L, p.X);
538         lua_setfield(L, -2, "x");
539         lua_pushnumber(L, p.Y);
540         lua_setfield(L, -2, "y");
541         lua_pushnumber(L, p.Z);
542         lua_setfield(L, -2, "z");
543 }
544
545 static v3s16 read_v3s16(lua_State *L, int index)
546 {
547         // Correct rounding at <0
548         v3f pf = read_v3f(L, index);
549         return floatToInt(pf, 1.0);
550 }
551
552 static v3s16 check_v3s16(lua_State *L, int index)
553 {
554         // Correct rounding at <0
555         v3f pf = check_v3f(L, index);
556         return floatToInt(pf, 1.0);
557 }
558
559 static void pushnode(lua_State *L, const MapNode &n, INodeDefManager *ndef)
560 {
561         lua_newtable(L);
562         lua_pushstring(L, ndef->get(n).name.c_str());
563         lua_setfield(L, -2, "name");
564         lua_pushnumber(L, n.getParam1());
565         lua_setfield(L, -2, "param1");
566         lua_pushnumber(L, n.getParam2());
567         lua_setfield(L, -2, "param2");
568 }
569
570 static MapNode readnode(lua_State *L, int index, INodeDefManager *ndef)
571 {
572         lua_getfield(L, index, "name");
573         const char *name = luaL_checkstring(L, -1);
574         lua_pop(L, 1);
575         u8 param1;
576         lua_getfield(L, index, "param1");
577         if(lua_isnil(L, -1))
578                 param1 = 0;
579         else
580                 param1 = lua_tonumber(L, -1);
581         lua_pop(L, 1);
582         u8 param2;
583         lua_getfield(L, index, "param2");
584         if(lua_isnil(L, -1))
585                 param2 = 0;
586         else
587                 param2 = lua_tonumber(L, -1);
588         lua_pop(L, 1);
589         return MapNode(ndef, name, param1, param2);
590 }
591
592 static video::SColor readARGB8(lua_State *L, int index)
593 {
594         video::SColor color;
595         luaL_checktype(L, index, LUA_TTABLE);
596         lua_getfield(L, index, "a");
597         if(lua_isnumber(L, -1))
598                 color.setAlpha(lua_tonumber(L, -1));
599         lua_pop(L, 1);
600         lua_getfield(L, index, "r");
601         color.setRed(lua_tonumber(L, -1));
602         lua_pop(L, 1);
603         lua_getfield(L, index, "g");
604         color.setGreen(lua_tonumber(L, -1));
605         lua_pop(L, 1);
606         lua_getfield(L, index, "b");
607         color.setBlue(lua_tonumber(L, -1));
608         lua_pop(L, 1);
609         return color;
610 }
611
612 static aabb3f read_aabb3f(lua_State *L, int index, f32 scale)
613 {
614         aabb3f box;
615         if(lua_istable(L, index)){
616                 lua_rawgeti(L, index, 1);
617                 box.MinEdge.X = lua_tonumber(L, -1) * scale;
618                 lua_pop(L, 1);
619                 lua_rawgeti(L, index, 2);
620                 box.MinEdge.Y = lua_tonumber(L, -1) * scale;
621                 lua_pop(L, 1);
622                 lua_rawgeti(L, index, 3);
623                 box.MinEdge.Z = lua_tonumber(L, -1) * scale;
624                 lua_pop(L, 1);
625                 lua_rawgeti(L, index, 4);
626                 box.MaxEdge.X = lua_tonumber(L, -1) * scale;
627                 lua_pop(L, 1);
628                 lua_rawgeti(L, index, 5);
629                 box.MaxEdge.Y = lua_tonumber(L, -1) * scale;
630                 lua_pop(L, 1);
631                 lua_rawgeti(L, index, 6);
632                 box.MaxEdge.Z = lua_tonumber(L, -1) * scale;
633                 lua_pop(L, 1);
634         }
635         return box;
636 }
637
638 static std::vector<aabb3f> read_aabb3f_vector(lua_State *L, int index, f32 scale)
639 {
640         std::vector<aabb3f> boxes;
641         if(lua_istable(L, index)){
642                 int n = lua_objlen(L, index);
643                 // Check if it's a single box or a list of boxes
644                 bool possibly_single_box = (n == 6);
645                 for(int i = 1; i <= n && possibly_single_box; i++){
646                         lua_rawgeti(L, index, i);
647                         if(!lua_isnumber(L, -1))
648                                 possibly_single_box = false;
649                         lua_pop(L, 1);
650                 }
651                 if(possibly_single_box){
652                         // Read a single box
653                         boxes.push_back(read_aabb3f(L, index, scale));
654                 } else {
655                         // Read a list of boxes
656                         for(int i = 1; i <= n; i++){
657                                 lua_rawgeti(L, index, i);
658                                 boxes.push_back(read_aabb3f(L, -1, scale));
659                                 lua_pop(L, 1);
660                         }
661                 }
662         }
663         return boxes;
664 }
665
666 static NodeBox read_nodebox(lua_State *L, int index)
667 {
668         NodeBox nodebox;
669         if(lua_istable(L, -1)){
670                 nodebox.type = (NodeBoxType)getenumfield(L, index, "type",
671                                 es_NodeBoxType, NODEBOX_REGULAR);
672
673                 lua_getfield(L, index, "fixed");
674                 if(lua_istable(L, -1))
675                         nodebox.fixed = read_aabb3f_vector(L, -1, BS);
676                 lua_pop(L, 1);
677
678                 lua_getfield(L, index, "wall_top");
679                 if(lua_istable(L, -1))
680                         nodebox.wall_top = read_aabb3f(L, -1, BS);
681                 lua_pop(L, 1);
682
683                 lua_getfield(L, index, "wall_bottom");
684                 if(lua_istable(L, -1))
685                         nodebox.wall_bottom = read_aabb3f(L, -1, BS);
686                 lua_pop(L, 1);
687
688                 lua_getfield(L, index, "wall_side");
689                 if(lua_istable(L, -1))
690                         nodebox.wall_side = read_aabb3f(L, -1, BS);
691                 lua_pop(L, 1);
692         }
693         return nodebox;
694 }
695
696 /*
697         NoiseParams
698 */
699 static NoiseParams *read_noiseparams(lua_State *L, int index)
700 {
701         if (index < 0)
702                 index = lua_gettop(L) + 1 + index;
703                 
704         if (!lua_istable(L, index))
705                 return NULL;
706
707         NoiseParams *np = new NoiseParams;
708                 
709         np->offset  = getfloatfield_default(L, index, "offset", 0.0);
710         np->scale   = getfloatfield_default(L, index, "scale", 0.0);
711         lua_getfield(L, index, "spread");
712         np->spread  = read_v3f(L, -1);
713         np->seed    = getintfield_default(L, index, "seed", 0);
714         np->octaves = getintfield_default(L, index, "octaves", 0);
715         np->persist = getfloatfield_default(L, index, "persist", 0.0);
716         
717         return np;
718 }
719
720 /*
721         Groups
722 */
723 static void read_groups(lua_State *L, int index,
724                 std::map<std::string, int> &result)
725 {
726         if (!lua_istable(L,index))
727                 return;
728         result.clear();
729         lua_pushnil(L);
730         if(index < 0)
731                 index -= 1;
732         while(lua_next(L, index) != 0){
733                 // key at index -2 and value at index -1
734                 std::string name = luaL_checkstring(L, -2);
735                 int rating = luaL_checkinteger(L, -1);
736                 result[name] = rating;
737                 // removes value, keeps key for next iteration
738                 lua_pop(L, 1);
739         }
740 }
741
742 /*
743         Privileges
744 */
745 static void read_privileges(lua_State *L, int index,
746                 std::set<std::string> &result)
747 {
748         result.clear();
749         lua_pushnil(L);
750         if(index < 0)
751                 index -= 1;
752         while(lua_next(L, index) != 0){
753                 // key at index -2 and value at index -1
754                 std::string key = luaL_checkstring(L, -2);
755                 bool value = lua_toboolean(L, -1);
756                 if(value)
757                         result.insert(key);
758                 // removes value, keeps key for next iteration
759                 lua_pop(L, 1);
760         }
761 }
762
763 /*
764         ToolCapabilities
765 */
766
767 static ToolCapabilities read_tool_capabilities(
768                 lua_State *L, int table)
769 {
770         ToolCapabilities toolcap;
771         getfloatfield(L, table, "full_punch_interval", toolcap.full_punch_interval);
772         getintfield(L, table, "max_drop_level", toolcap.max_drop_level);
773         lua_getfield(L, table, "groupcaps");
774         if(lua_istable(L, -1)){
775                 int table_groupcaps = lua_gettop(L);
776                 lua_pushnil(L);
777                 while(lua_next(L, table_groupcaps) != 0){
778                         // key at index -2 and value at index -1
779                         std::string groupname = luaL_checkstring(L, -2);
780                         if(lua_istable(L, -1)){
781                                 int table_groupcap = lua_gettop(L);
782                                 // This will be created
783                                 ToolGroupCap groupcap;
784                                 // Read simple parameters
785                                 getintfield(L, table_groupcap, "maxlevel", groupcap.maxlevel);
786                                 getintfield(L, table_groupcap, "uses", groupcap.uses);
787                                 // DEPRECATED: maxwear
788                                 float maxwear = 0;
789                                 if(getfloatfield(L, table_groupcap, "maxwear", maxwear)){
790                                         if(maxwear != 0)
791                                                 groupcap.uses = 1.0/maxwear;
792                                         else
793                                                 groupcap.uses = 0;
794                                         infostream<<script_get_backtrace(L)<<std::endl;
795                                         infostream<<"WARNING: field \"maxwear\" is deprecated; "
796                                                         <<"should replace with uses=1/maxwear"<<std::endl;
797                                 }
798                                 // Read "times" table
799                                 lua_getfield(L, table_groupcap, "times");
800                                 if(lua_istable(L, -1)){
801                                         int table_times = lua_gettop(L);
802                                         lua_pushnil(L);
803                                         while(lua_next(L, table_times) != 0){
804                                                 // key at index -2 and value at index -1
805                                                 int rating = luaL_checkinteger(L, -2);
806                                                 float time = luaL_checknumber(L, -1);
807                                                 groupcap.times[rating] = time;
808                                                 // removes value, keeps key for next iteration
809                                                 lua_pop(L, 1);
810                                         }
811                                 }
812                                 lua_pop(L, 1);
813                                 // Insert groupcap into toolcap
814                                 toolcap.groupcaps[groupname] = groupcap;
815                         }
816                         // removes value, keeps key for next iteration
817                         lua_pop(L, 1);
818                 }
819         }
820         lua_pop(L, 1);
821         return toolcap;
822 }
823
824 static void set_tool_capabilities(lua_State *L, int table,
825                 const ToolCapabilities &toolcap)
826 {
827         setfloatfield(L, table, "full_punch_interval", toolcap.full_punch_interval);
828         setintfield(L, table, "max_drop_level", toolcap.max_drop_level);
829         // Create groupcaps table
830         lua_newtable(L);
831         // For each groupcap
832         for(std::map<std::string, ToolGroupCap>::const_iterator
833                         i = toolcap.groupcaps.begin(); i != toolcap.groupcaps.end(); i++){
834                 // Create groupcap table
835                 lua_newtable(L);
836                 const std::string &name = i->first;
837                 const ToolGroupCap &groupcap = i->second;
838                 // Create subtable "times"
839                 lua_newtable(L);
840                 for(std::map<int, float>::const_iterator
841                                 i = groupcap.times.begin(); i != groupcap.times.end(); i++){
842                         int rating = i->first;
843                         float time = i->second;
844                         lua_pushinteger(L, rating);
845                         lua_pushnumber(L, time);
846                         lua_settable(L, -3);
847                 }
848                 // Set subtable "times"
849                 lua_setfield(L, -2, "times");
850                 // Set simple parameters
851                 setintfield(L, -1, "maxlevel", groupcap.maxlevel);
852                 setintfield(L, -1, "uses", groupcap.uses);
853                 // Insert groupcap table into groupcaps table
854                 lua_setfield(L, -2, name.c_str());
855         }
856         // Set groupcaps table
857         lua_setfield(L, -2, "groupcaps");
858 }
859
860 static void push_tool_capabilities(lua_State *L,
861                 const ToolCapabilities &prop)
862 {
863         lua_newtable(L);
864         set_tool_capabilities(L, -1, prop);
865 }
866
867 /*
868         DigParams
869 */
870
871 static void set_dig_params(lua_State *L, int table,
872                 const DigParams &params)
873 {
874         setboolfield(L, table, "diggable", params.diggable);
875         setfloatfield(L, table, "time", params.time);
876         setintfield(L, table, "wear", params.wear);
877 }
878
879 static void push_dig_params(lua_State *L,
880                 const DigParams &params)
881 {
882         lua_newtable(L);
883         set_dig_params(L, -1, params);
884 }
885
886 /*
887         HitParams
888 */
889
890 static void set_hit_params(lua_State *L, int table,
891                 const HitParams &params)
892 {
893         setintfield(L, table, "hp", params.hp);
894         setintfield(L, table, "wear", params.wear);
895 }
896
897 static void push_hit_params(lua_State *L,
898                 const HitParams &params)
899 {
900         lua_newtable(L);
901         set_hit_params(L, -1, params);
902 }
903
904 /*
905         PointedThing
906 */
907
908 static void push_pointed_thing(lua_State *L, const PointedThing& pointed)
909 {
910         lua_newtable(L);
911         if(pointed.type == POINTEDTHING_NODE)
912         {
913                 lua_pushstring(L, "node");
914                 lua_setfield(L, -2, "type");
915                 push_v3s16(L, pointed.node_undersurface);
916                 lua_setfield(L, -2, "under");
917                 push_v3s16(L, pointed.node_abovesurface);
918                 lua_setfield(L, -2, "above");
919         }
920         else if(pointed.type == POINTEDTHING_OBJECT)
921         {
922                 lua_pushstring(L, "object");
923                 lua_setfield(L, -2, "type");
924                 objectref_get(L, pointed.object_id);
925                 lua_setfield(L, -2, "ref");
926         }
927         else
928         {
929                 lua_pushstring(L, "nothing");
930                 lua_setfield(L, -2, "type");
931         }
932 }
933
934 /*
935         SimpleSoundSpec
936 */
937
938 static void read_soundspec(lua_State *L, int index, SimpleSoundSpec &spec)
939 {
940         if(index < 0)
941                 index = lua_gettop(L) + 1 + index;
942         if(lua_isnil(L, index)){
943         } else if(lua_istable(L, index)){
944                 getstringfield(L, index, "name", spec.name);
945                 getfloatfield(L, index, "gain", spec.gain);
946         } else if(lua_isstring(L, index)){
947                 spec.name = lua_tostring(L, index);
948         }
949 }
950
951 /*
952         ObjectProperties
953 */
954
955 static void read_object_properties(lua_State *L, int index,
956                 ObjectProperties *prop)
957 {
958         if(index < 0)
959                 index = lua_gettop(L) + 1 + index;
960         if(!lua_istable(L, index))
961                 return;
962
963         prop->hp_max = getintfield_default(L, -1, "hp_max", 10);
964
965         getboolfield(L, -1, "physical", prop->physical);
966
967         getfloatfield(L, -1, "weight", prop->weight);
968
969         lua_getfield(L, -1, "collisionbox");
970         if(lua_istable(L, -1))
971                 prop->collisionbox = read_aabb3f(L, -1, 1.0);
972         lua_pop(L, 1);
973
974         getstringfield(L, -1, "visual", prop->visual);
975
976         getstringfield(L, -1, "mesh", prop->mesh);
977         
978         lua_getfield(L, -1, "visual_size");
979         if(lua_istable(L, -1))
980                 prop->visual_size = read_v2f(L, -1);
981         lua_pop(L, 1);
982
983         lua_getfield(L, -1, "textures");
984         if(lua_istable(L, -1)){
985                 prop->textures.clear();
986                 int table = lua_gettop(L);
987                 lua_pushnil(L);
988                 while(lua_next(L, table) != 0){
989                         // key at index -2 and value at index -1
990                         if(lua_isstring(L, -1))
991                                 prop->textures.push_back(lua_tostring(L, -1));
992                         else
993                                 prop->textures.push_back("");
994                         // removes value, keeps key for next iteration
995                         lua_pop(L, 1);
996                 }
997         }
998         lua_pop(L, 1);
999
1000         lua_getfield(L, -1, "colors");
1001         if(lua_istable(L, -1)){
1002                 prop->colors.clear();
1003                 int table = lua_gettop(L);
1004                 lua_pushnil(L);
1005                 while(lua_next(L, table) != 0){
1006                         // key at index -2 and value at index -1
1007                         if(lua_isstring(L, -1))
1008                                 prop->colors.push_back(readARGB8(L, -1));
1009                         else
1010                                 prop->colors.push_back(video::SColor(255, 255, 255, 255));
1011                         // removes value, keeps key for next iteration
1012                         lua_pop(L, 1);
1013                 }
1014         }
1015         lua_pop(L, 1);
1016         
1017         lua_getfield(L, -1, "spritediv");
1018         if(lua_istable(L, -1))
1019                 prop->spritediv = read_v2s16(L, -1);
1020         lua_pop(L, 1);
1021
1022         lua_getfield(L, -1, "initial_sprite_basepos");
1023         if(lua_istable(L, -1))
1024                 prop->initial_sprite_basepos = read_v2s16(L, -1);
1025         lua_pop(L, 1);
1026
1027         getboolfield(L, -1, "is_visible", prop->is_visible);
1028         getboolfield(L, -1, "makes_footstep_sound", prop->makes_footstep_sound);
1029         getfloatfield(L, -1, "automatic_rotate", prop->automatic_rotate);
1030 }
1031
1032 /*
1033         ItemDefinition
1034 */
1035
1036 static ItemDefinition read_item_definition(lua_State *L, int index,
1037                 ItemDefinition default_def = ItemDefinition())
1038 {
1039         if(index < 0)
1040                 index = lua_gettop(L) + 1 + index;
1041
1042         // Read the item definition
1043         ItemDefinition def = default_def;
1044
1045         def.type = (ItemType)getenumfield(L, index, "type",
1046                         es_ItemType, ITEM_NONE);
1047         getstringfield(L, index, "name", def.name);
1048         getstringfield(L, index, "description", def.description);
1049         getstringfield(L, index, "inventory_image", def.inventory_image);
1050         getstringfield(L, index, "wield_image", def.wield_image);
1051
1052         lua_getfield(L, index, "wield_scale");
1053         if(lua_istable(L, -1)){
1054                 def.wield_scale = check_v3f(L, -1);
1055         }
1056         lua_pop(L, 1);
1057
1058         def.stack_max = getintfield_default(L, index, "stack_max", def.stack_max);
1059         if(def.stack_max == 0)
1060                 def.stack_max = 1;
1061
1062         lua_getfield(L, index, "on_use");
1063         def.usable = lua_isfunction(L, -1);
1064         lua_pop(L, 1);
1065
1066         getboolfield(L, index, "liquids_pointable", def.liquids_pointable);
1067
1068         warn_if_field_exists(L, index, "tool_digging_properties",
1069                         "deprecated: use tool_capabilities");
1070
1071         lua_getfield(L, index, "tool_capabilities");
1072         if(lua_istable(L, -1)){
1073                 def.tool_capabilities = new ToolCapabilities(
1074                                 read_tool_capabilities(L, -1));
1075         }
1076
1077         // If name is "" (hand), ensure there are ToolCapabilities
1078         // because it will be looked up there whenever any other item has
1079         // no ToolCapabilities
1080         if(def.name == "" && def.tool_capabilities == NULL){
1081                 def.tool_capabilities = new ToolCapabilities();
1082         }
1083
1084         lua_getfield(L, index, "groups");
1085         read_groups(L, -1, def.groups);
1086         lua_pop(L, 1);
1087
1088         // Client shall immediately place this node when player places the item.
1089         // Server will update the precise end result a moment later.
1090         // "" = no prediction
1091         getstringfield(L, index, "node_placement_prediction",
1092                         def.node_placement_prediction);
1093
1094         return def;
1095 }
1096
1097 /*
1098         TileDef
1099 */
1100
1101 static TileDef read_tiledef(lua_State *L, int index)
1102 {
1103         if(index < 0)
1104                 index = lua_gettop(L) + 1 + index;
1105
1106         TileDef tiledef;
1107
1108         // key at index -2 and value at index
1109         if(lua_isstring(L, index)){
1110                 // "default_lava.png"
1111                 tiledef.name = lua_tostring(L, index);
1112         }
1113         else if(lua_istable(L, index))
1114         {
1115                 // {name="default_lava.png", animation={}}
1116                 tiledef.name = "";
1117                 getstringfield(L, index, "name", tiledef.name);
1118                 getstringfield(L, index, "image", tiledef.name); // MaterialSpec compat.
1119                 tiledef.backface_culling = getboolfield_default(
1120                                         L, index, "backface_culling", true);
1121                 // animation = {}
1122                 lua_getfield(L, index, "animation");
1123                 if(lua_istable(L, -1)){
1124                         // {type="vertical_frames", aspect_w=16, aspect_h=16, length=2.0}
1125                         tiledef.animation.type = (TileAnimationType)
1126                                         getenumfield(L, -1, "type", es_TileAnimationType,
1127                                         TAT_NONE);
1128                         tiledef.animation.aspect_w =
1129                                         getintfield_default(L, -1, "aspect_w", 16);
1130                         tiledef.animation.aspect_h =
1131                                         getintfield_default(L, -1, "aspect_h", 16);
1132                         tiledef.animation.length =
1133                                         getfloatfield_default(L, -1, "length", 1.0);
1134                 }
1135                 lua_pop(L, 1);
1136         }
1137
1138         return tiledef;
1139 }
1140
1141 /*
1142         ContentFeatures
1143 */
1144
1145 static ContentFeatures read_content_features(lua_State *L, int index)
1146 {
1147         if(index < 0)
1148                 index = lua_gettop(L) + 1 + index;
1149
1150         ContentFeatures f;
1151
1152         /* Cache existence of some callbacks */
1153         lua_getfield(L, index, "on_construct");
1154         if(!lua_isnil(L, -1)) f.has_on_construct = true;
1155         lua_pop(L, 1);
1156         lua_getfield(L, index, "on_destruct");
1157         if(!lua_isnil(L, -1)) f.has_on_destruct = true;
1158         lua_pop(L, 1);
1159         lua_getfield(L, index, "after_destruct");
1160         if(!lua_isnil(L, -1)) f.has_after_destruct = true;
1161         lua_pop(L, 1);
1162
1163         lua_getfield(L, index, "on_rightclick");
1164         f.rightclickable = lua_isfunction(L, -1);
1165         lua_pop(L, 1);
1166
1167         /* Name */
1168         getstringfield(L, index, "name", f.name);
1169
1170         /* Groups */
1171         lua_getfield(L, index, "groups");
1172         read_groups(L, -1, f.groups);
1173         lua_pop(L, 1);
1174
1175         /* Visual definition */
1176
1177         f.drawtype = (NodeDrawType)getenumfield(L, index, "drawtype", es_DrawType,
1178                         NDT_NORMAL);
1179         getfloatfield(L, index, "visual_scale", f.visual_scale);
1180
1181         // tiles = {}
1182         lua_getfield(L, index, "tiles");
1183         // If nil, try the deprecated name "tile_images" instead
1184         if(lua_isnil(L, -1)){
1185                 lua_pop(L, 1);
1186                 warn_if_field_exists(L, index, "tile_images",
1187                                 "Deprecated; new name is \"tiles\".");
1188                 lua_getfield(L, index, "tile_images");
1189         }
1190         if(lua_istable(L, -1)){
1191                 int table = lua_gettop(L);
1192                 lua_pushnil(L);
1193                 int i = 0;
1194                 while(lua_next(L, table) != 0){
1195                         // Read tiledef from value
1196                         f.tiledef[i] = read_tiledef(L, -1);
1197                         // removes value, keeps key for next iteration
1198                         lua_pop(L, 1);
1199                         i++;
1200                         if(i==6){
1201                                 lua_pop(L, 1);
1202                                 break;
1203                         }
1204                 }
1205                 // Copy last value to all remaining textures
1206                 if(i >= 1){
1207                         TileDef lasttile = f.tiledef[i-1];
1208                         while(i < 6){
1209                                 f.tiledef[i] = lasttile;
1210                                 i++;
1211                         }
1212                 }
1213         }
1214         lua_pop(L, 1);
1215
1216         // special_tiles = {}
1217         lua_getfield(L, index, "special_tiles");
1218         // If nil, try the deprecated name "special_materials" instead
1219         if(lua_isnil(L, -1)){
1220                 lua_pop(L, 1);
1221                 warn_if_field_exists(L, index, "special_materials",
1222                                 "Deprecated; new name is \"special_tiles\".");
1223                 lua_getfield(L, index, "special_materials");
1224         }
1225         if(lua_istable(L, -1)){
1226                 int table = lua_gettop(L);
1227                 lua_pushnil(L);
1228                 int i = 0;
1229                 while(lua_next(L, table) != 0){
1230                         // Read tiledef from value
1231                         f.tiledef_special[i] = read_tiledef(L, -1);
1232                         // removes value, keeps key for next iteration
1233                         lua_pop(L, 1);
1234                         i++;
1235                         if(i==6){
1236                                 lua_pop(L, 1);
1237                                 break;
1238                         }
1239                 }
1240         }
1241         lua_pop(L, 1);
1242
1243         f.alpha = getintfield_default(L, index, "alpha", 255);
1244
1245         /* Other stuff */
1246
1247         lua_getfield(L, index, "post_effect_color");
1248         if(!lua_isnil(L, -1))
1249                 f.post_effect_color = readARGB8(L, -1);
1250         lua_pop(L, 1);
1251
1252         f.param_type = (ContentParamType)getenumfield(L, index, "paramtype",
1253                         es_ContentParamType, CPT_NONE);
1254         f.param_type_2 = (ContentParamType2)getenumfield(L, index, "paramtype2",
1255                         es_ContentParamType2, CPT2_NONE);
1256
1257         // Warn about some deprecated fields
1258         warn_if_field_exists(L, index, "wall_mounted",
1259                         "deprecated: use paramtype2 = 'wallmounted'");
1260         warn_if_field_exists(L, index, "light_propagates",
1261                         "deprecated: determined from paramtype");
1262         warn_if_field_exists(L, index, "dug_item",
1263                         "deprecated: use 'drop' field");
1264         warn_if_field_exists(L, index, "extra_dug_item",
1265                         "deprecated: use 'drop' field");
1266         warn_if_field_exists(L, index, "extra_dug_item_rarity",
1267                         "deprecated: use 'drop' field");
1268         warn_if_field_exists(L, index, "metadata_name",
1269                         "deprecated: use on_add and metadata callbacks");
1270
1271         // True for all ground-like things like stone and mud, false for eg. trees
1272         getboolfield(L, index, "is_ground_content", f.is_ground_content);
1273         f.light_propagates = (f.param_type == CPT_LIGHT);
1274         getboolfield(L, index, "sunlight_propagates", f.sunlight_propagates);
1275         // This is used for collision detection.
1276         // Also for general solidness queries.
1277         getboolfield(L, index, "walkable", f.walkable);
1278         // Player can point to these
1279         getboolfield(L, index, "pointable", f.pointable);
1280         // Player can dig these
1281         getboolfield(L, index, "diggable", f.diggable);
1282         // Player can climb these
1283         getboolfield(L, index, "climbable", f.climbable);
1284         // Player can build on these
1285         getboolfield(L, index, "buildable_to", f.buildable_to);
1286         // Whether the node is non-liquid, source liquid or flowing liquid
1287         f.liquid_type = (LiquidType)getenumfield(L, index, "liquidtype",
1288                         es_LiquidType, LIQUID_NONE);
1289         // If the content is liquid, this is the flowing version of the liquid.
1290         getstringfield(L, index, "liquid_alternative_flowing",
1291                         f.liquid_alternative_flowing);
1292         // If the content is liquid, this is the source version of the liquid.
1293         getstringfield(L, index, "liquid_alternative_source",
1294                         f.liquid_alternative_source);
1295         // Viscosity for fluid flow, ranging from 1 to 7, with
1296         // 1 giving almost instantaneous propagation and 7 being
1297         // the slowest possible
1298         f.liquid_viscosity = getintfield_default(L, index,
1299                         "liquid_viscosity", f.liquid_viscosity);
1300         getboolfield(L, index, "liquid_renewable", f.liquid_renewable);
1301         // Amount of light the node emits
1302         f.light_source = getintfield_default(L, index,
1303                         "light_source", f.light_source);
1304         f.damage_per_second = getintfield_default(L, index,
1305                         "damage_per_second", f.damage_per_second);
1306
1307         lua_getfield(L, index, "node_box");
1308         if(lua_istable(L, -1))
1309                 f.node_box = read_nodebox(L, -1);
1310         lua_pop(L, 1);
1311
1312         lua_getfield(L, index, "selection_box");
1313         if(lua_istable(L, -1))
1314                 f.selection_box = read_nodebox(L, -1);
1315         lua_pop(L, 1);
1316
1317         // Set to true if paramtype used to be 'facedir_simple'
1318         getboolfield(L, index, "legacy_facedir_simple", f.legacy_facedir_simple);
1319         // Set to true if wall_mounted used to be set to true
1320         getboolfield(L, index, "legacy_wallmounted", f.legacy_wallmounted);
1321
1322         // Sound table
1323         lua_getfield(L, index, "sounds");
1324         if(lua_istable(L, -1)){
1325                 lua_getfield(L, -1, "footstep");
1326                 read_soundspec(L, -1, f.sound_footstep);
1327                 lua_pop(L, 1);
1328                 lua_getfield(L, -1, "dig");
1329                 read_soundspec(L, -1, f.sound_dig);
1330                 lua_pop(L, 1);
1331                 lua_getfield(L, -1, "dug");
1332                 read_soundspec(L, -1, f.sound_dug);
1333                 lua_pop(L, 1);
1334         }
1335         lua_pop(L, 1);
1336
1337         return f;
1338 }
1339
1340 /*
1341         Inventory stuff
1342 */
1343
1344 static ItemStack read_item(lua_State *L, int index);
1345 static std::vector<ItemStack> read_items(lua_State *L, int index);
1346 // creates a table of ItemStacks
1347 static void push_items(lua_State *L, const std::vector<ItemStack> &items);
1348
1349 static void inventory_set_list_from_lua(Inventory *inv, const char *name,
1350                 lua_State *L, int tableindex, int forcesize=-1)
1351 {
1352         if(tableindex < 0)
1353                 tableindex = lua_gettop(L) + 1 + tableindex;
1354         // If nil, delete list
1355         if(lua_isnil(L, tableindex)){
1356                 inv->deleteList(name);
1357                 return;
1358         }
1359         // Otherwise set list
1360         std::vector<ItemStack> items = read_items(L, tableindex);
1361         int listsize = (forcesize != -1) ? forcesize : items.size();
1362         InventoryList *invlist = inv->addList(name, listsize);
1363         int index = 0;
1364         for(std::vector<ItemStack>::const_iterator
1365                         i = items.begin(); i != items.end(); i++){
1366                 if(forcesize != -1 && index == forcesize)
1367                         break;
1368                 invlist->changeItem(index, *i);
1369                 index++;
1370         }
1371         while(forcesize != -1 && index < forcesize){
1372                 invlist->deleteItem(index);
1373                 index++;
1374         }
1375 }
1376
1377 static void inventory_get_list_to_lua(Inventory *inv, const char *name,
1378                 lua_State *L)
1379 {
1380         InventoryList *invlist = inv->getList(name);
1381         if(invlist == NULL){
1382                 lua_pushnil(L);
1383                 return;
1384         }
1385         std::vector<ItemStack> items;
1386         for(u32 i=0; i<invlist->getSize(); i++)
1387                 items.push_back(invlist->getItem(i));
1388         push_items(L, items);
1389 }
1390
1391 /*
1392         Helpful macros for userdata classes
1393 */
1394
1395 #define method(class, name) {#name, class::l_##name}
1396
1397 /*
1398         LuaItemStack
1399 */
1400
1401 class LuaItemStack
1402 {
1403 private:
1404         ItemStack m_stack;
1405
1406         static const char className[];
1407         static const luaL_reg methods[];
1408
1409         // Exported functions
1410
1411         // garbage collector
1412         static int gc_object(lua_State *L)
1413         {
1414                 LuaItemStack *o = *(LuaItemStack **)(lua_touserdata(L, 1));
1415                 delete o;
1416                 return 0;
1417         }
1418
1419         // is_empty(self) -> true/false
1420         static int l_is_empty(lua_State *L)
1421         {
1422                 LuaItemStack *o = checkobject(L, 1);
1423                 ItemStack &item = o->m_stack;
1424                 lua_pushboolean(L, item.empty());
1425                 return 1;
1426         }
1427
1428         // get_name(self) -> string
1429         static int l_get_name(lua_State *L)
1430         {
1431                 LuaItemStack *o = checkobject(L, 1);
1432                 ItemStack &item = o->m_stack;
1433                 lua_pushstring(L, item.name.c_str());
1434                 return 1;
1435         }
1436
1437         // get_count(self) -> number
1438         static int l_get_count(lua_State *L)
1439         {
1440                 LuaItemStack *o = checkobject(L, 1);
1441                 ItemStack &item = o->m_stack;
1442                 lua_pushinteger(L, item.count);
1443                 return 1;
1444         }
1445
1446         // get_wear(self) -> number
1447         static int l_get_wear(lua_State *L)
1448         {
1449                 LuaItemStack *o = checkobject(L, 1);
1450                 ItemStack &item = o->m_stack;
1451                 lua_pushinteger(L, item.wear);
1452                 return 1;
1453         }
1454
1455         // get_metadata(self) -> string
1456         static int l_get_metadata(lua_State *L)
1457         {
1458                 LuaItemStack *o = checkobject(L, 1);
1459                 ItemStack &item = o->m_stack;
1460                 lua_pushlstring(L, item.metadata.c_str(), item.metadata.size());
1461                 return 1;
1462         }
1463
1464         // clear(self) -> true
1465         static int l_clear(lua_State *L)
1466         {
1467                 LuaItemStack *o = checkobject(L, 1);
1468                 o->m_stack.clear();
1469                 lua_pushboolean(L, true);
1470                 return 1;
1471         }
1472
1473         // replace(self, itemstack or itemstring or table or nil) -> true
1474         static int l_replace(lua_State *L)
1475         {
1476                 LuaItemStack *o = checkobject(L, 1);
1477                 o->m_stack = read_item(L, 2);
1478                 lua_pushboolean(L, true);
1479                 return 1;
1480         }
1481
1482         // to_string(self) -> string
1483         static int l_to_string(lua_State *L)
1484         {
1485                 LuaItemStack *o = checkobject(L, 1);
1486                 std::string itemstring = o->m_stack.getItemString();
1487                 lua_pushstring(L, itemstring.c_str());
1488                 return 1;
1489         }
1490
1491         // to_table(self) -> table or nil
1492         static int l_to_table(lua_State *L)
1493         {
1494                 LuaItemStack *o = checkobject(L, 1);
1495                 const ItemStack &item = o->m_stack;
1496                 if(item.empty())
1497                 {
1498                         lua_pushnil(L);
1499                 }
1500                 else
1501                 {
1502                         lua_newtable(L);
1503                         lua_pushstring(L, item.name.c_str());
1504                         lua_setfield(L, -2, "name");
1505                         lua_pushinteger(L, item.count);
1506                         lua_setfield(L, -2, "count");
1507                         lua_pushinteger(L, item.wear);
1508                         lua_setfield(L, -2, "wear");
1509                         lua_pushlstring(L, item.metadata.c_str(), item.metadata.size());
1510                         lua_setfield(L, -2, "metadata");
1511                 }
1512                 return 1;
1513         }
1514
1515         // get_stack_max(self) -> number
1516         static int l_get_stack_max(lua_State *L)
1517         {
1518                 LuaItemStack *o = checkobject(L, 1);
1519                 ItemStack &item = o->m_stack;
1520                 lua_pushinteger(L, item.getStackMax(get_server(L)->idef()));
1521                 return 1;
1522         }
1523
1524         // get_free_space(self) -> number
1525         static int l_get_free_space(lua_State *L)
1526         {
1527                 LuaItemStack *o = checkobject(L, 1);
1528                 ItemStack &item = o->m_stack;
1529                 lua_pushinteger(L, item.freeSpace(get_server(L)->idef()));
1530                 return 1;
1531         }
1532
1533         // is_known(self) -> true/false
1534         // Checks if the item is defined.
1535         static int l_is_known(lua_State *L)
1536         {
1537                 LuaItemStack *o = checkobject(L, 1);
1538                 ItemStack &item = o->m_stack;
1539                 bool is_known = item.isKnown(get_server(L)->idef());
1540                 lua_pushboolean(L, is_known);
1541                 return 1;
1542         }
1543
1544         // get_definition(self) -> table
1545         // Returns the item definition table from minetest.registered_items,
1546         // or a fallback one (name="unknown")
1547         static int l_get_definition(lua_State *L)
1548         {
1549                 LuaItemStack *o = checkobject(L, 1);
1550                 ItemStack &item = o->m_stack;
1551
1552                 // Get minetest.registered_items[name]
1553                 lua_getglobal(L, "minetest");
1554                 lua_getfield(L, -1, "registered_items");
1555                 luaL_checktype(L, -1, LUA_TTABLE);
1556                 lua_getfield(L, -1, item.name.c_str());
1557                 if(lua_isnil(L, -1))
1558                 {
1559                         lua_pop(L, 1);
1560                         lua_getfield(L, -1, "unknown");
1561                 }
1562                 return 1;
1563         }
1564
1565         // get_tool_capabilities(self) -> table
1566         // Returns the effective tool digging properties.
1567         // Returns those of the hand ("") if this item has none associated.
1568         static int l_get_tool_capabilities(lua_State *L)
1569         {
1570                 LuaItemStack *o = checkobject(L, 1);
1571                 ItemStack &item = o->m_stack;
1572                 const ToolCapabilities &prop =
1573                         item.getToolCapabilities(get_server(L)->idef());
1574                 push_tool_capabilities(L, prop);
1575                 return 1;
1576         }
1577
1578         // add_wear(self, amount) -> true/false
1579         // The range for "amount" is [0,65535]. Wear is only added if the item
1580         // is a tool. Adding wear might destroy the item.
1581         // Returns true if the item is (or was) a tool.
1582         static int l_add_wear(lua_State *L)
1583         {
1584                 LuaItemStack *o = checkobject(L, 1);
1585                 ItemStack &item = o->m_stack;
1586                 int amount = lua_tointeger(L, 2);
1587                 bool result = item.addWear(amount, get_server(L)->idef());
1588                 lua_pushboolean(L, result);
1589                 return 1;
1590         }
1591
1592         // add_item(self, itemstack or itemstring or table or nil) -> itemstack
1593         // Returns leftover item stack
1594         static int l_add_item(lua_State *L)
1595         {
1596                 LuaItemStack *o = checkobject(L, 1);
1597                 ItemStack &item = o->m_stack;
1598                 ItemStack newitem = read_item(L, 2);
1599                 ItemStack leftover = item.addItem(newitem, get_server(L)->idef());
1600                 create(L, leftover);
1601                 return 1;
1602         }
1603
1604         // item_fits(self, itemstack or itemstring or table or nil) -> true/false, itemstack
1605         // First return value is true iff the new item fits fully into the stack
1606         // Second return value is the would-be-left-over item stack
1607         static int l_item_fits(lua_State *L)
1608         {
1609                 LuaItemStack *o = checkobject(L, 1);
1610                 ItemStack &item = o->m_stack;
1611                 ItemStack newitem = read_item(L, 2);
1612                 ItemStack restitem;
1613                 bool fits = item.itemFits(newitem, &restitem, get_server(L)->idef());
1614                 lua_pushboolean(L, fits);  // first return value
1615                 create(L, restitem);       // second return value
1616                 return 2;
1617         }
1618
1619         // take_item(self, takecount=1) -> itemstack
1620         static int l_take_item(lua_State *L)
1621         {
1622                 LuaItemStack *o = checkobject(L, 1);
1623                 ItemStack &item = o->m_stack;
1624                 u32 takecount = 1;
1625                 if(!lua_isnone(L, 2))
1626                         takecount = luaL_checkinteger(L, 2);
1627                 ItemStack taken = item.takeItem(takecount);
1628                 create(L, taken);
1629                 return 1;
1630         }
1631
1632         // peek_item(self, peekcount=1) -> itemstack
1633         static int l_peek_item(lua_State *L)
1634         {
1635                 LuaItemStack *o = checkobject(L, 1);
1636                 ItemStack &item = o->m_stack;
1637                 u32 peekcount = 1;
1638                 if(!lua_isnone(L, 2))
1639                         peekcount = lua_tointeger(L, 2);
1640                 ItemStack peekaboo = item.peekItem(peekcount);
1641                 create(L, peekaboo);
1642                 return 1;
1643         }
1644
1645 public:
1646         LuaItemStack(const ItemStack &item):
1647                 m_stack(item)
1648         {
1649         }
1650
1651         ~LuaItemStack()
1652         {
1653         }
1654
1655         const ItemStack& getItem() const
1656         {
1657                 return m_stack;
1658         }
1659         ItemStack& getItem()
1660         {
1661                 return m_stack;
1662         }
1663
1664         // LuaItemStack(itemstack or itemstring or table or nil)
1665         // Creates an LuaItemStack and leaves it on top of stack
1666         static int create_object(lua_State *L)
1667         {
1668                 ItemStack item = read_item(L, 1);
1669                 LuaItemStack *o = new LuaItemStack(item);
1670                 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
1671                 luaL_getmetatable(L, className);
1672                 lua_setmetatable(L, -2);
1673                 return 1;
1674         }
1675         // Not callable from Lua
1676         static int create(lua_State *L, const ItemStack &item)
1677         {
1678                 LuaItemStack *o = new LuaItemStack(item);
1679                 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
1680                 luaL_getmetatable(L, className);
1681                 lua_setmetatable(L, -2);
1682                 return 1;
1683         }
1684
1685         static LuaItemStack* checkobject(lua_State *L, int narg)
1686         {
1687                 luaL_checktype(L, narg, LUA_TUSERDATA);
1688                 void *ud = luaL_checkudata(L, narg, className);
1689                 if(!ud) luaL_typerror(L, narg, className);
1690                 return *(LuaItemStack**)ud;  // unbox pointer
1691         }
1692
1693         static void Register(lua_State *L)
1694         {
1695                 lua_newtable(L);
1696                 int methodtable = lua_gettop(L);
1697                 luaL_newmetatable(L, className);
1698                 int metatable = lua_gettop(L);
1699
1700                 lua_pushliteral(L, "__metatable");
1701                 lua_pushvalue(L, methodtable);
1702                 lua_settable(L, metatable);  // hide metatable from Lua getmetatable()
1703
1704                 lua_pushliteral(L, "__index");
1705                 lua_pushvalue(L, methodtable);
1706                 lua_settable(L, metatable);
1707
1708                 lua_pushliteral(L, "__gc");
1709                 lua_pushcfunction(L, gc_object);
1710                 lua_settable(L, metatable);
1711
1712                 lua_pop(L, 1);  // drop metatable
1713
1714                 luaL_openlib(L, 0, methods, 0);  // fill methodtable
1715                 lua_pop(L, 1);  // drop methodtable
1716
1717                 // Can be created from Lua (LuaItemStack(itemstack or itemstring or table or nil))
1718                 lua_register(L, className, create_object);
1719         }
1720 };
1721 const char LuaItemStack::className[] = "ItemStack";
1722 const luaL_reg LuaItemStack::methods[] = {
1723         method(LuaItemStack, is_empty),
1724         method(LuaItemStack, get_name),
1725         method(LuaItemStack, get_count),
1726         method(LuaItemStack, get_wear),
1727         method(LuaItemStack, get_metadata),
1728         method(LuaItemStack, clear),
1729         method(LuaItemStack, replace),
1730         method(LuaItemStack, to_string),
1731         method(LuaItemStack, to_table),
1732         method(LuaItemStack, get_stack_max),
1733         method(LuaItemStack, get_free_space),
1734         method(LuaItemStack, is_known),
1735         method(LuaItemStack, get_definition),
1736         method(LuaItemStack, get_tool_capabilities),
1737         method(LuaItemStack, add_wear),
1738         method(LuaItemStack, add_item),
1739         method(LuaItemStack, item_fits),
1740         method(LuaItemStack, take_item),
1741         method(LuaItemStack, peek_item),
1742         {0,0}
1743 };
1744
1745 static ItemStack read_item(lua_State *L, int index)
1746 {
1747         if(index < 0)
1748                 index = lua_gettop(L) + 1 + index;
1749
1750         if(lua_isnil(L, index))
1751         {
1752                 return ItemStack();
1753         }
1754         else if(lua_isuserdata(L, index))
1755         {
1756                 // Convert from LuaItemStack
1757                 LuaItemStack *o = LuaItemStack::checkobject(L, index);
1758                 return o->getItem();
1759         }
1760         else if(lua_isstring(L, index))
1761         {
1762                 // Convert from itemstring
1763                 std::string itemstring = lua_tostring(L, index);
1764                 IItemDefManager *idef = get_server(L)->idef();
1765                 try
1766                 {
1767                         ItemStack item;
1768                         item.deSerialize(itemstring, idef);
1769                         return item;
1770                 }
1771                 catch(SerializationError &e)
1772                 {
1773                         infostream<<"WARNING: unable to create item from itemstring"
1774                                         <<": "<<itemstring<<std::endl;
1775                         return ItemStack();
1776                 }
1777         }
1778         else if(lua_istable(L, index))
1779         {
1780                 // Convert from table
1781                 IItemDefManager *idef = get_server(L)->idef();
1782                 std::string name = getstringfield_default(L, index, "name", "");
1783                 int count = getintfield_default(L, index, "count", 1);
1784                 int wear = getintfield_default(L, index, "wear", 0);
1785                 std::string metadata = getstringfield_default(L, index, "metadata", "");
1786                 return ItemStack(name, count, wear, metadata, idef);
1787         }
1788         else
1789         {
1790                 throw LuaError(L, "Expecting itemstack, itemstring, table or nil");
1791         }
1792 }
1793
1794 static std::vector<ItemStack> read_items(lua_State *L, int index)
1795 {
1796         if(index < 0)
1797                 index = lua_gettop(L) + 1 + index;
1798
1799         std::vector<ItemStack> items;
1800         luaL_checktype(L, index, LUA_TTABLE);
1801         lua_pushnil(L);
1802         while(lua_next(L, index) != 0){
1803                 // key at index -2 and value at index -1
1804                 items.push_back(read_item(L, -1));
1805                 // removes value, keeps key for next iteration
1806                 lua_pop(L, 1);
1807         }
1808         return items;
1809 }
1810
1811 // creates a table of ItemStacks
1812 static void push_items(lua_State *L, const std::vector<ItemStack> &items)
1813 {
1814         // Get the table insert function
1815         lua_getglobal(L, "table");
1816         lua_getfield(L, -1, "insert");
1817         int table_insert = lua_gettop(L);
1818         // Create and fill table
1819         lua_newtable(L);
1820         int table = lua_gettop(L);
1821         for(u32 i=0; i<items.size(); i++){
1822                 ItemStack item = items[i];
1823                 lua_pushvalue(L, table_insert);
1824                 lua_pushvalue(L, table);
1825                 LuaItemStack::create(L, item);
1826                 if(lua_pcall(L, 2, 0, 0))
1827                         script_error(L, "error: %s", lua_tostring(L, -1));
1828         }
1829         lua_remove(L, -2); // Remove table
1830         lua_remove(L, -2); // Remove insert
1831 }
1832
1833 /*
1834         InvRef
1835 */
1836
1837 class InvRef
1838 {
1839 private:
1840         InventoryLocation m_loc;
1841
1842         static const char className[];
1843         static const luaL_reg methods[];
1844
1845         static InvRef *checkobject(lua_State *L, int narg)
1846         {
1847                 luaL_checktype(L, narg, LUA_TUSERDATA);
1848                 void *ud = luaL_checkudata(L, narg, className);
1849                 if(!ud) luaL_typerror(L, narg, className);
1850                 return *(InvRef**)ud;  // unbox pointer
1851         }
1852
1853         static Inventory* getinv(lua_State *L, InvRef *ref)
1854         {
1855                 return get_server(L)->getInventory(ref->m_loc);
1856         }
1857
1858         static InventoryList* getlist(lua_State *L, InvRef *ref,
1859                         const char *listname)
1860         {
1861                 Inventory *inv = getinv(L, ref);
1862                 if(!inv)
1863                         return NULL;
1864                 return inv->getList(listname);
1865         }
1866
1867         static void reportInventoryChange(lua_State *L, InvRef *ref)
1868         {
1869                 // Inform other things that the inventory has changed
1870                 get_server(L)->setInventoryModified(ref->m_loc);
1871         }
1872
1873         // Exported functions
1874
1875         // garbage collector
1876         static int gc_object(lua_State *L) {
1877                 InvRef *o = *(InvRef **)(lua_touserdata(L, 1));
1878                 delete o;
1879                 return 0;
1880         }
1881
1882         // is_empty(self, listname) -> true/false
1883         static int l_is_empty(lua_State *L)
1884         {
1885                 InvRef *ref = checkobject(L, 1);
1886                 const char *listname = luaL_checkstring(L, 2);
1887                 InventoryList *list = getlist(L, ref, listname);
1888                 if(list && list->getUsedSlots() > 0){
1889                         lua_pushboolean(L, false);
1890                 } else {
1891                         lua_pushboolean(L, true);
1892                 }
1893                 return 1;
1894         }
1895
1896         // get_size(self, listname)
1897         static int l_get_size(lua_State *L)
1898         {
1899                 InvRef *ref = checkobject(L, 1);
1900                 const char *listname = luaL_checkstring(L, 2);
1901                 InventoryList *list = getlist(L, ref, listname);
1902                 if(list){
1903                         lua_pushinteger(L, list->getSize());
1904                 } else {
1905                         lua_pushinteger(L, 0);
1906                 }
1907                 return 1;
1908         }
1909
1910         // get_width(self, listname)
1911         static int l_get_width(lua_State *L)
1912         {
1913                 InvRef *ref = checkobject(L, 1);
1914                 const char *listname = luaL_checkstring(L, 2);
1915                 InventoryList *list = getlist(L, ref, listname);
1916                 if(list){
1917                         lua_pushinteger(L, list->getWidth());
1918                 } else {
1919                         lua_pushinteger(L, 0);
1920                 }
1921                 return 1;
1922         }
1923
1924         // set_size(self, listname, size)
1925         static int l_set_size(lua_State *L)
1926         {
1927                 InvRef *ref = checkobject(L, 1);
1928                 const char *listname = luaL_checkstring(L, 2);
1929                 int newsize = luaL_checknumber(L, 3);
1930                 Inventory *inv = getinv(L, ref);
1931                 if(newsize == 0){
1932                         inv->deleteList(listname);
1933                         reportInventoryChange(L, ref);
1934                         return 0;
1935                 }
1936                 InventoryList *list = inv->getList(listname);
1937                 if(list){
1938                         list->setSize(newsize);
1939                 } else {
1940                         list = inv->addList(listname, newsize);
1941                 }
1942                 reportInventoryChange(L, ref);
1943                 return 0;
1944         }
1945
1946         // set_width(self, listname, size)
1947         static int l_set_width(lua_State *L)
1948         {
1949                 InvRef *ref = checkobject(L, 1);
1950                 const char *listname = luaL_checkstring(L, 2);
1951                 int newwidth = luaL_checknumber(L, 3);
1952                 Inventory *inv = getinv(L, ref);
1953                 InventoryList *list = inv->getList(listname);
1954                 if(list){
1955                         list->setWidth(newwidth);
1956                 } else {
1957                         return 0;
1958                 }
1959                 reportInventoryChange(L, ref);
1960                 return 0;
1961         }
1962
1963         // get_stack(self, listname, i) -> itemstack
1964         static int l_get_stack(lua_State *L)
1965         {
1966                 InvRef *ref = checkobject(L, 1);
1967                 const char *listname = luaL_checkstring(L, 2);
1968                 int i = luaL_checknumber(L, 3) - 1;
1969                 InventoryList *list = getlist(L, ref, listname);
1970                 ItemStack item;
1971                 if(list != NULL && i >= 0 && i < (int) list->getSize())
1972                         item = list->getItem(i);
1973                 LuaItemStack::create(L, item);
1974                 return 1;
1975         }
1976
1977         // set_stack(self, listname, i, stack) -> true/false
1978         static int l_set_stack(lua_State *L)
1979         {
1980                 InvRef *ref = checkobject(L, 1);
1981                 const char *listname = luaL_checkstring(L, 2);
1982                 int i = luaL_checknumber(L, 3) - 1;
1983                 ItemStack newitem = read_item(L, 4);
1984                 InventoryList *list = getlist(L, ref, listname);
1985                 if(list != NULL && i >= 0 && i < (int) list->getSize()){
1986                         list->changeItem(i, newitem);
1987                         reportInventoryChange(L, ref);
1988                         lua_pushboolean(L, true);
1989                 } else {
1990                         lua_pushboolean(L, false);
1991                 }
1992                 return 1;
1993         }
1994
1995         // get_list(self, listname) -> list or nil
1996         static int l_get_list(lua_State *L)
1997         {
1998                 InvRef *ref = checkobject(L, 1);
1999                 const char *listname = luaL_checkstring(L, 2);
2000                 Inventory *inv = getinv(L, ref);
2001                 inventory_get_list_to_lua(inv, listname, L);
2002                 return 1;
2003         }
2004
2005         // set_list(self, listname, list)
2006         static int l_set_list(lua_State *L)
2007         {
2008                 InvRef *ref = checkobject(L, 1);
2009                 const char *listname = luaL_checkstring(L, 2);
2010                 Inventory *inv = getinv(L, ref);
2011                 InventoryList *list = inv->getList(listname);
2012                 if(list)
2013                         inventory_set_list_from_lua(inv, listname, L, 3,
2014                                         list->getSize());
2015                 else
2016                         inventory_set_list_from_lua(inv, listname, L, 3);
2017                 reportInventoryChange(L, ref);
2018                 return 0;
2019         }
2020
2021         // add_item(self, listname, itemstack or itemstring or table or nil) -> itemstack
2022         // Returns the leftover stack
2023         static int l_add_item(lua_State *L)
2024         {
2025                 InvRef *ref = checkobject(L, 1);
2026                 const char *listname = luaL_checkstring(L, 2);
2027                 ItemStack item = read_item(L, 3);
2028                 InventoryList *list = getlist(L, ref, listname);
2029                 if(list){
2030                         ItemStack leftover = list->addItem(item);
2031                         if(leftover.count != item.count)
2032                                 reportInventoryChange(L, ref);
2033                         LuaItemStack::create(L, leftover);
2034                 } else {
2035                         LuaItemStack::create(L, item);
2036                 }
2037                 return 1;
2038         }
2039
2040         // room_for_item(self, listname, itemstack or itemstring or table or nil) -> true/false
2041         // Returns true if the item completely fits into the list
2042         static int l_room_for_item(lua_State *L)
2043         {
2044                 InvRef *ref = checkobject(L, 1);
2045                 const char *listname = luaL_checkstring(L, 2);
2046                 ItemStack item = read_item(L, 3);
2047                 InventoryList *list = getlist(L, ref, listname);
2048                 if(list){
2049                         lua_pushboolean(L, list->roomForItem(item));
2050                 } else {
2051                         lua_pushboolean(L, false);
2052                 }
2053                 return 1;
2054         }
2055
2056         // contains_item(self, listname, itemstack or itemstring or table or nil) -> true/false
2057         // Returns true if the list contains the given count of the given item name
2058         static int l_contains_item(lua_State *L)
2059         {
2060                 InvRef *ref = checkobject(L, 1);
2061                 const char *listname = luaL_checkstring(L, 2);
2062                 ItemStack item = read_item(L, 3);
2063                 InventoryList *list = getlist(L, ref, listname);
2064                 if(list){
2065                         lua_pushboolean(L, list->containsItem(item));
2066                 } else {
2067                         lua_pushboolean(L, false);
2068                 }
2069                 return 1;
2070         }
2071
2072         // remove_item(self, listname, itemstack or itemstring or table or nil) -> itemstack
2073         // Returns the items that were actually removed
2074         static int l_remove_item(lua_State *L)
2075         {
2076                 InvRef *ref = checkobject(L, 1);
2077                 const char *listname = luaL_checkstring(L, 2);
2078                 ItemStack item = read_item(L, 3);
2079                 InventoryList *list = getlist(L, ref, listname);
2080                 if(list){
2081                         ItemStack removed = list->removeItem(item);
2082                         if(!removed.empty())
2083                                 reportInventoryChange(L, ref);
2084                         LuaItemStack::create(L, removed);
2085                 } else {
2086                         LuaItemStack::create(L, ItemStack());
2087                 }
2088                 return 1;
2089         }
2090
2091         // get_location() -> location (like minetest.get_inventory(location))
2092         static int l_get_location(lua_State *L)
2093         {
2094                 InvRef *ref = checkobject(L, 1);
2095                 const InventoryLocation &loc = ref->m_loc;
2096                 switch(loc.type){
2097                 case InventoryLocation::PLAYER:
2098                         lua_newtable(L);
2099                         lua_pushstring(L, "player");
2100                         lua_setfield(L, -2, "type");
2101                         lua_pushstring(L, loc.name.c_str());
2102                         lua_setfield(L, -2, "name");
2103                         return 1;
2104                 case InventoryLocation::NODEMETA:
2105                         lua_newtable(L);
2106                         lua_pushstring(L, "nodemeta");
2107                         lua_setfield(L, -2, "type");
2108                         push_v3s16(L, loc.p);
2109                         lua_setfield(L, -2, "name");
2110                         return 1;
2111                 case InventoryLocation::DETACHED:
2112                         lua_newtable(L);
2113                         lua_pushstring(L, "detached");
2114                         lua_setfield(L, -2, "type");
2115                         lua_pushstring(L, loc.name.c_str());
2116                         lua_setfield(L, -2, "name");
2117                         return 1;
2118                 case InventoryLocation::UNDEFINED:
2119                 case InventoryLocation::CURRENT_PLAYER:
2120                         break;
2121                 }
2122                 lua_newtable(L);
2123                 lua_pushstring(L, "undefined");
2124                 lua_setfield(L, -2, "type");
2125                 return 1;
2126         }
2127
2128 public:
2129         InvRef(const InventoryLocation &loc):
2130                 m_loc(loc)
2131         {
2132         }
2133
2134         ~InvRef()
2135         {
2136         }
2137
2138         // Creates an InvRef and leaves it on top of stack
2139         // Not callable from Lua; all references are created on the C side.
2140         static void create(lua_State *L, const InventoryLocation &loc)
2141         {
2142                 InvRef *o = new InvRef(loc);
2143                 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
2144                 luaL_getmetatable(L, className);
2145                 lua_setmetatable(L, -2);
2146         }
2147         static void createPlayer(lua_State *L, Player *player)
2148         {
2149                 InventoryLocation loc;
2150                 loc.setPlayer(player->getName());
2151                 create(L, loc);
2152         }
2153         static void createNodeMeta(lua_State *L, v3s16 p)
2154         {
2155                 InventoryLocation loc;
2156                 loc.setNodeMeta(p);
2157                 create(L, loc);
2158         }
2159
2160         static void Register(lua_State *L)
2161         {
2162                 lua_newtable(L);
2163                 int methodtable = lua_gettop(L);
2164                 luaL_newmetatable(L, className);
2165                 int metatable = lua_gettop(L);
2166
2167                 lua_pushliteral(L, "__metatable");
2168                 lua_pushvalue(L, methodtable);
2169                 lua_settable(L, metatable);  // hide metatable from Lua getmetatable()
2170
2171                 lua_pushliteral(L, "__index");
2172                 lua_pushvalue(L, methodtable);
2173                 lua_settable(L, metatable);
2174
2175                 lua_pushliteral(L, "__gc");
2176                 lua_pushcfunction(L, gc_object);
2177                 lua_settable(L, metatable);
2178
2179                 lua_pop(L, 1);  // drop metatable
2180
2181                 luaL_openlib(L, 0, methods, 0);  // fill methodtable
2182                 lua_pop(L, 1);  // drop methodtable
2183
2184                 // Cannot be created from Lua
2185                 //lua_register(L, className, create_object);
2186         }
2187 };
2188 const char InvRef::className[] = "InvRef";
2189 const luaL_reg InvRef::methods[] = {
2190         method(InvRef, is_empty),
2191         method(InvRef, get_size),
2192         method(InvRef, set_size),
2193         method(InvRef, get_width),
2194         method(InvRef, set_width),
2195         method(InvRef, get_stack),
2196         method(InvRef, set_stack),
2197         method(InvRef, get_list),
2198         method(InvRef, set_list),
2199         method(InvRef, add_item),
2200         method(InvRef, room_for_item),
2201         method(InvRef, contains_item),
2202         method(InvRef, remove_item),
2203         method(InvRef, get_location),
2204         {0,0}
2205 };
2206
2207 /*
2208         NodeMetaRef
2209 */
2210
2211 class NodeMetaRef
2212 {
2213 private:
2214         v3s16 m_p;
2215         ServerEnvironment *m_env;
2216
2217         static const char className[];
2218         static const luaL_reg methods[];
2219
2220         static NodeMetaRef *checkobject(lua_State *L, int narg)
2221         {
2222                 luaL_checktype(L, narg, LUA_TUSERDATA);
2223                 void *ud = luaL_checkudata(L, narg, className);
2224                 if(!ud) luaL_typerror(L, narg, className);
2225                 return *(NodeMetaRef**)ud;  // unbox pointer
2226         }
2227
2228         static NodeMetadata* getmeta(NodeMetaRef *ref, bool auto_create)
2229         {
2230                 NodeMetadata *meta = ref->m_env->getMap().getNodeMetadata(ref->m_p);
2231                 if(meta == NULL && auto_create)
2232                 {
2233                         meta = new NodeMetadata(ref->m_env->getGameDef());
2234                         ref->m_env->getMap().setNodeMetadata(ref->m_p, meta);
2235                 }
2236                 return meta;
2237         }
2238
2239         static void reportMetadataChange(NodeMetaRef *ref)
2240         {
2241                 // NOTE: This same code is in rollback_interface.cpp
2242                 // Inform other things that the metadata has changed
2243                 v3s16 blockpos = getNodeBlockPos(ref->m_p);
2244                 MapEditEvent event;
2245                 event.type = MEET_BLOCK_NODE_METADATA_CHANGED;
2246                 event.p = blockpos;
2247                 ref->m_env->getMap().dispatchEvent(&event);
2248                 // Set the block to be saved
2249                 MapBlock *block = ref->m_env->getMap().getBlockNoCreateNoEx(blockpos);
2250                 if(block)
2251                         block->raiseModified(MOD_STATE_WRITE_NEEDED,
2252                                         "NodeMetaRef::reportMetadataChange");
2253         }
2254
2255         // Exported functions
2256
2257         // garbage collector
2258         static int gc_object(lua_State *L) {
2259                 NodeMetaRef *o = *(NodeMetaRef **)(lua_touserdata(L, 1));
2260                 delete o;
2261                 return 0;
2262         }
2263
2264         // get_string(self, name)
2265         static int l_get_string(lua_State *L)
2266         {
2267                 NodeMetaRef *ref = checkobject(L, 1);
2268                 std::string name = luaL_checkstring(L, 2);
2269
2270                 NodeMetadata *meta = getmeta(ref, false);
2271                 if(meta == NULL){
2272                         lua_pushlstring(L, "", 0);
2273                         return 1;
2274                 }
2275                 std::string str = meta->getString(name);
2276                 lua_pushlstring(L, str.c_str(), str.size());
2277                 return 1;
2278         }
2279
2280         // set_string(self, name, var)
2281         static int l_set_string(lua_State *L)
2282         {
2283                 NodeMetaRef *ref = checkobject(L, 1);
2284                 std::string name = luaL_checkstring(L, 2);
2285                 size_t len = 0;
2286                 const char *s = lua_tolstring(L, 3, &len);
2287                 std::string str(s, len);
2288
2289                 NodeMetadata *meta = getmeta(ref, !str.empty());
2290                 if(meta == NULL || str == meta->getString(name))
2291                         return 0;
2292                 meta->setString(name, str);
2293                 reportMetadataChange(ref);
2294                 return 0;
2295         }
2296
2297         // get_int(self, name)
2298         static int l_get_int(lua_State *L)
2299         {
2300                 NodeMetaRef *ref = checkobject(L, 1);
2301                 std::string name = lua_tostring(L, 2);
2302
2303                 NodeMetadata *meta = getmeta(ref, false);
2304                 if(meta == NULL){
2305                         lua_pushnumber(L, 0);
2306                         return 1;
2307                 }
2308                 std::string str = meta->getString(name);
2309                 lua_pushnumber(L, stoi(str));
2310                 return 1;
2311         }
2312
2313         // set_int(self, name, var)
2314         static int l_set_int(lua_State *L)
2315         {
2316                 NodeMetaRef *ref = checkobject(L, 1);
2317                 std::string name = lua_tostring(L, 2);
2318                 int a = lua_tointeger(L, 3);
2319                 std::string str = itos(a);
2320
2321                 NodeMetadata *meta = getmeta(ref, true);
2322                 if(meta == NULL || str == meta->getString(name))
2323                         return 0;
2324                 meta->setString(name, str);
2325                 reportMetadataChange(ref);
2326                 return 0;
2327         }
2328
2329         // get_float(self, name)
2330         static int l_get_float(lua_State *L)
2331         {
2332                 NodeMetaRef *ref = checkobject(L, 1);
2333                 std::string name = lua_tostring(L, 2);
2334
2335                 NodeMetadata *meta = getmeta(ref, false);
2336                 if(meta == NULL){
2337                         lua_pushnumber(L, 0);
2338                         return 1;
2339                 }
2340                 std::string str = meta->getString(name);
2341                 lua_pushnumber(L, stof(str));
2342                 return 1;
2343         }
2344
2345         // set_float(self, name, var)
2346         static int l_set_float(lua_State *L)
2347         {
2348                 NodeMetaRef *ref = checkobject(L, 1);
2349                 std::string name = lua_tostring(L, 2);
2350                 float a = lua_tonumber(L, 3);
2351                 std::string str = ftos(a);
2352
2353                 NodeMetadata *meta = getmeta(ref, true);
2354                 if(meta == NULL || str == meta->getString(name))
2355                         return 0;
2356                 meta->setString(name, str);
2357                 reportMetadataChange(ref);
2358                 return 0;
2359         }
2360
2361         // get_inventory(self)
2362         static int l_get_inventory(lua_State *L)
2363         {
2364                 NodeMetaRef *ref = checkobject(L, 1);
2365                 getmeta(ref, true);  // try to ensure the metadata exists
2366                 InvRef::createNodeMeta(L, ref->m_p);
2367                 return 1;
2368         }
2369
2370         // to_table(self)
2371         static int l_to_table(lua_State *L)
2372         {
2373                 NodeMetaRef *ref = checkobject(L, 1);
2374
2375                 NodeMetadata *meta = getmeta(ref, true);
2376                 if(meta == NULL){
2377                         lua_pushnil(L);
2378                         return 1;
2379                 }
2380                 lua_newtable(L);
2381                 // fields
2382                 lua_newtable(L);
2383                 {
2384                         std::map<std::string, std::string> fields = meta->getStrings();
2385                         for(std::map<std::string, std::string>::const_iterator
2386                                         i = fields.begin(); i != fields.end(); i++){
2387                                 const std::string &name = i->first;
2388                                 const std::string &value = i->second;
2389                                 lua_pushlstring(L, name.c_str(), name.size());
2390                                 lua_pushlstring(L, value.c_str(), value.size());
2391                                 lua_settable(L, -3);
2392                         }
2393                 }
2394                 lua_setfield(L, -2, "fields");
2395                 // inventory
2396                 lua_newtable(L);
2397                 Inventory *inv = meta->getInventory();
2398                 if(inv){
2399                         std::vector<const InventoryList*> lists = inv->getLists();
2400                         for(std::vector<const InventoryList*>::const_iterator
2401                                         i = lists.begin(); i != lists.end(); i++){
2402                                 inventory_get_list_to_lua(inv, (*i)->getName().c_str(), L);
2403                                 lua_setfield(L, -2, (*i)->getName().c_str());
2404                         }
2405                 }
2406                 lua_setfield(L, -2, "inventory");
2407                 return 1;
2408         }
2409
2410         // from_table(self, table)
2411         static int l_from_table(lua_State *L)
2412         {
2413                 NodeMetaRef *ref = checkobject(L, 1);
2414                 int base = 2;
2415
2416                 if(lua_isnil(L, base)){
2417                         // No metadata
2418                         ref->m_env->getMap().removeNodeMetadata(ref->m_p);
2419                         lua_pushboolean(L, true);
2420                         return 1;
2421                 }
2422
2423                 // Has metadata; clear old one first
2424                 ref->m_env->getMap().removeNodeMetadata(ref->m_p);
2425                 // Create new metadata
2426                 NodeMetadata *meta = getmeta(ref, true);
2427                 // Set fields
2428                 lua_getfield(L, base, "fields");
2429                 int fieldstable = lua_gettop(L);
2430                 lua_pushnil(L);
2431                 while(lua_next(L, fieldstable) != 0){
2432                         // key at index -2 and value at index -1
2433                         std::string name = lua_tostring(L, -2);
2434                         size_t cl;
2435                         const char *cs = lua_tolstring(L, -1, &cl);
2436                         std::string value(cs, cl);
2437                         meta->setString(name, value);
2438                         lua_pop(L, 1); // removes value, keeps key for next iteration
2439                 }
2440                 // Set inventory
2441                 Inventory *inv = meta->getInventory();
2442                 lua_getfield(L, base, "inventory");
2443                 int inventorytable = lua_gettop(L);
2444                 lua_pushnil(L);
2445                 while(lua_next(L, inventorytable) != 0){
2446                         // key at index -2 and value at index -1
2447                         std::string name = lua_tostring(L, -2);
2448                         inventory_set_list_from_lua(inv, name.c_str(), L, -1);
2449                         lua_pop(L, 1); // removes value, keeps key for next iteration
2450                 }
2451                 reportMetadataChange(ref);
2452                 lua_pushboolean(L, true);
2453                 return 1;
2454         }
2455
2456 public:
2457         NodeMetaRef(v3s16 p, ServerEnvironment *env):
2458                 m_p(p),
2459                 m_env(env)
2460         {
2461         }
2462
2463         ~NodeMetaRef()
2464         {
2465         }
2466
2467         // Creates an NodeMetaRef and leaves it on top of stack
2468         // Not callable from Lua; all references are created on the C side.
2469         static void create(lua_State *L, v3s16 p, ServerEnvironment *env)
2470         {
2471                 NodeMetaRef *o = new NodeMetaRef(p, env);
2472                 //infostream<<"NodeMetaRef::create: o="<<o<<std::endl;
2473                 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
2474                 luaL_getmetatable(L, className);
2475                 lua_setmetatable(L, -2);
2476         }
2477
2478         static void Register(lua_State *L)
2479         {
2480                 lua_newtable(L);
2481                 int methodtable = lua_gettop(L);
2482                 luaL_newmetatable(L, className);
2483                 int metatable = lua_gettop(L);
2484
2485                 lua_pushliteral(L, "__metatable");
2486                 lua_pushvalue(L, methodtable);
2487                 lua_settable(L, metatable);  // hide metatable from Lua getmetatable()
2488
2489                 lua_pushliteral(L, "__index");
2490                 lua_pushvalue(L, methodtable);
2491                 lua_settable(L, metatable);
2492
2493                 lua_pushliteral(L, "__gc");
2494                 lua_pushcfunction(L, gc_object);
2495                 lua_settable(L, metatable);
2496
2497                 lua_pop(L, 1);  // drop metatable
2498
2499                 luaL_openlib(L, 0, methods, 0);  // fill methodtable
2500                 lua_pop(L, 1);  // drop methodtable
2501
2502                 // Cannot be created from Lua
2503                 //lua_register(L, className, create_object);
2504         }
2505 };
2506 const char NodeMetaRef::className[] = "NodeMetaRef";
2507 const luaL_reg NodeMetaRef::methods[] = {
2508         method(NodeMetaRef, get_string),
2509         method(NodeMetaRef, set_string),
2510         method(NodeMetaRef, get_int),
2511         method(NodeMetaRef, set_int),
2512         method(NodeMetaRef, get_float),
2513         method(NodeMetaRef, set_float),
2514         method(NodeMetaRef, get_inventory),
2515         method(NodeMetaRef, to_table),
2516         method(NodeMetaRef, from_table),
2517         {0,0}
2518 };
2519
2520 /*
2521         ObjectRef
2522 */
2523
2524 class ObjectRef
2525 {
2526 private:
2527         ServerActiveObject *m_object;
2528
2529         static const char className[];
2530         static const luaL_reg methods[];
2531 public:
2532         static ObjectRef *checkobject(lua_State *L, int narg)
2533         {
2534                 luaL_checktype(L, narg, LUA_TUSERDATA);
2535                 void *ud = luaL_checkudata(L, narg, className);
2536                 if(!ud) luaL_typerror(L, narg, className);
2537                 return *(ObjectRef**)ud;  // unbox pointer
2538         }
2539
2540         static ServerActiveObject* getobject(ObjectRef *ref)
2541         {
2542                 ServerActiveObject *co = ref->m_object;
2543                 return co;
2544         }
2545 private:
2546         static LuaEntitySAO* getluaobject(ObjectRef *ref)
2547         {
2548                 ServerActiveObject *obj = getobject(ref);
2549                 if(obj == NULL)
2550                         return NULL;
2551                 if(obj->getType() != ACTIVEOBJECT_TYPE_LUAENTITY)
2552                         return NULL;
2553                 return (LuaEntitySAO*)obj;
2554         }
2555
2556         static PlayerSAO* getplayersao(ObjectRef *ref)
2557         {
2558                 ServerActiveObject *obj = getobject(ref);
2559                 if(obj == NULL)
2560                         return NULL;
2561                 if(obj->getType() != ACTIVEOBJECT_TYPE_PLAYER)
2562                         return NULL;
2563                 return (PlayerSAO*)obj;
2564         }
2565
2566         static Player* getplayer(ObjectRef *ref)
2567         {
2568                 PlayerSAO *playersao = getplayersao(ref);
2569                 if(playersao == NULL)
2570                         return NULL;
2571                 return playersao->getPlayer();
2572         }
2573
2574         // Exported functions
2575
2576         // garbage collector
2577         static int gc_object(lua_State *L) {
2578                 ObjectRef *o = *(ObjectRef **)(lua_touserdata(L, 1));
2579                 //infostream<<"ObjectRef::gc_object: o="<<o<<std::endl;
2580                 delete o;
2581                 return 0;
2582         }
2583
2584         // remove(self)
2585         static int l_remove(lua_State *L)
2586         {
2587                 ObjectRef *ref = checkobject(L, 1);
2588                 ServerActiveObject *co = getobject(ref);
2589                 if(co == NULL) return 0;
2590                 verbosestream<<"ObjectRef::l_remove(): id="<<co->getId()<<std::endl;
2591                 co->m_removed = true;
2592                 return 0;
2593         }
2594
2595         // getpos(self)
2596         // returns: {x=num, y=num, z=num}
2597         static int l_getpos(lua_State *L)
2598         {
2599                 ObjectRef *ref = checkobject(L, 1);
2600                 ServerActiveObject *co = getobject(ref);
2601                 if(co == NULL) return 0;
2602                 v3f pos = co->getBasePosition() / BS;
2603                 lua_newtable(L);
2604                 lua_pushnumber(L, pos.X);
2605                 lua_setfield(L, -2, "x");
2606                 lua_pushnumber(L, pos.Y);
2607                 lua_setfield(L, -2, "y");
2608                 lua_pushnumber(L, pos.Z);
2609                 lua_setfield(L, -2, "z");
2610                 return 1;
2611         }
2612
2613         // setpos(self, pos)
2614         static int l_setpos(lua_State *L)
2615         {
2616                 ObjectRef *ref = checkobject(L, 1);
2617                 //LuaEntitySAO *co = getluaobject(ref);
2618                 ServerActiveObject *co = getobject(ref);
2619                 if(co == NULL) return 0;
2620                 // pos
2621                 v3f pos = checkFloatPos(L, 2);
2622                 // Do it
2623                 co->setPos(pos);
2624                 return 0;
2625         }
2626
2627         // moveto(self, pos, continuous=false)
2628         static int l_moveto(lua_State *L)
2629         {
2630                 ObjectRef *ref = checkobject(L, 1);
2631                 //LuaEntitySAO *co = getluaobject(ref);
2632                 ServerActiveObject *co = getobject(ref);
2633                 if(co == NULL) return 0;
2634                 // pos
2635                 v3f pos = checkFloatPos(L, 2);
2636                 // continuous
2637                 bool continuous = lua_toboolean(L, 3);
2638                 // Do it
2639                 co->moveTo(pos, continuous);
2640                 return 0;
2641         }
2642
2643         // punch(self, puncher, time_from_last_punch, tool_capabilities, dir)
2644         static int l_punch(lua_State *L)
2645         {
2646                 ObjectRef *ref = checkobject(L, 1);
2647                 ObjectRef *puncher_ref = checkobject(L, 2);
2648                 ServerActiveObject *co = getobject(ref);
2649                 ServerActiveObject *puncher = getobject(puncher_ref);
2650                 if(co == NULL) return 0;
2651                 if(puncher == NULL) return 0;
2652                 v3f dir;
2653                 if(lua_type(L, 5) != LUA_TTABLE)
2654                         dir = co->getBasePosition() - puncher->getBasePosition();
2655                 else
2656                         dir = read_v3f(L, 5);
2657                 float time_from_last_punch = 1000000;
2658                 if(lua_isnumber(L, 3))
2659                         time_from_last_punch = lua_tonumber(L, 3);
2660                 ToolCapabilities toolcap = read_tool_capabilities(L, 4);
2661                 dir.normalize();
2662                 // Do it
2663                 co->punch(dir, &toolcap, puncher, time_from_last_punch);
2664                 return 0;
2665         }
2666
2667         // right_click(self, clicker); clicker = an another ObjectRef
2668         static int l_right_click(lua_State *L)
2669         {
2670                 ObjectRef *ref = checkobject(L, 1);
2671                 ObjectRef *ref2 = checkobject(L, 2);
2672                 ServerActiveObject *co = getobject(ref);
2673                 ServerActiveObject *co2 = getobject(ref2);
2674                 if(co == NULL) return 0;
2675                 if(co2 == NULL) return 0;
2676                 // Do it
2677                 co->rightClick(co2);
2678                 return 0;
2679         }
2680
2681         // set_hp(self, hp)
2682         // hp = number of hitpoints (2 * number of hearts)
2683         // returns: nil
2684         static int l_set_hp(lua_State *L)
2685         {
2686                 ObjectRef *ref = checkobject(L, 1);
2687                 luaL_checknumber(L, 2);
2688                 ServerActiveObject *co = getobject(ref);
2689                 if(co == NULL) return 0;
2690                 int hp = lua_tonumber(L, 2);
2691                 /*infostream<<"ObjectRef::l_set_hp(): id="<<co->getId()
2692                                 <<" hp="<<hp<<std::endl;*/
2693                 // Do it
2694                 co->setHP(hp);
2695                 // Return
2696                 return 0;
2697         }
2698
2699         // get_hp(self)
2700         // returns: number of hitpoints (2 * number of hearts)
2701         // 0 if not applicable to this type of object
2702         static int l_get_hp(lua_State *L)
2703         {
2704                 ObjectRef *ref = checkobject(L, 1);
2705                 ServerActiveObject *co = getobject(ref);
2706                 if(co == NULL){
2707                         // Default hp is 1
2708                         lua_pushnumber(L, 1);
2709                         return 1;
2710                 }
2711                 int hp = co->getHP();
2712                 /*infostream<<"ObjectRef::l_get_hp(): id="<<co->getId()
2713                                 <<" hp="<<hp<<std::endl;*/
2714                 // Return
2715                 lua_pushnumber(L, hp);
2716                 return 1;
2717         }
2718
2719         // get_inventory(self)
2720         static int l_get_inventory(lua_State *L)
2721         {
2722                 ObjectRef *ref = checkobject(L, 1);
2723                 ServerActiveObject *co = getobject(ref);
2724                 if(co == NULL) return 0;
2725                 // Do it
2726                 InventoryLocation loc = co->getInventoryLocation();
2727                 if(get_server(L)->getInventory(loc) != NULL)
2728                         InvRef::create(L, loc);
2729                 else
2730                         lua_pushnil(L); // An object may have no inventory (nil)
2731                 return 1;
2732         }
2733
2734         // get_wield_list(self)
2735         static int l_get_wield_list(lua_State *L)
2736         {
2737                 ObjectRef *ref = checkobject(L, 1);
2738                 ServerActiveObject *co = getobject(ref);
2739                 if(co == NULL) return 0;
2740                 // Do it
2741                 lua_pushstring(L, co->getWieldList().c_str());
2742                 return 1;
2743         }
2744
2745         // get_wield_index(self)
2746         static int l_get_wield_index(lua_State *L)
2747         {
2748                 ObjectRef *ref = checkobject(L, 1);
2749                 ServerActiveObject *co = getobject(ref);
2750                 if(co == NULL) return 0;
2751                 // Do it
2752                 lua_pushinteger(L, co->getWieldIndex() + 1);
2753                 return 1;
2754         }
2755
2756         // get_wielded_item(self)
2757         static int l_get_wielded_item(lua_State *L)
2758         {
2759                 ObjectRef *ref = checkobject(L, 1);
2760                 ServerActiveObject *co = getobject(ref);
2761                 if(co == NULL){
2762                         // Empty ItemStack
2763                         LuaItemStack::create(L, ItemStack());
2764                         return 1;
2765                 }
2766                 // Do it
2767                 LuaItemStack::create(L, co->getWieldedItem());
2768                 return 1;
2769         }
2770
2771         // set_wielded_item(self, itemstack or itemstring or table or nil)
2772         static int l_set_wielded_item(lua_State *L)
2773         {
2774                 ObjectRef *ref = checkobject(L, 1);
2775                 ServerActiveObject *co = getobject(ref);
2776                 if(co == NULL) return 0;
2777                 // Do it
2778                 ItemStack item = read_item(L, 2);
2779                 bool success = co->setWieldedItem(item);
2780                 lua_pushboolean(L, success);
2781                 return 1;
2782         }
2783
2784         // set_armor_groups(self, groups)
2785         static int l_set_armor_groups(lua_State *L)
2786         {
2787                 ObjectRef *ref = checkobject(L, 1);
2788                 ServerActiveObject *co = getobject(ref);
2789                 if(co == NULL) return 0;
2790                 // Do it
2791                 ItemGroupList groups;
2792                 read_groups(L, 2, groups);
2793                 co->setArmorGroups(groups);
2794                 return 0;
2795         }
2796
2797         // set_animation(self, frame_range, frame_speed, frame_blend)
2798         static int l_set_animation(lua_State *L)
2799         {
2800                 ObjectRef *ref = checkobject(L, 1);
2801                 ServerActiveObject *co = getobject(ref);
2802                 if(co == NULL) return 0;
2803                 // Do it
2804                 v2f frames = v2f(1, 1);
2805                 if(!lua_isnil(L, 2))
2806                         frames = read_v2f(L, 2);
2807                 float frame_speed = 15;
2808                 if(!lua_isnil(L, 3))
2809                         frame_speed = lua_tonumber(L, 3);
2810                 float frame_blend = 0;
2811                 if(!lua_isnil(L, 4))
2812                         frame_blend = lua_tonumber(L, 4);
2813                 co->setAnimation(frames, frame_speed, frame_blend);
2814                 return 0;
2815         }
2816
2817         // set_bone_position(self, std::string bone, v3f position, v3f rotation)
2818         static int l_set_bone_position(lua_State *L)
2819         {
2820                 ObjectRef *ref = checkobject(L, 1);
2821                 ServerActiveObject *co = getobject(ref);
2822                 if(co == NULL) return 0;
2823                 // Do it
2824                 std::string bone = "";
2825                 if(!lua_isnil(L, 2))
2826                         bone = lua_tostring(L, 2);
2827                 v3f position = v3f(0, 0, 0);
2828                 if(!lua_isnil(L, 3))
2829                         position = read_v3f(L, 3);
2830                 v3f rotation = v3f(0, 0, 0);
2831                 if(!lua_isnil(L, 4))
2832                         rotation = read_v3f(L, 4);
2833                 co->setBonePosition(bone, position, rotation);
2834                 return 0;
2835         }
2836
2837         // set_attach(self, parent, bone, position, rotation)
2838         static int l_set_attach(lua_State *L)
2839         {
2840                 ObjectRef *ref = checkobject(L, 1);
2841                 ObjectRef *parent_ref = checkobject(L, 2);
2842                 ServerActiveObject *co = getobject(ref);
2843                 ServerActiveObject *parent = getobject(parent_ref);
2844                 if(co == NULL) return 0;
2845                 if(parent == NULL) return 0;
2846                 // Do it
2847                 std::string bone = "";
2848                 if(!lua_isnil(L, 3))
2849                         bone = lua_tostring(L, 3);
2850                 v3f position = v3f(0, 0, 0);
2851                 if(!lua_isnil(L, 4))
2852                         position = read_v3f(L, 4);
2853                 v3f rotation = v3f(0, 0, 0);
2854                 if(!lua_isnil(L, 5))
2855                         rotation = read_v3f(L, 5);
2856                 co->setAttachment(parent->getId(), bone, position, rotation);
2857                 return 0;
2858         }
2859
2860         // set_detach(self)
2861         static int l_set_detach(lua_State *L)
2862         {
2863                 ObjectRef *ref = checkobject(L, 1);
2864                 ServerActiveObject *co = getobject(ref);
2865                 if(co == NULL) return 0;
2866                 // Do it
2867                 co->setAttachment(0, "", v3f(0,0,0), v3f(0,0,0));
2868                 return 0;
2869         }
2870
2871         // set_properties(self, properties)
2872         static int l_set_properties(lua_State *L)
2873         {
2874                 ObjectRef *ref = checkobject(L, 1);
2875                 ServerActiveObject *co = getobject(ref);
2876                 if(co == NULL) return 0;
2877                 ObjectProperties *prop = co->accessObjectProperties();
2878                 if(!prop)
2879                         return 0;
2880                 read_object_properties(L, 2, prop);
2881                 co->notifyObjectPropertiesModified();
2882                 return 0;
2883         }
2884
2885         /* LuaEntitySAO-only */
2886
2887         // setvelocity(self, {x=num, y=num, z=num})
2888         static int l_setvelocity(lua_State *L)
2889         {
2890                 ObjectRef *ref = checkobject(L, 1);
2891                 LuaEntitySAO *co = getluaobject(ref);
2892                 if(co == NULL) return 0;
2893                 v3f pos = checkFloatPos(L, 2);
2894                 // Do it
2895                 co->setVelocity(pos);
2896                 return 0;
2897         }
2898
2899         // getvelocity(self)
2900         static int l_getvelocity(lua_State *L)
2901         {
2902                 ObjectRef *ref = checkobject(L, 1);
2903                 LuaEntitySAO *co = getluaobject(ref);
2904                 if(co == NULL) return 0;
2905                 // Do it
2906                 v3f v = co->getVelocity();
2907                 pushFloatPos(L, v);
2908                 return 1;
2909         }
2910
2911         // setacceleration(self, {x=num, y=num, z=num})
2912         static int l_setacceleration(lua_State *L)
2913         {
2914                 ObjectRef *ref = checkobject(L, 1);
2915                 LuaEntitySAO *co = getluaobject(ref);
2916                 if(co == NULL) return 0;
2917                 // pos
2918                 v3f pos = checkFloatPos(L, 2);
2919                 // Do it
2920                 co->setAcceleration(pos);
2921                 return 0;
2922         }
2923
2924         // getacceleration(self)
2925         static int l_getacceleration(lua_State *L)
2926         {
2927                 ObjectRef *ref = checkobject(L, 1);
2928                 LuaEntitySAO *co = getluaobject(ref);
2929                 if(co == NULL) return 0;
2930                 // Do it
2931                 v3f v = co->getAcceleration();
2932                 pushFloatPos(L, v);
2933                 return 1;
2934         }
2935
2936         // setyaw(self, radians)
2937         static int l_setyaw(lua_State *L)
2938         {
2939                 ObjectRef *ref = checkobject(L, 1);
2940                 LuaEntitySAO *co = getluaobject(ref);
2941                 if(co == NULL) return 0;
2942                 float yaw = luaL_checknumber(L, 2) * core::RADTODEG;
2943                 // Do it
2944                 co->setYaw(yaw);
2945                 return 0;
2946         }
2947
2948         // getyaw(self)
2949         static int l_getyaw(lua_State *L)
2950         {
2951                 ObjectRef *ref = checkobject(L, 1);
2952                 LuaEntitySAO *co = getluaobject(ref);
2953                 if(co == NULL) return 0;
2954                 // Do it
2955                 float yaw = co->getYaw() * core::DEGTORAD;
2956                 lua_pushnumber(L, yaw);
2957                 return 1;
2958         }
2959
2960         // settexturemod(self, mod)
2961         static int l_settexturemod(lua_State *L)
2962         {
2963                 ObjectRef *ref = checkobject(L, 1);
2964                 LuaEntitySAO *co = getluaobject(ref);
2965                 if(co == NULL) return 0;
2966                 // Do it
2967                 std::string mod = luaL_checkstring(L, 2);
2968                 co->setTextureMod(mod);
2969                 return 0;
2970         }
2971
2972         // setsprite(self, p={x=0,y=0}, num_frames=1, framelength=0.2,
2973         //           select_horiz_by_yawpitch=false)
2974         static int l_setsprite(lua_State *L)
2975         {
2976                 ObjectRef *ref = checkobject(L, 1);
2977                 LuaEntitySAO *co = getluaobject(ref);
2978                 if(co == NULL) return 0;
2979                 // Do it
2980                 v2s16 p(0,0);
2981                 if(!lua_isnil(L, 2))
2982                         p = read_v2s16(L, 2);
2983                 int num_frames = 1;
2984                 if(!lua_isnil(L, 3))
2985                         num_frames = lua_tonumber(L, 3);
2986                 float framelength = 0.2;
2987                 if(!lua_isnil(L, 4))
2988                         framelength = lua_tonumber(L, 4);
2989                 bool select_horiz_by_yawpitch = false;
2990                 if(!lua_isnil(L, 5))
2991                         select_horiz_by_yawpitch = lua_toboolean(L, 5);
2992                 co->setSprite(p, num_frames, framelength, select_horiz_by_yawpitch);
2993                 return 0;
2994         }
2995
2996         // DEPRECATED
2997         // get_entity_name(self)
2998         static int l_get_entity_name(lua_State *L)
2999         {
3000                 ObjectRef *ref = checkobject(L, 1);
3001                 LuaEntitySAO *co = getluaobject(ref);
3002                 if(co == NULL) return 0;
3003                 // Do it
3004                 std::string name = co->getName();
3005                 lua_pushstring(L, name.c_str());
3006                 return 1;
3007         }
3008
3009         // get_luaentity(self)
3010         static int l_get_luaentity(lua_State *L)
3011         {
3012                 ObjectRef *ref = checkobject(L, 1);
3013                 LuaEntitySAO *co = getluaobject(ref);
3014                 if(co == NULL) return 0;
3015                 // Do it
3016                 luaentity_get(L, co->getId());
3017                 return 1;
3018         }
3019
3020         /* Player-only */
3021
3022         // is_player(self)
3023         static int l_is_player(lua_State *L)
3024         {
3025                 ObjectRef *ref = checkobject(L, 1);
3026                 Player *player = getplayer(ref);
3027                 lua_pushboolean(L, (player != NULL));
3028                 return 1;
3029         }
3030
3031         // get_player_name(self)
3032         static int l_get_player_name(lua_State *L)
3033         {
3034                 ObjectRef *ref = checkobject(L, 1);
3035                 Player *player = getplayer(ref);
3036                 if(player == NULL){
3037                         lua_pushlstring(L, "", 0);
3038                         return 1;
3039                 }
3040                 // Do it
3041                 lua_pushstring(L, player->getName());
3042                 return 1;
3043         }
3044
3045         // get_look_dir(self)
3046         static int l_get_look_dir(lua_State *L)
3047         {
3048                 ObjectRef *ref = checkobject(L, 1);
3049                 Player *player = getplayer(ref);
3050                 if(player == NULL) return 0;
3051                 // Do it
3052                 float pitch = player->getRadPitch();
3053                 float yaw = player->getRadYaw();
3054                 v3f v(cos(pitch)*cos(yaw), sin(pitch), cos(pitch)*sin(yaw));
3055                 push_v3f(L, v);
3056                 return 1;
3057         }
3058
3059         // get_look_pitch(self)
3060         static int l_get_look_pitch(lua_State *L)
3061         {
3062                 ObjectRef *ref = checkobject(L, 1);
3063                 Player *player = getplayer(ref);
3064                 if(player == NULL) return 0;
3065                 // Do it
3066                 lua_pushnumber(L, player->getRadPitch());
3067                 return 1;
3068         }
3069
3070         // get_look_yaw(self)
3071         static int l_get_look_yaw(lua_State *L)
3072         {
3073                 ObjectRef *ref = checkobject(L, 1);
3074                 Player *player = getplayer(ref);
3075                 if(player == NULL) return 0;
3076                 // Do it
3077                 lua_pushnumber(L, player->getRadYaw());
3078                 return 1;
3079         }
3080
3081         // set_inventory_formspec(self, formspec)
3082         static int l_set_inventory_formspec(lua_State *L)
3083         {
3084                 ObjectRef *ref = checkobject(L, 1);
3085                 Player *player = getplayer(ref);
3086                 if(player == NULL) return 0;
3087                 std::string formspec = luaL_checkstring(L, 2);
3088
3089                 player->inventory_formspec = formspec;
3090                 get_server(L)->reportInventoryFormspecModified(player->getName());
3091                 lua_pushboolean(L, true);
3092                 return 1;
3093         }
3094
3095         // get_inventory_formspec(self) -> formspec
3096         static int l_get_inventory_formspec(lua_State *L)
3097         {
3098                 ObjectRef *ref = checkobject(L, 1);
3099                 Player *player = getplayer(ref);
3100                 if(player == NULL) return 0;
3101
3102                 std::string formspec = player->inventory_formspec;
3103                 lua_pushlstring(L, formspec.c_str(), formspec.size());
3104                 return 1;
3105         }
3106         
3107         // get_player_control(self)
3108         static int l_get_player_control(lua_State *L)
3109         {
3110                 ObjectRef *ref = checkobject(L, 1);
3111                 Player *player = getplayer(ref);
3112                 if(player == NULL){
3113                         lua_pushlstring(L, "", 0);
3114                         return 1;
3115                 }
3116                 // Do it
3117                 PlayerControl control = player->getPlayerControl();
3118                 lua_newtable(L);
3119                 lua_pushboolean(L, control.up);
3120                 lua_setfield(L, -2, "up");
3121                 lua_pushboolean(L, control.down);
3122                 lua_setfield(L, -2, "down");
3123                 lua_pushboolean(L, control.left);
3124                 lua_setfield(L, -2, "left");
3125                 lua_pushboolean(L, control.right);
3126                 lua_setfield(L, -2, "right");
3127                 lua_pushboolean(L, control.jump);
3128                 lua_setfield(L, -2, "jump");
3129                 lua_pushboolean(L, control.aux1);
3130                 lua_setfield(L, -2, "aux1");
3131                 lua_pushboolean(L, control.sneak);
3132                 lua_setfield(L, -2, "sneak");
3133                 lua_pushboolean(L, control.LMB);
3134                 lua_setfield(L, -2, "LMB");
3135                 lua_pushboolean(L, control.RMB);
3136                 lua_setfield(L, -2, "RMB");
3137                 return 1;
3138         }
3139         
3140         // get_player_control_bits(self)
3141         static int l_get_player_control_bits(lua_State *L)
3142         {
3143                 ObjectRef *ref = checkobject(L, 1);
3144                 Player *player = getplayer(ref);
3145                 if(player == NULL){
3146                         lua_pushlstring(L, "", 0);
3147                         return 1;
3148                 }
3149                 // Do it        
3150                 lua_pushnumber(L, player->keyPressed);
3151                 return 1;
3152         }
3153         
3154 public:
3155         ObjectRef(ServerActiveObject *object):
3156                 m_object(object)
3157         {
3158                 //infostream<<"ObjectRef created for id="<<m_object->getId()<<std::endl;
3159         }
3160
3161         ~ObjectRef()
3162         {
3163                 /*if(m_object)
3164                         infostream<<"ObjectRef destructing for id="
3165                                         <<m_object->getId()<<std::endl;
3166                 else
3167                         infostream<<"ObjectRef destructing for id=unknown"<<std::endl;*/
3168         }
3169
3170         // Creates an ObjectRef and leaves it on top of stack
3171         // Not callable from Lua; all references are created on the C side.
3172         static void create(lua_State *L, ServerActiveObject *object)
3173         {
3174                 ObjectRef *o = new ObjectRef(object);
3175                 //infostream<<"ObjectRef::create: o="<<o<<std::endl;
3176                 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
3177                 luaL_getmetatable(L, className);
3178                 lua_setmetatable(L, -2);
3179         }
3180
3181         static void set_null(lua_State *L)
3182         {
3183                 ObjectRef *o = checkobject(L, -1);
3184                 o->m_object = NULL;
3185         }
3186
3187         static void Register(lua_State *L)
3188         {
3189                 lua_newtable(L);
3190                 int methodtable = lua_gettop(L);
3191                 luaL_newmetatable(L, className);
3192                 int metatable = lua_gettop(L);
3193
3194                 lua_pushliteral(L, "__metatable");
3195                 lua_pushvalue(L, methodtable);
3196                 lua_settable(L, metatable);  // hide metatable from Lua getmetatable()
3197
3198                 lua_pushliteral(L, "__index");
3199                 lua_pushvalue(L, methodtable);
3200                 lua_settable(L, metatable);
3201
3202                 lua_pushliteral(L, "__gc");
3203                 lua_pushcfunction(L, gc_object);
3204                 lua_settable(L, metatable);
3205
3206                 lua_pop(L, 1);  // drop metatable
3207
3208                 luaL_openlib(L, 0, methods, 0);  // fill methodtable
3209                 lua_pop(L, 1);  // drop methodtable
3210
3211                 // Cannot be created from Lua
3212                 //lua_register(L, className, create_object);
3213         }
3214 };
3215 const char ObjectRef::className[] = "ObjectRef";
3216 const luaL_reg ObjectRef::methods[] = {
3217         // ServerActiveObject
3218         method(ObjectRef, remove),
3219         method(ObjectRef, getpos),
3220         method(ObjectRef, setpos),
3221         method(ObjectRef, moveto),
3222         method(ObjectRef, punch),
3223         method(ObjectRef, right_click),
3224         method(ObjectRef, set_hp),
3225         method(ObjectRef, get_hp),
3226         method(ObjectRef, get_inventory),
3227         method(ObjectRef, get_wield_list),
3228         method(ObjectRef, get_wield_index),
3229         method(ObjectRef, get_wielded_item),
3230         method(ObjectRef, set_wielded_item),
3231         method(ObjectRef, set_armor_groups),
3232         method(ObjectRef, set_animation),
3233         method(ObjectRef, set_bone_position),
3234         method(ObjectRef, set_attach),
3235         method(ObjectRef, set_detach),
3236         method(ObjectRef, set_properties),
3237         // LuaEntitySAO-only
3238         method(ObjectRef, setvelocity),
3239         method(ObjectRef, getvelocity),
3240         method(ObjectRef, setacceleration),
3241         method(ObjectRef, getacceleration),
3242         method(ObjectRef, setyaw),
3243         method(ObjectRef, getyaw),
3244         method(ObjectRef, settexturemod),
3245         method(ObjectRef, setsprite),
3246         method(ObjectRef, get_entity_name),
3247         method(ObjectRef, get_luaentity),
3248         // Player-only
3249         method(ObjectRef, is_player),
3250         method(ObjectRef, get_player_name),
3251         method(ObjectRef, get_look_dir),
3252         method(ObjectRef, get_look_pitch),
3253         method(ObjectRef, get_look_yaw),
3254         method(ObjectRef, set_inventory_formspec),
3255         method(ObjectRef, get_inventory_formspec),
3256         method(ObjectRef, get_player_control),
3257         method(ObjectRef, get_player_control_bits),
3258         {0,0}
3259 };
3260
3261 // Creates a new anonymous reference if cobj=NULL or id=0
3262 static void objectref_get_or_create(lua_State *L,
3263                 ServerActiveObject *cobj)
3264 {
3265         if(cobj == NULL || cobj->getId() == 0){
3266                 ObjectRef::create(L, cobj);
3267         } else {
3268                 objectref_get(L, cobj->getId());
3269         }
3270 }
3271
3272 class LuaPerlinNoise
3273 {
3274 private:
3275         int seed;
3276         int octaves;
3277         float persistence;
3278         float scale;
3279         static const char className[];
3280         static const luaL_reg methods[];
3281
3282         // Exported functions
3283
3284         // garbage collector
3285         static int gc_object(lua_State *L)
3286         {
3287                 LuaPerlinNoise *o = *(LuaPerlinNoise **)(lua_touserdata(L, 1));
3288                 delete o;
3289                 return 0;
3290         }
3291
3292         static int l_get2d(lua_State *L)
3293         {
3294                 LuaPerlinNoise *o = checkobject(L, 1);
3295                 v2f pos2d = read_v2f(L,2);
3296                 lua_Number val = noise2d_perlin(pos2d.X/o->scale, pos2d.Y/o->scale, o->seed, o->octaves, o->persistence);
3297                 lua_pushnumber(L, val);
3298                 return 1;
3299         }
3300         static int l_get3d(lua_State *L)
3301         {
3302                 LuaPerlinNoise *o = checkobject(L, 1);
3303                 v3f pos3d = read_v3f(L,2);
3304                 lua_Number val = noise3d_perlin(pos3d.X/o->scale, pos3d.Y/o->scale, pos3d.Z/o->scale, o->seed, o->octaves, o->persistence);
3305                 lua_pushnumber(L, val);
3306                 return 1;
3307         }
3308
3309 public:
3310         LuaPerlinNoise(int a_seed, int a_octaves, float a_persistence,
3311                         float a_scale):
3312                 seed(a_seed),
3313                 octaves(a_octaves),
3314                 persistence(a_persistence),
3315                 scale(a_scale)
3316         {
3317         }
3318
3319         ~LuaPerlinNoise()
3320         {
3321         }
3322
3323         // LuaPerlinNoise(seed, octaves, persistence, scale)
3324         // Creates an LuaPerlinNoise and leaves it on top of stack
3325         static int create_object(lua_State *L)
3326         {
3327                 int seed = luaL_checkint(L, 1);
3328                 int octaves = luaL_checkint(L, 2);
3329                 float persistence = luaL_checknumber(L, 3);
3330                 float scale = luaL_checknumber(L, 4);
3331                 LuaPerlinNoise *o = new LuaPerlinNoise(seed, octaves, persistence, scale);
3332                 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
3333                 luaL_getmetatable(L, className);
3334                 lua_setmetatable(L, -2);
3335                 return 1;
3336         }
3337
3338         static LuaPerlinNoise* checkobject(lua_State *L, int narg)
3339         {
3340                 luaL_checktype(L, narg, LUA_TUSERDATA);
3341                 void *ud = luaL_checkudata(L, narg, className);
3342                 if(!ud) luaL_typerror(L, narg, className);
3343                 return *(LuaPerlinNoise**)ud;  // unbox pointer
3344         }
3345
3346         static void Register(lua_State *L)
3347         {
3348                 lua_newtable(L);
3349                 int methodtable = lua_gettop(L);
3350                 luaL_newmetatable(L, className);
3351                 int metatable = lua_gettop(L);
3352
3353                 lua_pushliteral(L, "__metatable");
3354                 lua_pushvalue(L, methodtable);
3355                 lua_settable(L, metatable);  // hide metatable from Lua getmetatable()
3356
3357                 lua_pushliteral(L, "__index");
3358                 lua_pushvalue(L, methodtable);
3359                 lua_settable(L, metatable);
3360
3361                 lua_pushliteral(L, "__gc");
3362                 lua_pushcfunction(L, gc_object);
3363                 lua_settable(L, metatable);
3364
3365                 lua_pop(L, 1);  // drop metatable
3366
3367                 luaL_openlib(L, 0, methods, 0);  // fill methodtable
3368                 lua_pop(L, 1);  // drop methodtable
3369
3370                 // Can be created from Lua (PerlinNoise(seed, octaves, persistence)
3371                 lua_register(L, className, create_object);
3372         }
3373 };
3374 const char LuaPerlinNoise::className[] = "PerlinNoise";
3375 const luaL_reg LuaPerlinNoise::methods[] = {
3376         method(LuaPerlinNoise, get2d),
3377         method(LuaPerlinNoise, get3d),
3378         {0,0}
3379 };
3380
3381 /*
3382   PerlinNoiseMap
3383  */
3384 class LuaPerlinNoiseMap
3385 {
3386 private:
3387         Noise *noise;
3388         static const char className[];
3389         static const luaL_reg methods[];
3390
3391         static int gc_object(lua_State *L)
3392         {
3393                 LuaPerlinNoiseMap *o = *(LuaPerlinNoiseMap **)(lua_touserdata(L, 1));
3394                 delete o;
3395                 return 0;
3396         }
3397
3398         static int l_get2dMap(lua_State *L)
3399         {
3400                 int i = 0;
3401
3402                 LuaPerlinNoiseMap *o = checkobject(L, 1);
3403                 v2f p = read_v2f(L, 2);
3404                 
3405                 Noise *n = o->noise;
3406                 n->perlinMap2D(p.X, p.Y);
3407                 
3408                 lua_newtable(L);
3409                 for (int y = 0; y != n->sy; y++) {
3410                         lua_newtable(L);
3411                         for (int x = 0; x != n->sx; x++) {
3412                                 float noiseval = n->np->offset + n->np->scale * n->result[i++];
3413                                 lua_pushnumber(L, noiseval);
3414                                 lua_rawseti(L, -2, x + 1);
3415                         }
3416                         lua_rawseti(L, -2, y + 1);
3417                 }
3418                 return 1;
3419         }
3420         
3421         static int l_get3dMap(lua_State *L)
3422         {
3423                 int i = 0;
3424                 
3425                 LuaPerlinNoiseMap *o = checkobject(L, 1);
3426                 v3f p = read_v3f(L, 2);
3427                 
3428                 Noise *n = o->noise;
3429                 n->perlinMap3D(p.X, p.Y, p.Z);
3430
3431                 lua_newtable(L);
3432                 for (int z = 0; z != n->sz; z++) {
3433                         lua_newtable(L);
3434                         for (int y = 0; y != n->sy; y++) {
3435                                 lua_newtable(L);
3436                                 for (int x = 0; x != n->sx; x++) {
3437                                         lua_pushnumber(L, n->np->offset + n->np->scale * n->result[i++]);
3438                                         lua_rawseti(L, -2, x + 1);
3439                                 }
3440                                 lua_rawseti(L, -2, y + 1);
3441                         }
3442                         lua_rawseti(L, -2, z + 1);
3443                 }
3444                 return 1;
3445         }
3446
3447 public:
3448         LuaPerlinNoiseMap(NoiseParams *np, int seed, v3s16 size) {
3449                 noise = new Noise(np, seed, size.X, size.Y, size.Z);
3450         }
3451
3452         ~LuaPerlinNoiseMap()
3453         {
3454                 delete noise->np;
3455                 delete noise;
3456         }
3457
3458         // LuaPerlinNoiseMap(np, size)
3459         // Creates an LuaPerlinNoiseMap and leaves it on top of stack
3460         static int create_object(lua_State *L)
3461         {
3462                 NoiseParams *np = read_noiseparams(L, 1);
3463                 if (!np)
3464                         return 0;
3465                 v3s16 size = read_v3s16(L, 2);
3466
3467                 LuaPerlinNoiseMap *o = new LuaPerlinNoiseMap(np, 0, size);
3468                 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
3469                 luaL_getmetatable(L, className);
3470                 lua_setmetatable(L, -2);
3471                 return 1;
3472         }
3473
3474         static LuaPerlinNoiseMap *checkobject(lua_State *L, int narg)
3475         {
3476                 luaL_checktype(L, narg, LUA_TUSERDATA);
3477                 
3478                 void *ud = luaL_checkudata(L, narg, className);
3479                 if (!ud)
3480                         luaL_typerror(L, narg, className);
3481                 
3482                 return *(LuaPerlinNoiseMap **)ud;  // unbox pointer
3483         }
3484
3485         static void Register(lua_State *L)
3486         {
3487                 lua_newtable(L);
3488                 int methodtable = lua_gettop(L);
3489                 luaL_newmetatable(L, className);
3490                 int metatable = lua_gettop(L);
3491
3492                 lua_pushliteral(L, "__metatable");
3493                 lua_pushvalue(L, methodtable);
3494                 lua_settable(L, metatable);  // hide metatable from Lua getmetatable()
3495
3496                 lua_pushliteral(L, "__index");
3497                 lua_pushvalue(L, methodtable);
3498                 lua_settable(L, metatable);
3499
3500                 lua_pushliteral(L, "__gc");
3501                 lua_pushcfunction(L, gc_object);
3502                 lua_settable(L, metatable);
3503
3504                 lua_pop(L, 1);  // drop metatable
3505
3506                 luaL_openlib(L, 0, methods, 0);  // fill methodtable
3507                 lua_pop(L, 1);  // drop methodtable
3508
3509                 // Can be created from Lua (PerlinNoiseMap(np, size)
3510                 lua_register(L, className, create_object);
3511         }
3512 };
3513 const char LuaPerlinNoiseMap::className[] = "PerlinNoiseMap";
3514 const luaL_reg LuaPerlinNoiseMap::methods[] = {
3515         method(LuaPerlinNoiseMap, get2dMap),
3516         method(LuaPerlinNoiseMap, get3dMap),
3517         {0,0}
3518 };
3519
3520 /*
3521         NodeTimerRef
3522 */
3523
3524 class NodeTimerRef
3525 {
3526 private:
3527         v3s16 m_p;
3528         ServerEnvironment *m_env;
3529
3530         static const char className[];
3531         static const luaL_reg methods[];
3532
3533         static int gc_object(lua_State *L) {
3534                 NodeTimerRef *o = *(NodeTimerRef **)(lua_touserdata(L, 1));
3535                 delete o;
3536                 return 0;
3537         }
3538
3539         static NodeTimerRef *checkobject(lua_State *L, int narg)
3540         {
3541                 luaL_checktype(L, narg, LUA_TUSERDATA);
3542                 void *ud = luaL_checkudata(L, narg, className);
3543                 if(!ud) luaL_typerror(L, narg, className);
3544                 return *(NodeTimerRef**)ud;  // unbox pointer
3545         }
3546
3547         static int l_set(lua_State *L)
3548         {
3549                 NodeTimerRef *o = checkobject(L, 1);
3550                 ServerEnvironment *env = o->m_env;
3551                 if(env == NULL) return 0;
3552                 f32 t = luaL_checknumber(L,2);
3553                 f32 e = luaL_checknumber(L,3);
3554                 env->getMap().setNodeTimer(o->m_p,NodeTimer(t,e));
3555                 return 0;
3556         }
3557
3558         static int l_start(lua_State *L)
3559         {
3560                 NodeTimerRef *o = checkobject(L, 1);
3561                 ServerEnvironment *env = o->m_env;
3562                 if(env == NULL) return 0;
3563                 f32 t = luaL_checknumber(L,2);
3564                 env->getMap().setNodeTimer(o->m_p,NodeTimer(t,0));
3565                 return 0;
3566         }
3567
3568         static int l_stop(lua_State *L)
3569         {
3570                 NodeTimerRef *o = checkobject(L, 1);
3571                 ServerEnvironment *env = o->m_env;
3572                 if(env == NULL) return 0;
3573                 env->getMap().removeNodeTimer(o->m_p);
3574                 return 0;
3575         }
3576
3577         static int l_is_started(lua_State *L)
3578         {
3579                 NodeTimerRef *o = checkobject(L, 1);
3580                 ServerEnvironment *env = o->m_env;
3581                 if(env == NULL) return 0;
3582
3583                 NodeTimer t = env->getMap().getNodeTimer(o->m_p);
3584                 lua_pushboolean(L,(t.timeout != 0));
3585                 return 1;
3586         }
3587
3588         static int l_get_timeout(lua_State *L)
3589         {
3590                 NodeTimerRef *o = checkobject(L, 1);
3591                 ServerEnvironment *env = o->m_env;
3592                 if(env == NULL) return 0;
3593
3594                 NodeTimer t = env->getMap().getNodeTimer(o->m_p);
3595                 lua_pushnumber(L,t.timeout);
3596                 return 1;
3597         }
3598
3599         static int l_get_elapsed(lua_State *L)
3600         {
3601                 NodeTimerRef *o = checkobject(L, 1);
3602                 ServerEnvironment *env = o->m_env;
3603                 if(env == NULL) return 0;
3604
3605                 NodeTimer t = env->getMap().getNodeTimer(o->m_p);
3606                 lua_pushnumber(L,t.elapsed);
3607                 return 1;
3608         }
3609
3610 public:
3611         NodeTimerRef(v3s16 p, ServerEnvironment *env):
3612                 m_p(p),
3613                 m_env(env)
3614         {
3615         }
3616
3617         ~NodeTimerRef()
3618         {
3619         }
3620
3621         // Creates an NodeTimerRef and leaves it on top of stack
3622         // Not callable from Lua; all references are created on the C side.
3623         static void create(lua_State *L, v3s16 p, ServerEnvironment *env)
3624         {
3625                 NodeTimerRef *o = new NodeTimerRef(p, env);
3626                 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
3627                 luaL_getmetatable(L, className);
3628                 lua_setmetatable(L, -2);
3629         }
3630
3631         static void set_null(lua_State *L)
3632         {
3633                 NodeTimerRef *o = checkobject(L, -1);
3634                 o->m_env = NULL;
3635         }
3636
3637         static void Register(lua_State *L)
3638         {
3639                 lua_newtable(L);
3640                 int methodtable = lua_gettop(L);
3641                 luaL_newmetatable(L, className);
3642                 int metatable = lua_gettop(L);
3643
3644                 lua_pushliteral(L, "__metatable");
3645                 lua_pushvalue(L, methodtable);
3646                 lua_settable(L, metatable);  // hide metatable from Lua getmetatable()
3647
3648                 lua_pushliteral(L, "__index");
3649                 lua_pushvalue(L, methodtable);
3650                 lua_settable(L, metatable);
3651
3652                 lua_pushliteral(L, "__gc");
3653                 lua_pushcfunction(L, gc_object);
3654                 lua_settable(L, metatable);
3655
3656                 lua_pop(L, 1);  // drop metatable
3657
3658                 luaL_openlib(L, 0, methods, 0);  // fill methodtable
3659                 lua_pop(L, 1);  // drop methodtable
3660
3661                 // Cannot be created from Lua
3662                 //lua_register(L, className, create_object);
3663         }
3664 };
3665 const char NodeTimerRef::className[] = "NodeTimerRef";
3666 const luaL_reg NodeTimerRef::methods[] = {
3667         method(NodeTimerRef, start),
3668         method(NodeTimerRef, set),
3669         method(NodeTimerRef, stop),
3670         method(NodeTimerRef, is_started),
3671         method(NodeTimerRef, get_timeout),
3672         method(NodeTimerRef, get_elapsed),
3673         {0,0}
3674 };
3675
3676 /*
3677         EnvRef
3678 */
3679
3680 class EnvRef
3681 {
3682 private:
3683         ServerEnvironment *m_env;
3684
3685         static const char className[];
3686         static const luaL_reg methods[];
3687
3688         static int gc_object(lua_State *L) {
3689                 EnvRef *o = *(EnvRef **)(lua_touserdata(L, 1));
3690                 delete o;
3691                 return 0;
3692         }
3693
3694         static EnvRef *checkobject(lua_State *L, int narg)
3695         {
3696                 luaL_checktype(L, narg, LUA_TUSERDATA);
3697                 void *ud = luaL_checkudata(L, narg, className);
3698                 if(!ud) luaL_typerror(L, narg, className);
3699                 return *(EnvRef**)ud;  // unbox pointer
3700         }
3701
3702         // Exported functions
3703
3704         // EnvRef:set_node(pos, node)
3705         // pos = {x=num, y=num, z=num}
3706         static int l_set_node(lua_State *L)
3707         {
3708                 EnvRef *o = checkobject(L, 1);
3709                 ServerEnvironment *env = o->m_env;
3710                 if(env == NULL) return 0;
3711                 INodeDefManager *ndef = env->getGameDef()->ndef();
3712                 // parameters
3713                 v3s16 pos = read_v3s16(L, 2);
3714                 MapNode n = readnode(L, 3, ndef);
3715                 // Do it
3716                 bool succeeded = env->setNode(pos, n);
3717                 lua_pushboolean(L, succeeded);
3718                 return 1;
3719         }
3720
3721         static int l_add_node(lua_State *L)
3722         {
3723                 return l_set_node(L);
3724         }
3725
3726         // EnvRef:remove_node(pos)
3727         // pos = {x=num, y=num, z=num}
3728         static int l_remove_node(lua_State *L)
3729         {
3730                 EnvRef *o = checkobject(L, 1);
3731                 ServerEnvironment *env = o->m_env;
3732                 if(env == NULL) return 0;
3733                 INodeDefManager *ndef = env->getGameDef()->ndef();
3734                 // parameters
3735                 v3s16 pos = read_v3s16(L, 2);
3736                 // Do it
3737                 bool succeeded = env->removeNode(pos);
3738                 lua_pushboolean(L, succeeded);
3739                 return 1;
3740         }
3741
3742         // EnvRef:get_node(pos)
3743         // pos = {x=num, y=num, z=num}
3744         static int l_get_node(lua_State *L)
3745         {
3746                 EnvRef *o = checkobject(L, 1);
3747                 ServerEnvironment *env = o->m_env;
3748                 if(env == NULL) return 0;
3749                 // pos
3750                 v3s16 pos = read_v3s16(L, 2);
3751                 // Do it
3752                 MapNode n = env->getMap().getNodeNoEx(pos);
3753                 // Return node
3754                 pushnode(L, n, env->getGameDef()->ndef());
3755                 return 1;
3756         }
3757
3758         // EnvRef:get_node_or_nil(pos)
3759         // pos = {x=num, y=num, z=num}
3760         static int l_get_node_or_nil(lua_State *L)
3761         {
3762                 EnvRef *o = checkobject(L, 1);
3763                 ServerEnvironment *env = o->m_env;
3764                 if(env == NULL) return 0;
3765                 // pos
3766                 v3s16 pos = read_v3s16(L, 2);
3767                 // Do it
3768                 try{
3769                         MapNode n = env->getMap().getNode(pos);
3770                         // Return node
3771                         pushnode(L, n, env->getGameDef()->ndef());
3772                         return 1;
3773                 } catch(InvalidPositionException &e)
3774                 {
3775                         lua_pushnil(L);
3776                         return 1;
3777                 }
3778         }
3779
3780         // EnvRef:get_node_light(pos, timeofday)
3781         // pos = {x=num, y=num, z=num}
3782         // timeofday: nil = current time, 0 = night, 0.5 = day
3783         static int l_get_node_light(lua_State *L)
3784         {
3785                 EnvRef *o = checkobject(L, 1);
3786                 ServerEnvironment *env = o->m_env;
3787                 if(env == NULL) return 0;
3788                 // Do it
3789                 v3s16 pos = read_v3s16(L, 2);
3790                 u32 time_of_day = env->getTimeOfDay();
3791                 if(lua_isnumber(L, 3))
3792                         time_of_day = 24000.0 * lua_tonumber(L, 3);
3793                 time_of_day %= 24000;
3794                 u32 dnr = time_to_daynight_ratio(time_of_day, true);
3795                 MapNode n = env->getMap().getNodeNoEx(pos);
3796                 try{
3797                         MapNode n = env->getMap().getNode(pos);
3798                         INodeDefManager *ndef = env->getGameDef()->ndef();
3799                         lua_pushinteger(L, n.getLightBlend(dnr, ndef));
3800                         return 1;
3801                 } catch(InvalidPositionException &e)
3802                 {
3803                         lua_pushnil(L);
3804                         return 1;
3805                 }
3806         }
3807
3808         // EnvRef:place_node(pos, node)
3809         // pos = {x=num, y=num, z=num}
3810         static int l_place_node(lua_State *L)
3811         {
3812                 EnvRef *o = checkobject(L, 1);
3813                 ServerEnvironment *env = o->m_env;
3814                 if(env == NULL) return 0;
3815                 v3s16 pos = read_v3s16(L, 2);
3816                 MapNode n = readnode(L, 3, env->getGameDef()->ndef());
3817
3818                 // Don't attempt to load non-loaded area as of now
3819                 MapNode n_old = env->getMap().getNodeNoEx(pos);
3820                 if(n_old.getContent() == CONTENT_IGNORE){
3821                         lua_pushboolean(L, false);
3822                         return 1;
3823                 }
3824                 // Create item to place
3825                 INodeDefManager *ndef = get_server(L)->ndef();
3826                 IItemDefManager *idef = get_server(L)->idef();
3827                 ItemStack item(ndef->get(n).name, 1, 0, "", idef);
3828                 // Make pointed position
3829                 PointedThing pointed;
3830                 pointed.type = POINTEDTHING_NODE;
3831                 pointed.node_abovesurface = pos;
3832                 pointed.node_undersurface = pos + v3s16(0,-1,0);
3833                 // Place it with a NULL placer (appears in Lua as a non-functional
3834                 // ObjectRef)
3835                 bool success = scriptapi_item_on_place(L, item, NULL, pointed);
3836                 lua_pushboolean(L, success);
3837                 return 1;
3838         }
3839
3840         // EnvRef:dig_node(pos)
3841         // pos = {x=num, y=num, z=num}
3842         static int l_dig_node(lua_State *L)
3843         {
3844                 EnvRef *o = checkobject(L, 1);
3845                 ServerEnvironment *env = o->m_env;
3846                 if(env == NULL) return 0;
3847                 v3s16 pos = read_v3s16(L, 2);
3848
3849                 // Don't attempt to load non-loaded area as of now
3850                 MapNode n = env->getMap().getNodeNoEx(pos);
3851                 if(n.getContent() == CONTENT_IGNORE){
3852                         lua_pushboolean(L, false);
3853                         return 1;
3854                 }
3855                 // Dig it out with a NULL digger (appears in Lua as a
3856                 // non-functional ObjectRef)
3857                 bool success = scriptapi_node_on_dig(L, pos, n, NULL);
3858                 lua_pushboolean(L, success);
3859                 return 1;
3860         }
3861
3862         // EnvRef:punch_node(pos)
3863         // pos = {x=num, y=num, z=num}
3864         static int l_punch_node(lua_State *L)
3865         {
3866                 EnvRef *o = checkobject(L, 1);
3867                 ServerEnvironment *env = o->m_env;
3868                 if(env == NULL) return 0;
3869                 v3s16 pos = read_v3s16(L, 2);
3870
3871                 // Don't attempt to load non-loaded area as of now
3872                 MapNode n = env->getMap().getNodeNoEx(pos);
3873                 if(n.getContent() == CONTENT_IGNORE){
3874                         lua_pushboolean(L, false);
3875                         return 1;
3876                 }
3877                 // Punch it with a NULL puncher (appears in Lua as a non-functional
3878                 // ObjectRef)
3879                 bool success = scriptapi_node_on_punch(L, pos, n, NULL);
3880                 lua_pushboolean(L, success);
3881                 return 1;
3882         }
3883
3884         // EnvRef:get_meta(pos)
3885         static int l_get_meta(lua_State *L)
3886         {
3887                 //infostream<<"EnvRef::l_get_meta()"<<std::endl;
3888                 EnvRef *o = checkobject(L, 1);
3889                 ServerEnvironment *env = o->m_env;
3890                 if(env == NULL) return 0;
3891                 // Do it
3892                 v3s16 p = read_v3s16(L, 2);
3893                 NodeMetaRef::create(L, p, env);
3894                 return 1;
3895         }
3896
3897         // EnvRef:get_node_timer(pos)
3898         static int l_get_node_timer(lua_State *L)
3899         {
3900                 EnvRef *o = checkobject(L, 1);
3901                 ServerEnvironment *env = o->m_env;
3902                 if(env == NULL) return 0;
3903                 // Do it
3904                 v3s16 p = read_v3s16(L, 2);
3905                 NodeTimerRef::create(L, p, env);
3906                 return 1;
3907         }
3908
3909         // EnvRef:add_entity(pos, entityname) -> ObjectRef or nil
3910         // pos = {x=num, y=num, z=num}
3911         static int l_add_entity(lua_State *L)
3912         {
3913                 //infostream<<"EnvRef::l_add_entity()"<<std::endl;
3914                 EnvRef *o = checkobject(L, 1);
3915                 ServerEnvironment *env = o->m_env;
3916                 if(env == NULL) return 0;
3917                 // pos
3918                 v3f pos = checkFloatPos(L, 2);
3919                 // content
3920                 const char *name = luaL_checkstring(L, 3);
3921                 // Do it
3922                 ServerActiveObject *obj = new LuaEntitySAO(env, pos, name, "");
3923                 int objectid = env->addActiveObject(obj);
3924                 // If failed to add, return nothing (reads as nil)
3925                 if(objectid == 0)
3926                         return 0;
3927                 // Return ObjectRef
3928                 objectref_get_or_create(L, obj);
3929                 return 1;
3930         }
3931
3932         // EnvRef:add_item(pos, itemstack or itemstring or table) -> ObjectRef or nil
3933         // pos = {x=num, y=num, z=num}
3934         static int l_add_item(lua_State *L)
3935         {
3936                 //infostream<<"EnvRef::l_add_item()"<<std::endl;
3937                 EnvRef *o = checkobject(L, 1);
3938                 ServerEnvironment *env = o->m_env;
3939                 if(env == NULL) return 0;
3940                 // pos
3941                 v3f pos = checkFloatPos(L, 2);
3942                 // item
3943                 ItemStack item = read_item(L, 3);
3944                 if(item.empty() || !item.isKnown(get_server(L)->idef()))
3945                         return 0;
3946                 // Use minetest.spawn_item to spawn a __builtin:item
3947                 lua_getglobal(L, "minetest");
3948                 lua_getfield(L, -1, "spawn_item");
3949                 if(lua_isnil(L, -1))
3950                         return 0;
3951                 lua_pushvalue(L, 2);
3952                 lua_pushstring(L, item.getItemString().c_str());
3953                 if(lua_pcall(L, 2, 1, 0))
3954                         script_error(L, "error: %s", lua_tostring(L, -1));
3955                 return 1;
3956                 /*lua_pushvalue(L, 1);
3957                 lua_pushstring(L, "__builtin:item");
3958                 lua_pushstring(L, item.getItemString().c_str());
3959                 return l_add_entity(L);*/
3960                 /*// Do it
3961                 ServerActiveObject *obj = createItemSAO(env, pos, item.getItemString());
3962                 int objectid = env->addActiveObject(obj);
3963                 // If failed to add, return nothing (reads as nil)
3964                 if(objectid == 0)
3965                         return 0;
3966                 // Return ObjectRef
3967                 objectref_get_or_create(L, obj);
3968                 return 1;*/
3969         }
3970
3971         // EnvRef:add_rat(pos)
3972         // pos = {x=num, y=num, z=num}
3973         static int l_add_rat(lua_State *L)
3974         {
3975                 infostream<<"EnvRef::l_add_rat(): C++ mobs have been removed."
3976                                 <<" Doing nothing."<<std::endl;
3977                 return 0;
3978         }
3979
3980         // EnvRef:add_firefly(pos)
3981         // pos = {x=num, y=num, z=num}
3982         static int l_add_firefly(lua_State *L)
3983         {
3984                 infostream<<"EnvRef::l_add_firefly(): C++ mobs have been removed."
3985                                 <<" Doing nothing."<<std::endl;
3986                 return 0;
3987         }
3988
3989         // EnvRef:get_player_by_name(name)
3990         static int l_get_player_by_name(lua_State *L)
3991         {
3992                 EnvRef *o = checkobject(L, 1);
3993                 ServerEnvironment *env = o->m_env;
3994                 if(env == NULL) return 0;
3995                 // Do it
3996                 const char *name = luaL_checkstring(L, 2);
3997                 Player *player = env->getPlayer(name);
3998                 if(player == NULL){
3999                         lua_pushnil(L);
4000                         return 1;
4001                 }
4002                 PlayerSAO *sao = player->getPlayerSAO();
4003                 if(sao == NULL){
4004                         lua_pushnil(L);
4005                         return 1;
4006                 }
4007                 // Put player on stack
4008                 objectref_get_or_create(L, sao);
4009                 return 1;
4010         }
4011
4012         // EnvRef:get_objects_inside_radius(pos, radius)
4013         static int l_get_objects_inside_radius(lua_State *L)
4014         {
4015                 // Get the table insert function
4016                 lua_getglobal(L, "table");
4017                 lua_getfield(L, -1, "insert");
4018                 int table_insert = lua_gettop(L);
4019                 // Get environemnt
4020                 EnvRef *o = checkobject(L, 1);
4021                 ServerEnvironment *env = o->m_env;
4022                 if(env == NULL) return 0;
4023                 // Do it
4024                 v3f pos = checkFloatPos(L, 2);
4025                 float radius = luaL_checknumber(L, 3) * BS;
4026                 std::set<u16> ids = env->getObjectsInsideRadius(pos, radius);
4027                 lua_newtable(L);
4028                 int table = lua_gettop(L);
4029                 for(std::set<u16>::const_iterator
4030                                 i = ids.begin(); i != ids.end(); i++){
4031                         ServerActiveObject *obj = env->getActiveObject(*i);
4032                         // Insert object reference into table
4033                         lua_pushvalue(L, table_insert);
4034                         lua_pushvalue(L, table);
4035                         objectref_get_or_create(L, obj);
4036                         if(lua_pcall(L, 2, 0, 0))
4037                                 script_error(L, "error: %s", lua_tostring(L, -1));
4038                 }
4039                 return 1;
4040         }
4041
4042         // EnvRef:set_timeofday(val)
4043         // val = 0...1
4044         static int l_set_timeofday(lua_State *L)
4045         {
4046                 EnvRef *o = checkobject(L, 1);
4047                 ServerEnvironment *env = o->m_env;
4048                 if(env == NULL) return 0;
4049                 // Do it
4050                 float timeofday_f = luaL_checknumber(L, 2);
4051                 assert(timeofday_f >= 0.0 && timeofday_f <= 1.0);
4052                 int timeofday_mh = (int)(timeofday_f * 24000.0);
4053                 // This should be set directly in the environment but currently
4054                 // such changes aren't immediately sent to the clients, so call
4055                 // the server instead.
4056                 //env->setTimeOfDay(timeofday_mh);
4057                 get_server(L)->setTimeOfDay(timeofday_mh);
4058                 return 0;
4059         }
4060
4061         // EnvRef:get_timeofday() -> 0...1
4062         static int l_get_timeofday(lua_State *L)
4063         {
4064                 EnvRef *o = checkobject(L, 1);
4065                 ServerEnvironment *env = o->m_env;
4066                 if(env == NULL) return 0;
4067                 // Do it
4068                 int timeofday_mh = env->getTimeOfDay();
4069                 float timeofday_f = (float)timeofday_mh / 24000.0;
4070                 lua_pushnumber(L, timeofday_f);
4071                 return 1;
4072         }
4073
4074
4075         // EnvRef:find_node_near(pos, radius, nodenames) -> pos or nil
4076         // nodenames: eg. {"ignore", "group:tree"} or "default:dirt"
4077         static int l_find_node_near(lua_State *L)
4078         {
4079                 EnvRef *o = checkobject(L, 1);
4080                 ServerEnvironment *env = o->m_env;
4081                 if(env == NULL) return 0;
4082                 INodeDefManager *ndef = get_server(L)->ndef();
4083                 v3s16 pos = read_v3s16(L, 2);
4084                 int radius = luaL_checkinteger(L, 3);
4085                 std::set<content_t> filter;
4086                 if(lua_istable(L, 4)){
4087                         int table = 4;
4088                         lua_pushnil(L);
4089                         while(lua_next(L, table) != 0){
4090                                 // key at index -2 and value at index -1
4091                                 luaL_checktype(L, -1, LUA_TSTRING);
4092                                 ndef->getIds(lua_tostring(L, -1), filter);
4093                                 // removes value, keeps key for next iteration
4094                                 lua_pop(L, 1);
4095                         }
4096                 } else if(lua_isstring(L, 4)){
4097                         ndef->getIds(lua_tostring(L, 4), filter);
4098                 }
4099
4100                 for(int d=1; d<=radius; d++){
4101                         core::list<v3s16> list;
4102                         getFacePositions(list, d);
4103                         for(core::list<v3s16>::Iterator i = list.begin();
4104                                         i != list.end(); i++){
4105                                 v3s16 p = pos + (*i);
4106                                 content_t c = env->getMap().getNodeNoEx(p).getContent();
4107                                 if(filter.count(c) != 0){
4108                                         push_v3s16(L, p);
4109                                         return 1;
4110                                 }
4111                         }
4112                 }
4113                 return 0;
4114         }
4115
4116         // EnvRef:find_nodes_in_area(minp, maxp, nodenames) -> list of positions
4117         // nodenames: eg. {"ignore", "group:tree"} or "default:dirt"
4118         static int l_find_nodes_in_area(lua_State *L)
4119         {
4120                 EnvRef *o = checkobject(L, 1);
4121                 ServerEnvironment *env = o->m_env;
4122                 if(env == NULL) return 0;
4123                 INodeDefManager *ndef = get_server(L)->ndef();
4124                 v3s16 minp = read_v3s16(L, 2);
4125                 v3s16 maxp = read_v3s16(L, 3);
4126                 std::set<content_t> filter;
4127                 if(lua_istable(L, 4)){
4128                         int table = 4;
4129                         lua_pushnil(L);
4130                         while(lua_next(L, table) != 0){
4131                                 // key at index -2 and value at index -1
4132                                 luaL_checktype(L, -1, LUA_TSTRING);
4133                                 ndef->getIds(lua_tostring(L, -1), filter);
4134                                 // removes value, keeps key for next iteration
4135                                 lua_pop(L, 1);
4136                         }
4137                 } else if(lua_isstring(L, 4)){
4138                         ndef->getIds(lua_tostring(L, 4), filter);
4139                 }
4140
4141                 // Get the table insert function
4142                 lua_getglobal(L, "table");
4143                 lua_getfield(L, -1, "insert");
4144                 int table_insert = lua_gettop(L);
4145
4146                 lua_newtable(L);
4147                 int table = lua_gettop(L);
4148                 for(s16 x=minp.X; x<=maxp.X; x++)
4149                 for(s16 y=minp.Y; y<=maxp.Y; y++)
4150                 for(s16 z=minp.Z; z<=maxp.Z; z++)
4151                 {
4152                         v3s16 p(x,y,z);
4153                         content_t c = env->getMap().getNodeNoEx(p).getContent();
4154                         if(filter.count(c) != 0){
4155                                 lua_pushvalue(L, table_insert);
4156                                 lua_pushvalue(L, table);
4157                                 push_v3s16(L, p);
4158                                 if(lua_pcall(L, 2, 0, 0))
4159                                         script_error(L, "error: %s", lua_tostring(L, -1));
4160                         }
4161                 }
4162                 return 1;
4163         }
4164
4165         //      EnvRef:get_perlin(seeddiff, octaves, persistence, scale)
4166         //  returns world-specific PerlinNoise
4167         static int l_get_perlin(lua_State *L)
4168         {
4169                 EnvRef *o = checkobject(L, 1);
4170                 ServerEnvironment *env = o->m_env;
4171                 if(env == NULL) return 0;
4172
4173                 int seeddiff = luaL_checkint(L, 2);
4174                 int octaves = luaL_checkint(L, 3);
4175                 float persistence = luaL_checknumber(L, 4);
4176                 float scale = luaL_checknumber(L, 5);
4177
4178                 LuaPerlinNoise *n = new LuaPerlinNoise(seeddiff + int(env->getServerMap().getSeed()), octaves, persistence, scale);
4179                 *(void **)(lua_newuserdata(L, sizeof(void *))) = n;
4180                 luaL_getmetatable(L, "PerlinNoise");
4181                 lua_setmetatable(L, -2);
4182                 return 1;
4183         }
4184     
4185         //  EnvRef:get_perlin_map(noiseparams, size)
4186         //  returns world-specific PerlinNoiseMap
4187         static int l_get_perlin_map(lua_State *L)
4188         {
4189                 EnvRef *o = checkobject(L, 1);
4190                 ServerEnvironment *env = o->m_env;
4191                 if (env == NULL)
4192                         return 0;
4193                 
4194                 NoiseParams *np = read_noiseparams(L, 2);
4195                 if (!np)
4196                         return 0;
4197                 v3s16 size = read_v3s16(L, 3);
4198                 
4199                 int seed = (int)(env->getServerMap().getSeed());
4200                 LuaPerlinNoiseMap *n = new LuaPerlinNoiseMap(np, seed, size);
4201                 *(void **)(lua_newuserdata(L, sizeof(void *))) = n;
4202                 luaL_getmetatable(L, "PerlinNoiseMap");
4203                 lua_setmetatable(L, -2);
4204                 return 1;
4205         }
4206
4207         // EnvRef:clear_objects()
4208         // clear all objects in the environment
4209         static int l_clear_objects(lua_State *L)
4210         {
4211                 EnvRef *o = checkobject(L, 1);
4212                 o->m_env->clearAllObjects();
4213                 return 0;
4214         }
4215
4216         static int l_spawn_tree(lua_State *L)
4217         {
4218                 EnvRef *o = checkobject(L, 1);
4219                 ServerEnvironment *env = o->m_env;
4220                 if(env == NULL) return 0;
4221                 v3s16 p0 = read_v3s16(L, 2);
4222
4223                 treegen::TreeDef tree_def;
4224                 std::string trunk,leaves,fruit;
4225                 INodeDefManager *ndef = env->getGameDef()->ndef();
4226
4227                 if(lua_istable(L, 3))
4228                 {
4229                         getstringfield(L, 3, "axiom", tree_def.initial_axiom);
4230                         getstringfield(L, 3, "rules_a", tree_def.rules_a);
4231                         getstringfield(L, 3, "rules_b", tree_def.rules_b);
4232                         getstringfield(L, 3, "rules_c", tree_def.rules_c);
4233                         getstringfield(L, 3, "rules_d", tree_def.rules_d);
4234                         getstringfield(L, 3, "trunk", trunk);
4235                         tree_def.trunknode=ndef->getId(trunk);
4236                         getstringfield(L, 3, "leaves", leaves);
4237                         tree_def.leavesnode=ndef->getId(leaves);
4238                         tree_def.leaves2_chance=0;
4239                         getstringfield(L, 3, "leaves2", leaves);
4240                         if (leaves !="")
4241                         {
4242                                 tree_def.leaves2node=ndef->getId(leaves);
4243                                 getintfield(L, 3, "leaves2_chance", tree_def.leaves2_chance);
4244                         }
4245                         getintfield(L, 3, "angle", tree_def.angle);
4246                         getintfield(L, 3, "iterations", tree_def.iterations);
4247                         getintfield(L, 3, "random_level", tree_def.iterations_random_level);
4248                         getstringfield(L, 3, "trunk_type", tree_def.trunk_type);
4249                         getboolfield(L, 3, "thin_branches", tree_def.thin_branches);
4250                         tree_def.fruit_chance=0;
4251                         getstringfield(L, 3, "fruit", fruit);
4252                         if (fruit != "")
4253                         {
4254                                 tree_def.fruitnode=ndef->getId(fruit);
4255                                 getintfield(L, 3, "fruit_chance",tree_def.fruit_chance);
4256                         }
4257                         getintfield(L, 3, "seed", tree_def.seed);
4258                 }
4259                 else
4260                         return 0;
4261                 treegen::spawn_ltree (env, p0, ndef, tree_def);
4262                 return 1;
4263         }
4264
4265 public:
4266         EnvRef(ServerEnvironment *env):
4267                 m_env(env)
4268         {
4269                 //infostream<<"EnvRef created"<<std::endl;
4270         }
4271
4272         ~EnvRef()
4273         {
4274                 //infostream<<"EnvRef destructing"<<std::endl;
4275         }
4276
4277         // Creates an EnvRef and leaves it on top of stack
4278         // Not callable from Lua; all references are created on the C side.
4279         static void create(lua_State *L, ServerEnvironment *env)
4280         {
4281                 EnvRef *o = new EnvRef(env);
4282                 //infostream<<"EnvRef::create: o="<<o<<std::endl;
4283                 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
4284                 luaL_getmetatable(L, className);
4285                 lua_setmetatable(L, -2);
4286         }
4287
4288         static void set_null(lua_State *L)
4289         {
4290                 EnvRef *o = checkobject(L, -1);
4291                 o->m_env = NULL;
4292         }
4293
4294         static void Register(lua_State *L)
4295         {
4296                 lua_newtable(L);
4297                 int methodtable = lua_gettop(L);
4298                 luaL_newmetatable(L, className);
4299                 int metatable = lua_gettop(L);
4300
4301                 lua_pushliteral(L, "__metatable");
4302                 lua_pushvalue(L, methodtable);
4303                 lua_settable(L, metatable);  // hide metatable from Lua getmetatable()
4304
4305                 lua_pushliteral(L, "__index");
4306                 lua_pushvalue(L, methodtable);
4307                 lua_settable(L, metatable);
4308
4309                 lua_pushliteral(L, "__gc");
4310                 lua_pushcfunction(L, gc_object);
4311                 lua_settable(L, metatable);
4312
4313                 lua_pop(L, 1);  // drop metatable
4314
4315                 luaL_openlib(L, 0, methods, 0);  // fill methodtable
4316                 lua_pop(L, 1);  // drop methodtable
4317
4318                 // Cannot be created from Lua
4319                 //lua_register(L, className, create_object);
4320         }
4321 };
4322 const char EnvRef::className[] = "EnvRef";
4323 const luaL_reg EnvRef::methods[] = {
4324         method(EnvRef, set_node),
4325         method(EnvRef, add_node),
4326         method(EnvRef, remove_node),
4327         method(EnvRef, get_node),
4328         method(EnvRef, get_node_or_nil),
4329         method(EnvRef, get_node_light),
4330         method(EnvRef, place_node),
4331         method(EnvRef, dig_node),
4332         method(EnvRef, punch_node),
4333         method(EnvRef, add_entity),
4334         method(EnvRef, add_item),
4335         method(EnvRef, add_rat),
4336         method(EnvRef, add_firefly),
4337         method(EnvRef, get_meta),
4338         method(EnvRef, get_node_timer),
4339         method(EnvRef, get_player_by_name),
4340         method(EnvRef, get_objects_inside_radius),
4341         method(EnvRef, set_timeofday),
4342         method(EnvRef, get_timeofday),
4343         method(EnvRef, find_node_near),
4344         method(EnvRef, find_nodes_in_area),
4345         method(EnvRef, get_perlin),
4346         method(EnvRef, get_perlin_map),
4347         method(EnvRef, clear_objects),
4348         method(EnvRef, spawn_tree),
4349         {0,0}
4350 };
4351
4352 /*
4353         LuaPseudoRandom
4354 */
4355
4356
4357 class LuaPseudoRandom
4358 {
4359 private:
4360         PseudoRandom m_pseudo;
4361
4362         static const char className[];
4363         static const luaL_reg methods[];
4364
4365         // Exported functions
4366
4367         // garbage collector
4368         static int gc_object(lua_State *L)
4369         {
4370                 LuaPseudoRandom *o = *(LuaPseudoRandom **)(lua_touserdata(L, 1));
4371                 delete o;
4372                 return 0;
4373         }
4374
4375         // next(self, min=0, max=32767) -> get next value
4376         static int l_next(lua_State *L)
4377         {
4378                 LuaPseudoRandom *o = checkobject(L, 1);
4379                 int min = 0;
4380                 int max = 32767;
4381                 lua_settop(L, 3); // Fill 2 and 3 with nil if they don't exist
4382                 if(!lua_isnil(L, 2))
4383                         min = luaL_checkinteger(L, 2);
4384                 if(!lua_isnil(L, 3))
4385                         max = luaL_checkinteger(L, 3);
4386                 if(max < min){
4387                         errorstream<<"PseudoRandom.next(): max="<<max<<" min="<<min<<std::endl;
4388                         throw LuaError(L, "PseudoRandom.next(): max < min");
4389                 }
4390                 if(max - min != 32767 && max - min > 32767/5)
4391                         throw LuaError(L, "PseudoRandom.next() max-min is not 32767 and is > 32768/5. This is disallowed due to the bad random distribution the implementation would otherwise make.");
4392                 PseudoRandom &pseudo = o->m_pseudo;
4393                 int val = pseudo.next();
4394                 val = (val % (max-min+1)) + min;
4395                 lua_pushinteger(L, val);
4396                 return 1;
4397         }
4398
4399 public:
4400         LuaPseudoRandom(int seed):
4401                 m_pseudo(seed)
4402         {
4403         }
4404
4405         ~LuaPseudoRandom()
4406         {
4407         }
4408
4409         const PseudoRandom& getItem() const
4410         {
4411                 return m_pseudo;
4412         }
4413         PseudoRandom& getItem()
4414         {
4415                 return m_pseudo;
4416         }
4417
4418         // LuaPseudoRandom(seed)
4419         // Creates an LuaPseudoRandom and leaves it on top of stack
4420         static int create_object(lua_State *L)
4421         {
4422                 int seed = luaL_checknumber(L, 1);
4423                 LuaPseudoRandom *o = new LuaPseudoRandom(seed);
4424                 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
4425                 luaL_getmetatable(L, className);
4426                 lua_setmetatable(L, -2);
4427                 return 1;
4428         }
4429
4430         static LuaPseudoRandom* checkobject(lua_State *L, int narg)
4431         {
4432                 luaL_checktype(L, narg, LUA_TUSERDATA);
4433                 void *ud = luaL_checkudata(L, narg, className);
4434                 if(!ud) luaL_typerror(L, narg, className);
4435                 return *(LuaPseudoRandom**)ud;  // unbox pointer
4436         }
4437
4438         static void Register(lua_State *L)
4439         {
4440                 lua_newtable(L);
4441                 int methodtable = lua_gettop(L);
4442                 luaL_newmetatable(L, className);
4443                 int metatable = lua_gettop(L);
4444
4445                 lua_pushliteral(L, "__metatable");
4446                 lua_pushvalue(L, methodtable);
4447                 lua_settable(L, metatable);  // hide metatable from Lua getmetatable()
4448
4449                 lua_pushliteral(L, "__index");
4450                 lua_pushvalue(L, methodtable);
4451                 lua_settable(L, metatable);
4452
4453                 lua_pushliteral(L, "__gc");
4454                 lua_pushcfunction(L, gc_object);
4455                 lua_settable(L, metatable);
4456
4457                 lua_pop(L, 1);  // drop metatable
4458
4459                 luaL_openlib(L, 0, methods, 0);  // fill methodtable
4460                 lua_pop(L, 1);  // drop methodtable
4461
4462                 // Can be created from Lua (LuaPseudoRandom(seed))
4463                 lua_register(L, className, create_object);
4464         }
4465 };
4466 const char LuaPseudoRandom::className[] = "PseudoRandom";
4467 const luaL_reg LuaPseudoRandom::methods[] = {
4468         method(LuaPseudoRandom, next),
4469         {0,0}
4470 };
4471
4472
4473
4474 /*
4475         LuaABM
4476 */
4477
4478 class LuaABM : public ActiveBlockModifier
4479 {
4480 private:
4481         lua_State *m_lua;
4482         int m_id;
4483
4484         std::set<std::string> m_trigger_contents;
4485         std::set<std::string> m_required_neighbors;
4486         float m_trigger_interval;
4487         u32 m_trigger_chance;
4488 public:
4489         LuaABM(lua_State *L, int id,
4490                         const std::set<std::string> &trigger_contents,
4491                         const std::set<std::string> &required_neighbors,
4492                         float trigger_interval, u32 trigger_chance):
4493                 m_lua(L),
4494                 m_id(id),
4495                 m_trigger_contents(trigger_contents),
4496                 m_required_neighbors(required_neighbors),
4497                 m_trigger_interval(trigger_interval),
4498                 m_trigger_chance(trigger_chance)
4499         {
4500         }
4501         virtual std::set<std::string> getTriggerContents()
4502         {
4503                 return m_trigger_contents;
4504         }
4505         virtual std::set<std::string> getRequiredNeighbors()
4506         {
4507                 return m_required_neighbors;
4508         }
4509         virtual float getTriggerInterval()
4510         {
4511                 return m_trigger_interval;
4512         }
4513         virtual u32 getTriggerChance()
4514         {
4515                 return m_trigger_chance;
4516         }
4517         virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n,
4518                         u32 active_object_count, u32 active_object_count_wider)
4519         {
4520                 lua_State *L = m_lua;
4521
4522                 realitycheck(L);
4523                 assert(lua_checkstack(L, 20));
4524                 StackUnroller stack_unroller(L);
4525
4526                 // Get minetest.registered_abms
4527                 lua_getglobal(L, "minetest");
4528                 lua_getfield(L, -1, "registered_abms");
4529                 luaL_checktype(L, -1, LUA_TTABLE);
4530                 int registered_abms = lua_gettop(L);
4531
4532                 // Get minetest.registered_abms[m_id]
4533                 lua_pushnumber(L, m_id);
4534                 lua_gettable(L, registered_abms);
4535                 if(lua_isnil(L, -1))
4536                         assert(0);
4537
4538                 // Call action
4539                 luaL_checktype(L, -1, LUA_TTABLE);
4540                 lua_getfield(L, -1, "action");
4541                 luaL_checktype(L, -1, LUA_TFUNCTION);
4542                 push_v3s16(L, p);
4543                 pushnode(L, n, env->getGameDef()->ndef());
4544                 lua_pushnumber(L, active_object_count);
4545                 lua_pushnumber(L, active_object_count_wider);
4546                 if(lua_pcall(L, 4, 0, 0))
4547                         script_error(L, "error: %s", lua_tostring(L, -1));
4548         }
4549 };
4550
4551 /*
4552         ServerSoundParams
4553 */
4554
4555 static void read_server_sound_params(lua_State *L, int index,
4556                 ServerSoundParams &params)
4557 {
4558         if(index < 0)
4559                 index = lua_gettop(L) + 1 + index;
4560         // Clear
4561         params = ServerSoundParams();
4562         if(lua_istable(L, index)){
4563                 getfloatfield(L, index, "gain", params.gain);
4564                 getstringfield(L, index, "to_player", params.to_player);
4565                 lua_getfield(L, index, "pos");
4566                 if(!lua_isnil(L, -1)){
4567                         v3f p = read_v3f(L, -1)*BS;
4568                         params.pos = p;
4569                         params.type = ServerSoundParams::SSP_POSITIONAL;
4570                 }
4571                 lua_pop(L, 1);
4572                 lua_getfield(L, index, "object");
4573                 if(!lua_isnil(L, -1)){
4574                         ObjectRef *ref = ObjectRef::checkobject(L, -1);
4575                         ServerActiveObject *sao = ObjectRef::getobject(ref);
4576                         if(sao){
4577                                 params.object = sao->getId();
4578                                 params.type = ServerSoundParams::SSP_OBJECT;
4579                         }
4580                 }
4581                 lua_pop(L, 1);
4582                 params.max_hear_distance = BS*getfloatfield_default(L, index,
4583                                 "max_hear_distance", params.max_hear_distance/BS);
4584                 getboolfield(L, index, "loop", params.loop);
4585         }
4586 }
4587
4588 /*
4589         Global functions
4590 */
4591
4592 // debug(text)
4593 // Writes a line to dstream
4594 static int l_debug(lua_State *L)
4595 {
4596         std::string text = lua_tostring(L, 1);
4597         dstream << text << std::endl;
4598         return 0;
4599 }
4600
4601 // log([level,] text)
4602 // Writes a line to the logger.
4603 // The one-argument version logs to infostream.
4604 // The two-argument version accept a log level: error, action, info, or verbose.
4605 static int l_log(lua_State *L)
4606 {
4607         std::string text;
4608         LogMessageLevel level = LMT_INFO;
4609         if(lua_isnone(L, 2))
4610         {
4611                 text = lua_tostring(L, 1);
4612         }
4613         else
4614         {
4615                 std::string levelname = luaL_checkstring(L, 1);
4616                 text = luaL_checkstring(L, 2);
4617                 if(levelname == "error")
4618                         level = LMT_ERROR;
4619                 else if(levelname == "action")
4620                         level = LMT_ACTION;
4621                 else if(levelname == "verbose")
4622                         level = LMT_VERBOSE;
4623         }
4624         log_printline(level, text);
4625         return 0;
4626 }
4627
4628 // request_shutdown()
4629 static int l_request_shutdown(lua_State *L)
4630 {
4631         get_server(L)->requestShutdown();
4632         return 0;
4633 }
4634
4635 // get_server_status()
4636 static int l_get_server_status(lua_State *L)
4637 {
4638         lua_pushstring(L, wide_to_narrow(get_server(L)->getStatusString()).c_str());
4639         return 1;
4640 }
4641
4642 // register_biome_groups({frequencies})
4643 static int l_register_biome_groups(lua_State *L)
4644 {
4645         luaL_checktype(L, 1, LUA_TTABLE);
4646         int index = 1;
4647         if (!lua_istable(L, index))
4648                 throw LuaError(L, "register_biome_groups: parameter is not a table");
4649
4650         BiomeDefManager *bmgr = get_server(L)->getBiomeDef();
4651         if (!bmgr) {
4652                 verbosestream << "register_biome_groups: BiomeDefManager not active" << std::endl;
4653                 return 0;
4654         }
4655
4656         lua_pushnil(L);
4657         for (int i = 1; lua_next(L, index) != 0; i++) {
4658                 bmgr->addBiomeGroup(lua_tonumber(L, -1));
4659                 lua_pop(L, 1);
4660         }
4661         lua_pop(L, 1);
4662
4663         return 0;
4664 }
4665
4666 // register_biome({lots of stuff})
4667 static int l_register_biome(lua_State *L)
4668 {
4669         luaL_checktype(L, 1, LUA_TTABLE);
4670         int index = 1, groupid;
4671         std::string nodename;
4672
4673         IWritableNodeDefManager *ndef = get_server(L)->getWritableNodeDefManager();
4674         BiomeDefManager *bmgr = get_server(L)->getBiomeDef();
4675         if (!bmgr) {
4676                 verbosestream << "register_biome: BiomeDefManager not active" << std::endl;
4677                 return 0;
4678         }
4679
4680         groupid = getintfield_default(L, index, "group_id", 0);
4681
4682         enum BiomeTerrainType terrain = (BiomeTerrainType)getenumfield(L, index,
4683                                         "terrain_type", es_BiomeTerrainType, BIOME_TERRAIN_NORMAL);
4684         Biome *b = bmgr->createBiome(terrain);
4685
4686         b->name = getstringfield_default(L, index, "name", "");
4687
4688         if (getstringfield(L, index, "node_top", nodename))
4689                 b->n_top = MapNode(ndef->getId(nodename));
4690         else
4691                 b->n_top = MapNode(CONTENT_IGNORE);
4692
4693         if (getstringfield(L, index, "node_filler", nodename))
4694                 b->n_filler = MapNode(ndef->getId(nodename));
4695         else
4696                 b->n_filler = b->n_top;
4697
4698         b->ntopnodes = getintfield_default(L, index, "num_top_nodes", 0);
4699
4700         b->height_min   = getintfield_default(L, index, "height_min", 0);
4701         b->height_max   = getintfield_default(L, index, "height_max", 0);
4702         b->heat_min     = getfloatfield_default(L, index, "heat_min", 0.);
4703         b->heat_max     = getfloatfield_default(L, index, "heat_max", 0.);
4704         b->humidity_min = getfloatfield_default(L, index, "humidity_min", 0.);
4705         b->humidity_max = getfloatfield_default(L, index, "humidity_max", 0.);
4706
4707         b->np = new NoiseParams; // should read an entire NoiseParams later on...
4708         getfloatfield(L, index, "scale", b->np->scale);
4709         getfloatfield(L, index, "offset", b->np->offset);
4710
4711         b->groupid = (s8)groupid;
4712         b->flags   = 0; //reserved
4713
4714         bmgr->addBiome(b);
4715
4716         verbosestream << "register_biome: " << b->name << std::endl;
4717         return 0;
4718 }
4719
4720 // register_item_raw({lots of stuff})
4721 static int l_register_item_raw(lua_State *L)
4722 {
4723         luaL_checktype(L, 1, LUA_TTABLE);
4724         int table = 1;
4725
4726         // Get the writable item and node definition managers from the server
4727         IWritableItemDefManager *idef =
4728                         get_server(L)->getWritableItemDefManager();
4729         IWritableNodeDefManager *ndef =
4730                         get_server(L)->getWritableNodeDefManager();
4731
4732         // Check if name is defined
4733         std::string name;
4734         lua_getfield(L, table, "name");
4735         if(lua_isstring(L, -1)){
4736                 name = lua_tostring(L, -1);
4737                 verbosestream<<"register_item_raw: "<<name<<std::endl;
4738         } else {
4739                 throw LuaError(L, "register_item_raw: name is not defined or not a string");
4740         }
4741
4742         // Check if on_use is defined
4743
4744         ItemDefinition def;
4745         // Set a distinctive default value to check if this is set
4746         def.node_placement_prediction = "__default";
4747
4748         // Read the item definition
4749         def = read_item_definition(L, table, def);
4750
4751         // Default to having client-side placement prediction for nodes
4752         // ("" in item definition sets it off)
4753         if(def.node_placement_prediction == "__default"){
4754                 if(def.type == ITEM_NODE)
4755                         def.node_placement_prediction = name;
4756                 else
4757                         def.node_placement_prediction = "";
4758         }
4759
4760         // Register item definition
4761         idef->registerItem(def);
4762
4763         // Read the node definition (content features) and register it
4764         if(def.type == ITEM_NODE)
4765         {
4766                 ContentFeatures f = read_content_features(L, table);
4767                 ndef->set(f.name, f);
4768         }
4769
4770         return 0; /* number of results */
4771 }
4772
4773 // register_alias_raw(name, convert_to_name)
4774 static int l_register_alias_raw(lua_State *L)
4775 {
4776         std::string name = luaL_checkstring(L, 1);
4777         std::string convert_to = luaL_checkstring(L, 2);
4778
4779         // Get the writable item definition manager from the server
4780         IWritableItemDefManager *idef =
4781                         get_server(L)->getWritableItemDefManager();
4782
4783         idef->registerAlias(name, convert_to);
4784
4785         return 0; /* number of results */
4786 }
4787
4788 // helper for register_craft
4789 static bool read_craft_recipe_shaped(lua_State *L, int index,
4790                 int &width, std::vector<std::string> &recipe)
4791 {
4792         if(index < 0)
4793                 index = lua_gettop(L) + 1 + index;
4794
4795         if(!lua_istable(L, index))
4796                 return false;
4797
4798         lua_pushnil(L);
4799         int rowcount = 0;
4800         while(lua_next(L, index) != 0){
4801                 int colcount = 0;
4802                 // key at index -2 and value at index -1
4803                 if(!lua_istable(L, -1))
4804                         return false;
4805                 int table2 = lua_gettop(L);
4806                 lua_pushnil(L);
4807                 while(lua_next(L, table2) != 0){
4808                         // key at index -2 and value at index -1
4809                         if(!lua_isstring(L, -1))
4810                                 return false;
4811                         recipe.push_back(lua_tostring(L, -1));
4812                         // removes value, keeps key for next iteration
4813                         lua_pop(L, 1);
4814                         colcount++;
4815                 }
4816                 if(rowcount == 0){
4817                         width = colcount;
4818                 } else {
4819                         if(colcount != width)
4820                                 return false;
4821                 }
4822                 // removes value, keeps key for next iteration
4823                 lua_pop(L, 1);
4824                 rowcount++;
4825         }
4826         return width != 0;
4827 }
4828
4829 // helper for register_craft
4830 static bool read_craft_recipe_shapeless(lua_State *L, int index,
4831                 std::vector<std::string> &recipe)
4832 {
4833         if(index < 0)
4834                 index = lua_gettop(L) + 1 + index;
4835
4836         if(!lua_istable(L, index))
4837                 return false;
4838
4839         lua_pushnil(L);
4840         while(lua_next(L, index) != 0){
4841                 // key at index -2 and value at index -1
4842                 if(!lua_isstring(L, -1))
4843                         return false;
4844                 recipe.push_back(lua_tostring(L, -1));
4845                 // removes value, keeps key for next iteration
4846                 lua_pop(L, 1);
4847         }
4848         return true;
4849 }
4850
4851 // helper for register_craft
4852 static bool read_craft_replacements(lua_State *L, int index,
4853                 CraftReplacements &replacements)
4854 {
4855         if(index < 0)
4856                 index = lua_gettop(L) + 1 + index;
4857
4858         if(!lua_istable(L, index))
4859                 return false;
4860
4861         lua_pushnil(L);
4862         while(lua_next(L, index) != 0){
4863                 // key at index -2 and value at index -1
4864                 if(!lua_istable(L, -1))
4865                         return false;
4866                 lua_rawgeti(L, -1, 1);
4867                 if(!lua_isstring(L, -1))
4868                         return false;
4869                 std::string replace_from = lua_tostring(L, -1);
4870                 lua_pop(L, 1);
4871                 lua_rawgeti(L, -1, 2);
4872                 if(!lua_isstring(L, -1))
4873                         return false;
4874                 std::string replace_to = lua_tostring(L, -1);
4875                 lua_pop(L, 1);
4876                 replacements.pairs.push_back(
4877                                 std::make_pair(replace_from, replace_to));
4878                 // removes value, keeps key for next iteration
4879                 lua_pop(L, 1);
4880         }
4881         return true;
4882 }
4883 // register_craft({output=item, recipe={{item00,item10},{item01,item11}})
4884 static int l_register_craft(lua_State *L)
4885 {
4886         //infostream<<"register_craft"<<std::endl;
4887         luaL_checktype(L, 1, LUA_TTABLE);
4888         int table = 1;
4889
4890         // Get the writable craft definition manager from the server
4891         IWritableCraftDefManager *craftdef =
4892                         get_server(L)->getWritableCraftDefManager();
4893
4894         std::string type = getstringfield_default(L, table, "type", "shaped");
4895
4896         /*
4897                 CraftDefinitionShaped
4898         */
4899         if(type == "shaped"){
4900                 std::string output = getstringfield_default(L, table, "output", "");
4901                 if(output == "")
4902                         throw LuaError(L, "Crafting definition is missing an output");
4903
4904                 int width = 0;
4905                 std::vector<std::string> recipe;
4906                 lua_getfield(L, table, "recipe");
4907                 if(lua_isnil(L, -1))
4908                         throw LuaError(L, "Crafting definition is missing a recipe"
4909                                         " (output=\"" + output + "\")");
4910                 if(!read_craft_recipe_shaped(L, -1, width, recipe))
4911                         throw LuaError(L, "Invalid crafting recipe"
4912                                         " (output=\"" + output + "\")");
4913
4914                 CraftReplacements replacements;
4915                 lua_getfield(L, table, "replacements");
4916                 if(!lua_isnil(L, -1))
4917                 {
4918                         if(!read_craft_replacements(L, -1, replacements))
4919                                 throw LuaError(L, "Invalid replacements"
4920                                                 " (output=\"" + output + "\")");
4921                 }
4922
4923                 CraftDefinition *def = new CraftDefinitionShaped(
4924                                 output, width, recipe, replacements);
4925                 craftdef->registerCraft(def);
4926         }
4927         /*
4928                 CraftDefinitionShapeless
4929         */
4930         else if(type == "shapeless"){
4931                 std::string output = getstringfield_default(L, table, "output", "");
4932                 if(output == "")
4933                         throw LuaError(L, "Crafting definition (shapeless)"
4934                                         " is missing an output");
4935
4936                 std::vector<std::string> recipe;
4937                 lua_getfield(L, table, "recipe");
4938                 if(lua_isnil(L, -1))
4939                         throw LuaError(L, "Crafting definition (shapeless)"
4940                                         " is missing a recipe"
4941                                         " (output=\"" + output + "\")");
4942                 if(!read_craft_recipe_shapeless(L, -1, recipe))
4943                         throw LuaError(L, "Invalid crafting recipe"
4944                                         " (output=\"" + output + "\")");
4945
4946                 CraftReplacements replacements;
4947                 lua_getfield(L, table, "replacements");
4948                 if(!lua_isnil(L, -1))
4949                 {
4950                         if(!read_craft_replacements(L, -1, replacements))
4951                                 throw LuaError(L, "Invalid replacements"
4952                                                 " (output=\"" + output + "\")");
4953                 }
4954
4955                 CraftDefinition *def = new CraftDefinitionShapeless(
4956                                 output, recipe, replacements);
4957                 craftdef->registerCraft(def);
4958         }
4959         /*
4960                 CraftDefinitionToolRepair
4961         */
4962         else if(type == "toolrepair"){
4963                 float additional_wear = getfloatfield_default(L, table,
4964                                 "additional_wear", 0.0);
4965
4966                 CraftDefinition *def = new CraftDefinitionToolRepair(
4967                                 additional_wear);
4968                 craftdef->registerCraft(def);
4969         }
4970         /*
4971                 CraftDefinitionCooking
4972         */
4973         else if(type == "cooking"){
4974                 std::string output = getstringfield_default(L, table, "output", "");
4975                 if(output == "")
4976                         throw LuaError(L, "Crafting definition (cooking)"
4977                                         " is missing an output");
4978
4979                 std::string recipe = getstringfield_default(L, table, "recipe", "");
4980                 if(recipe == "")
4981                         throw LuaError(L, "Crafting definition (cooking)"
4982                                         " is missing a recipe"
4983                                         " (output=\"" + output + "\")");
4984
4985                 float cooktime = getfloatfield_default(L, table, "cooktime", 3.0);
4986
4987                 CraftReplacements replacements;
4988                 lua_getfield(L, table, "replacements");
4989                 if(!lua_isnil(L, -1))
4990                 {
4991                         if(!read_craft_replacements(L, -1, replacements))
4992                                 throw LuaError(L, "Invalid replacements"
4993                                                 " (cooking output=\"" + output + "\")");
4994                 }
4995
4996                 CraftDefinition *def = new CraftDefinitionCooking(
4997                                 output, recipe, cooktime, replacements);
4998                 craftdef->registerCraft(def);
4999         }
5000         /*
5001                 CraftDefinitionFuel
5002         */
5003         else if(type == "fuel"){
5004                 std::string recipe = getstringfield_default(L, table, "recipe", "");
5005                 if(recipe == "")
5006                         throw LuaError(L, "Crafting definition (fuel)"
5007                                         " is missing a recipe");
5008
5009                 float burntime = getfloatfield_default(L, table, "burntime", 1.0);
5010
5011                 CraftReplacements replacements;
5012                 lua_getfield(L, table, "replacements");
5013                 if(!lua_isnil(L, -1))
5014                 {
5015                         if(!read_craft_replacements(L, -1, replacements))
5016                                 throw LuaError(L, "Invalid replacements"
5017                                                 " (fuel recipe=\"" + recipe + "\")");
5018                 }
5019
5020                 CraftDefinition *def = new CraftDefinitionFuel(
5021                                 recipe, burntime, replacements);
5022                 craftdef->registerCraft(def);
5023         }
5024         else
5025         {
5026                 throw LuaError(L, "Unknown crafting definition type: \"" + type + "\"");
5027         }
5028
5029         lua_pop(L, 1);
5030         return 0; /* number of results */
5031 }
5032
5033 // setting_set(name, value)
5034 static int l_setting_set(lua_State *L)
5035 {
5036         const char *name = luaL_checkstring(L, 1);
5037         const char *value = luaL_checkstring(L, 2);
5038         g_settings->set(name, value);
5039         return 0;
5040 }
5041
5042 // setting_get(name)
5043 static int l_setting_get(lua_State *L)
5044 {
5045         const char *name = luaL_checkstring(L, 1);
5046         try{
5047                 std::string value = g_settings->get(name);
5048                 lua_pushstring(L, value.c_str());
5049         } catch(SettingNotFoundException &e){
5050                 lua_pushnil(L);
5051         }
5052         return 1;
5053 }
5054
5055 // setting_getbool(name)
5056 static int l_setting_getbool(lua_State *L)
5057 {
5058         const char *name = luaL_checkstring(L, 1);
5059         try{
5060                 bool value = g_settings->getBool(name);
5061                 lua_pushboolean(L, value);
5062         } catch(SettingNotFoundException &e){
5063                 lua_pushnil(L);
5064         }
5065         return 1;
5066 }
5067
5068 // setting_save()
5069 static int l_setting_save(lua_State *L)
5070 {
5071         get_server(L)->saveConfig();
5072         return 0;
5073 }
5074
5075 // chat_send_all(text)
5076 static int l_chat_send_all(lua_State *L)
5077 {
5078         const char *text = luaL_checkstring(L, 1);
5079         // Get server from registry
5080         Server *server = get_server(L);
5081         // Send
5082         server->notifyPlayers(narrow_to_wide(text));
5083         return 0;
5084 }
5085
5086 // chat_send_player(name, text)
5087 static int l_chat_send_player(lua_State *L)
5088 {
5089         const char *name = luaL_checkstring(L, 1);
5090         const char *text = luaL_checkstring(L, 2);
5091         // Get server from registry
5092         Server *server = get_server(L);
5093         // Send
5094         server->notifyPlayer(name, narrow_to_wide(text));
5095         return 0;
5096 }
5097
5098 // get_player_privs(name, text)
5099 static int l_get_player_privs(lua_State *L)
5100 {
5101         const char *name = luaL_checkstring(L, 1);
5102         // Get server from registry
5103         Server *server = get_server(L);
5104         // Do it
5105         lua_newtable(L);
5106         int table = lua_gettop(L);
5107         std::set<std::string> privs_s = server->getPlayerEffectivePrivs(name);
5108         for(std::set<std::string>::const_iterator
5109                         i = privs_s.begin(); i != privs_s.end(); i++){
5110                 lua_pushboolean(L, true);
5111                 lua_setfield(L, table, i->c_str());
5112         }
5113         lua_pushvalue(L, table);
5114         return 1;
5115 }
5116
5117 // get_ban_list()
5118 static int l_get_ban_list(lua_State *L)
5119 {
5120         lua_pushstring(L, get_server(L)->getBanDescription("").c_str());
5121         return 1;
5122 }
5123
5124 // get_ban_description()
5125 static int l_get_ban_description(lua_State *L)
5126 {
5127         const char * ip_or_name = luaL_checkstring(L, 1);
5128         lua_pushstring(L, get_server(L)->getBanDescription(std::string(ip_or_name)).c_str());
5129         return 1;
5130 }
5131
5132 // ban_player()
5133 static int l_ban_player(lua_State *L)
5134 {
5135         const char * name = luaL_checkstring(L, 1);
5136         Player *player = get_env(L)->getPlayer(name);
5137         if(player == NULL)
5138         {
5139                 lua_pushboolean(L, false); // no such player
5140                 return 1;
5141         }
5142         try
5143         {
5144                 Address addr = get_server(L)->getPeerAddress(get_env(L)->getPlayer(name)->peer_id);
5145                 std::string ip_str = addr.serializeString();
5146                 get_server(L)->setIpBanned(ip_str, name);
5147         }
5148         catch(con::PeerNotFoundException) // unlikely
5149         {
5150                 dstream << __FUNCTION_NAME << ": peer was not found" << std::endl;
5151                 lua_pushboolean(L, false); // error
5152                 return 1;
5153         }
5154         lua_pushboolean(L, true);
5155         return 1;
5156 }
5157
5158 // unban_player_or_ip()
5159 static int l_unban_player_of_ip(lua_State *L)
5160 {
5161         const char * ip_or_name = luaL_checkstring(L, 1);
5162         get_server(L)->unsetIpBanned(ip_or_name);
5163         lua_pushboolean(L, true);
5164         return 1;
5165 }
5166
5167 // get_inventory(location)
5168 static int l_get_inventory(lua_State *L)
5169 {
5170         InventoryLocation loc;
5171
5172         std::string type = checkstringfield(L, 1, "type");
5173         if(type == "player"){
5174                 std::string name = checkstringfield(L, 1, "name");
5175                 loc.setPlayer(name);
5176         } else if(type == "node"){
5177                 lua_getfield(L, 1, "pos");
5178                 v3s16 pos = check_v3s16(L, -1);
5179                 loc.setNodeMeta(pos);
5180         } else if(type == "detached"){
5181                 std::string name = checkstringfield(L, 1, "name");
5182                 loc.setDetached(name);
5183         }
5184
5185         if(get_server(L)->getInventory(loc) != NULL)
5186                 InvRef::create(L, loc);
5187         else
5188                 lua_pushnil(L);
5189         return 1;
5190 }
5191
5192 // create_detached_inventory_raw(name)
5193 static int l_create_detached_inventory_raw(lua_State *L)
5194 {
5195         const char *name = luaL_checkstring(L, 1);
5196         if(get_server(L)->createDetachedInventory(name) != NULL){
5197                 InventoryLocation loc;
5198                 loc.setDetached(name);
5199                 InvRef::create(L, loc);
5200         }else{
5201                 lua_pushnil(L);
5202         }
5203         return 1;
5204 }
5205
5206 // show_formspec(playername,formname,formspec)
5207 static int l_show_formspec(lua_State *L)
5208 {
5209         const char *playername = luaL_checkstring(L, 1);
5210         const char *formname = luaL_checkstring(L, 2);
5211         const char *formspec = luaL_checkstring(L, 3);
5212
5213         if(get_server(L)->showFormspec(playername,formspec,formname))
5214         {
5215                 lua_pushboolean(L, true);
5216         }else{
5217                 lua_pushboolean(L, false);
5218         }
5219         return 1;
5220 }
5221
5222 // get_dig_params(groups, tool_capabilities[, time_from_last_punch])
5223 static int l_get_dig_params(lua_State *L)
5224 {
5225         std::map<std::string, int> groups;
5226         read_groups(L, 1, groups);
5227         ToolCapabilities tp = read_tool_capabilities(L, 2);
5228         if(lua_isnoneornil(L, 3))
5229                 push_dig_params(L, getDigParams(groups, &tp));
5230         else
5231                 push_dig_params(L, getDigParams(groups, &tp,
5232                                         luaL_checknumber(L, 3)));
5233         return 1;
5234 }
5235
5236 // get_hit_params(groups, tool_capabilities[, time_from_last_punch])
5237 static int l_get_hit_params(lua_State *L)
5238 {
5239         std::map<std::string, int> groups;
5240         read_groups(L, 1, groups);
5241         ToolCapabilities tp = read_tool_capabilities(L, 2);
5242         if(lua_isnoneornil(L, 3))
5243                 push_hit_params(L, getHitParams(groups, &tp));
5244         else
5245                 push_hit_params(L, getHitParams(groups, &tp,
5246                                         luaL_checknumber(L, 3)));
5247         return 1;
5248 }
5249
5250 // get_current_modname()
5251 static int l_get_current_modname(lua_State *L)
5252 {
5253         lua_getfield(L, LUA_REGISTRYINDEX, "minetest_current_modname");
5254         return 1;
5255 }
5256
5257 // get_modpath(modname)
5258 static int l_get_modpath(lua_State *L)
5259 {
5260         std::string modname = luaL_checkstring(L, 1);
5261         // Do it
5262         if(modname == "__builtin"){
5263                 std::string path = get_server(L)->getBuiltinLuaPath();
5264                 lua_pushstring(L, path.c_str());
5265                 return 1;
5266         }
5267         const ModSpec *mod = get_server(L)->getModSpec(modname);
5268         if(!mod){
5269                 lua_pushnil(L);
5270                 return 1;
5271         }
5272         lua_pushstring(L, mod->path.c_str());
5273         return 1;
5274 }
5275
5276 // get_modnames()
5277 // the returned list is sorted alphabetically for you
5278 static int l_get_modnames(lua_State *L)
5279 {
5280         // Get a list of mods
5281         core::list<std::string> mods_unsorted, mods_sorted;
5282         get_server(L)->getModNames(mods_unsorted);
5283
5284         // Take unsorted items from mods_unsorted and sort them into
5285         // mods_sorted; not great performance but the number of mods on a
5286         // server will likely be small.
5287         for(core::list<std::string>::Iterator i = mods_unsorted.begin();
5288             i != mods_unsorted.end(); i++)
5289         {
5290                 bool added = false;
5291                 for(core::list<std::string>::Iterator x = mods_sorted.begin();
5292                     x != mods_unsorted.end(); x++)
5293                 {
5294                         // I doubt anybody using Minetest will be using
5295                         // anything not ASCII based :)
5296                         if((*i).compare(*x) <= 0)
5297                         {
5298                                 mods_sorted.insert_before(x, *i);
5299                                 added = true;
5300                                 break;
5301                         }
5302                 }
5303                 if(!added)
5304                         mods_sorted.push_back(*i);
5305         }
5306
5307         // Get the table insertion function from Lua.
5308         lua_getglobal(L, "table");
5309         lua_getfield(L, -1, "insert");
5310         int insertion_func = lua_gettop(L);
5311
5312         // Package them up for Lua
5313         lua_newtable(L);
5314         int new_table = lua_gettop(L);
5315         core::list<std::string>::Iterator i = mods_sorted.begin();
5316         while(i != mods_sorted.end())
5317         {
5318                 lua_pushvalue(L, insertion_func);
5319                 lua_pushvalue(L, new_table);
5320                 lua_pushstring(L, (*i).c_str());
5321                 if(lua_pcall(L, 2, 0, 0) != 0)
5322                 {
5323                         script_error(L, "error: %s", lua_tostring(L, -1));
5324                 }
5325                 i++;
5326         }
5327         return 1;
5328 }
5329
5330 // get_worldpath()
5331 static int l_get_worldpath(lua_State *L)
5332 {
5333         std::string worldpath = get_server(L)->getWorldPath();
5334         lua_pushstring(L, worldpath.c_str());
5335         return 1;
5336 }
5337
5338 // sound_play(spec, parameters)
5339 static int l_sound_play(lua_State *L)
5340 {
5341         SimpleSoundSpec spec;
5342         read_soundspec(L, 1, spec);
5343         ServerSoundParams params;
5344         read_server_sound_params(L, 2, params);
5345         s32 handle = get_server(L)->playSound(spec, params);
5346         lua_pushinteger(L, handle);
5347         return 1;
5348 }
5349
5350 // sound_stop(handle)
5351 static int l_sound_stop(lua_State *L)
5352 {
5353         int handle = luaL_checkinteger(L, 1);
5354         get_server(L)->stopSound(handle);
5355         return 0;
5356 }
5357
5358 // is_singleplayer()
5359 static int l_is_singleplayer(lua_State *L)
5360 {
5361         lua_pushboolean(L, get_server(L)->isSingleplayer());
5362         return 1;
5363 }
5364
5365 // get_password_hash(name, raw_password)
5366 static int l_get_password_hash(lua_State *L)
5367 {
5368         std::string name = luaL_checkstring(L, 1);
5369         std::string raw_password = luaL_checkstring(L, 2);
5370         std::string hash = translatePassword(name,
5371                         narrow_to_wide(raw_password));
5372         lua_pushstring(L, hash.c_str());
5373         return 1;
5374 }
5375
5376 // notify_authentication_modified(name)
5377 static int l_notify_authentication_modified(lua_State *L)
5378 {
5379         std::string name = "";
5380         if(lua_isstring(L, 1))
5381                 name = lua_tostring(L, 1);
5382         get_server(L)->reportPrivsModified(name);
5383         return 0;
5384 }
5385
5386 // get_craft_result(input)
5387 static int l_get_craft_result(lua_State *L)
5388 {
5389         int input_i = 1;
5390         std::string method_s = getstringfield_default(L, input_i, "method", "normal");
5391         enum CraftMethod method = (CraftMethod)getenumfield(L, input_i, "method",
5392                                 es_CraftMethod, CRAFT_METHOD_NORMAL);
5393         int width = 1;
5394         lua_getfield(L, input_i, "width");
5395         if(lua_isnumber(L, -1))
5396                 width = luaL_checkinteger(L, -1);
5397         lua_pop(L, 1);
5398         lua_getfield(L, input_i, "items");
5399         std::vector<ItemStack> items = read_items(L, -1);
5400         lua_pop(L, 1); // items
5401
5402         IGameDef *gdef = get_server(L);
5403         ICraftDefManager *cdef = gdef->cdef();
5404         CraftInput input(method, width, items);
5405         CraftOutput output;
5406         bool got = cdef->getCraftResult(input, output, true, gdef);
5407         lua_newtable(L); // output table
5408         if(got){
5409                 ItemStack item;
5410                 item.deSerialize(output.item, gdef->idef());
5411                 LuaItemStack::create(L, item);
5412                 lua_setfield(L, -2, "item");
5413                 setintfield(L, -1, "time", output.time);
5414         } else {
5415                 LuaItemStack::create(L, ItemStack());
5416                 lua_setfield(L, -2, "item");
5417                 setintfield(L, -1, "time", 0);
5418         }
5419         lua_newtable(L); // decremented input table
5420         lua_pushstring(L, method_s.c_str());
5421         lua_setfield(L, -2, "method");
5422         lua_pushinteger(L, width);
5423         lua_setfield(L, -2, "width");
5424         push_items(L, input.items);
5425         lua_setfield(L, -2, "items");
5426         return 2;
5427 }
5428
5429 // get_craft_recipe(result item)
5430 static int l_get_craft_recipe(lua_State *L)
5431 {
5432         int k = 0;
5433         char tmp[20];
5434         int input_i = 1;
5435         std::string o_item = luaL_checkstring(L,input_i);
5436
5437         IGameDef *gdef = get_server(L);
5438         ICraftDefManager *cdef = gdef->cdef();
5439         CraftInput input;
5440         CraftOutput output(o_item,0);
5441         bool got = cdef->getCraftRecipe(input, output, gdef);
5442         lua_newtable(L); // output table
5443         if(got){
5444                 lua_newtable(L);
5445                 for(std::vector<ItemStack>::const_iterator
5446                         i = input.items.begin();
5447                         i != input.items.end(); i++, k++)
5448                 {
5449                         if (i->empty())
5450                         {
5451                                 continue;
5452                         }
5453                         sprintf(tmp,"%d",k);
5454                         lua_pushstring(L,tmp);
5455                         lua_pushstring(L,i->name.c_str());
5456                         lua_settable(L, -3);
5457                 }
5458                 lua_setfield(L, -2, "items");
5459                 setintfield(L, -1, "width", input.width);
5460                 switch (input.method) {
5461                 case CRAFT_METHOD_NORMAL:
5462                         lua_pushstring(L,"normal");
5463                         break;
5464                 case CRAFT_METHOD_COOKING:
5465                         lua_pushstring(L,"cooking");
5466                         break;
5467                 case CRAFT_METHOD_FUEL:
5468                         lua_pushstring(L,"fuel");
5469                         break;
5470                 default:
5471                         lua_pushstring(L,"unknown");
5472                 }
5473                 lua_setfield(L, -2, "type");
5474         } else {
5475                 lua_pushnil(L);
5476                 lua_setfield(L, -2, "items");
5477                 setintfield(L, -1, "width", 0);
5478         }
5479         return 1;
5480 }
5481
5482 // rollback_get_last_node_actor(p, range, seconds) -> actor, p, seconds
5483 static int l_rollback_get_last_node_actor(lua_State *L)
5484 {
5485         v3s16 p = read_v3s16(L, 1);
5486         int range = luaL_checknumber(L, 2);
5487         int seconds = luaL_checknumber(L, 3);
5488         Server *server = get_server(L);
5489         IRollbackManager *rollback = server->getRollbackManager();
5490         v3s16 act_p;
5491         int act_seconds = 0;
5492         std::string actor = rollback->getLastNodeActor(p, range, seconds, &act_p, &act_seconds);
5493         lua_pushstring(L, actor.c_str());
5494         push_v3s16(L, act_p);
5495         lua_pushnumber(L, act_seconds);
5496         return 3;
5497 }
5498
5499 // rollback_revert_actions_by(actor, seconds) -> bool, log messages
5500 static int l_rollback_revert_actions_by(lua_State *L)
5501 {
5502         std::string actor = luaL_checkstring(L, 1);
5503         int seconds = luaL_checknumber(L, 2);
5504         Server *server = get_server(L);
5505         IRollbackManager *rollback = server->getRollbackManager();
5506         std::list<RollbackAction> actions = rollback->getRevertActions(actor, seconds);
5507         std::list<std::string> log;
5508         bool success = server->rollbackRevertActions(actions, &log);
5509         // Push boolean result
5510         lua_pushboolean(L, success);
5511         // Get the table insert function and push the log table
5512         lua_getglobal(L, "table");
5513         lua_getfield(L, -1, "insert");
5514         int table_insert = lua_gettop(L);
5515         lua_newtable(L);
5516         int table = lua_gettop(L);
5517         for(std::list<std::string>::const_iterator i = log.begin();
5518                         i != log.end(); i++)
5519         {
5520                 lua_pushvalue(L, table_insert);
5521                 lua_pushvalue(L, table);
5522                 lua_pushstring(L, i->c_str());
5523                 if(lua_pcall(L, 2, 0, 0))
5524                         script_error(L, "error: %s", lua_tostring(L, -1));
5525         }
5526         lua_remove(L, -2); // Remove table
5527         lua_remove(L, -2); // Remove insert
5528         return 2;
5529 }
5530
5531 static const struct luaL_Reg minetest_f [] = {
5532         {"debug", l_debug},
5533         {"log", l_log},
5534         {"request_shutdown", l_request_shutdown},
5535         {"get_server_status", l_get_server_status},
5536         {"register_item_raw", l_register_item_raw},
5537         {"register_alias_raw", l_register_alias_raw},
5538         {"register_craft", l_register_craft},
5539         {"register_biome", l_register_biome},
5540         {"register_biome_groups", l_register_biome_groups},
5541         {"setting_set", l_setting_set},
5542         {"setting_get", l_setting_get},
5543         {"setting_getbool", l_setting_getbool},
5544         {"setting_save",l_setting_save},
5545         {"chat_send_all", l_chat_send_all},
5546         {"chat_send_player", l_chat_send_player},
5547         {"get_player_privs", l_get_player_privs},
5548         {"get_ban_list", l_get_ban_list},
5549         {"get_ban_description", l_get_ban_description},
5550         {"ban_player", l_ban_player},
5551         {"unban_player_or_ip", l_unban_player_of_ip},
5552         {"get_inventory", l_get_inventory},
5553         {"create_detached_inventory_raw", l_create_detached_inventory_raw},
5554         {"show_formspec", l_show_formspec},
5555         {"get_dig_params", l_get_dig_params},
5556         {"get_hit_params", l_get_hit_params},
5557         {"get_current_modname", l_get_current_modname},
5558         {"get_modpath", l_get_modpath},
5559         {"get_modnames", l_get_modnames},
5560         {"get_worldpath", l_get_worldpath},
5561         {"sound_play", l_sound_play},
5562         {"sound_stop", l_sound_stop},
5563         {"is_singleplayer", l_is_singleplayer},
5564         {"get_password_hash", l_get_password_hash},
5565         {"notify_authentication_modified", l_notify_authentication_modified},
5566         {"get_craft_result", l_get_craft_result},
5567         {"get_craft_recipe", l_get_craft_recipe},
5568         {"rollback_get_last_node_actor", l_rollback_get_last_node_actor},
5569         {"rollback_revert_actions_by", l_rollback_revert_actions_by},
5570         {NULL, NULL}
5571 };
5572
5573 /*
5574         Main export function
5575 */
5576
5577 void scriptapi_export(lua_State *L, Server *server)
5578 {
5579         realitycheck(L);
5580         assert(lua_checkstack(L, 20));
5581         verbosestream<<"scriptapi_export()"<<std::endl;
5582         StackUnroller stack_unroller(L);
5583
5584         // Store server as light userdata in registry
5585         lua_pushlightuserdata(L, server);
5586         lua_setfield(L, LUA_REGISTRYINDEX, "minetest_server");
5587
5588         // Register global functions in table minetest
5589         lua_newtable(L);
5590         luaL_register(L, NULL, minetest_f);
5591         lua_setglobal(L, "minetest");
5592
5593         // Get the main minetest table
5594         lua_getglobal(L, "minetest");
5595
5596         // Add tables to minetest
5597         lua_newtable(L);
5598         lua_setfield(L, -2, "object_refs");
5599         lua_newtable(L);
5600         lua_setfield(L, -2, "luaentities");
5601
5602         // Register wrappers
5603         LuaItemStack::Register(L);
5604         InvRef::Register(L);
5605         NodeMetaRef::Register(L);
5606         NodeTimerRef::Register(L);
5607         ObjectRef::Register(L);
5608         EnvRef::Register(L);
5609         LuaPseudoRandom::Register(L);
5610         LuaPerlinNoise::Register(L);
5611         LuaPerlinNoiseMap::Register(L);
5612 }
5613
5614 bool scriptapi_loadmod(lua_State *L, const std::string &scriptpath,
5615                 const std::string &modname)
5616 {
5617         ModNameStorer modnamestorer(L, modname);
5618
5619         if(!string_allowed(modname, "abcdefghijklmnopqrstuvwxyz"
5620                         "0123456789_")){
5621                 errorstream<<"Error loading mod \""<<modname
5622                                 <<"\": modname does not follow naming conventions: "
5623                                 <<"Only chararacters [a-z0-9_] are allowed."<<std::endl;
5624                 return false;
5625         }
5626
5627         bool success = false;
5628
5629         try{
5630                 success = script_load(L, scriptpath.c_str());
5631         }
5632         catch(LuaError &e){
5633                 errorstream<<"Error loading mod \""<<modname
5634                                 <<"\": "<<e.what()<<std::endl;
5635         }
5636
5637         return success;
5638 }
5639
5640 void scriptapi_add_environment(lua_State *L, ServerEnvironment *env)
5641 {
5642         realitycheck(L);
5643         assert(lua_checkstack(L, 20));
5644         verbosestream<<"scriptapi_add_environment"<<std::endl;
5645         StackUnroller stack_unroller(L);
5646
5647         // Create EnvRef on stack
5648         EnvRef::create(L, env);
5649         int envref = lua_gettop(L);
5650
5651         // minetest.env = envref
5652         lua_getglobal(L, "minetest");
5653         luaL_checktype(L, -1, LUA_TTABLE);
5654         lua_pushvalue(L, envref);
5655         lua_setfield(L, -2, "env");
5656
5657         // Store environment as light userdata in registry
5658         lua_pushlightuserdata(L, env);
5659         lua_setfield(L, LUA_REGISTRYINDEX, "minetest_env");
5660
5661         /*
5662                 Add ActiveBlockModifiers to environment
5663         */
5664
5665         // Get minetest.registered_abms
5666         lua_getglobal(L, "minetest");
5667         lua_getfield(L, -1, "registered_abms");
5668         luaL_checktype(L, -1, LUA_TTABLE);
5669         int registered_abms = lua_gettop(L);
5670
5671         if(lua_istable(L, registered_abms)){
5672                 int table = lua_gettop(L);
5673                 lua_pushnil(L);
5674                 while(lua_next(L, table) != 0){
5675                         // key at index -2 and value at index -1
5676                         int id = lua_tonumber(L, -2);
5677                         int current_abm = lua_gettop(L);
5678
5679                         std::set<std::string> trigger_contents;
5680                         lua_getfield(L, current_abm, "nodenames");
5681                         if(lua_istable(L, -1)){
5682                                 int table = lua_gettop(L);
5683                                 lua_pushnil(L);
5684                                 while(lua_next(L, table) != 0){
5685                                         // key at index -2 and value at index -1
5686                                         luaL_checktype(L, -1, LUA_TSTRING);
5687                                         trigger_contents.insert(lua_tostring(L, -1));
5688                                         // removes value, keeps key for next iteration
5689                                         lua_pop(L, 1);
5690                                 }
5691                         } else if(lua_isstring(L, -1)){
5692                                 trigger_contents.insert(lua_tostring(L, -1));
5693                         }
5694                         lua_pop(L, 1);
5695
5696                         std::set<std::string> required_neighbors;
5697                         lua_getfield(L, current_abm, "neighbors");
5698                         if(lua_istable(L, -1)){
5699                                 int table = lua_gettop(L);
5700                                 lua_pushnil(L);
5701                                 while(lua_next(L, table) != 0){
5702                                         // key at index -2 and value at index -1
5703                                         luaL_checktype(L, -1, LUA_TSTRING);
5704                                         required_neighbors.insert(lua_tostring(L, -1));
5705                                         // removes value, keeps key for next iteration
5706                                         lua_pop(L, 1);
5707                                 }
5708                         } else if(lua_isstring(L, -1)){
5709                                 required_neighbors.insert(lua_tostring(L, -1));
5710                         }
5711                         lua_pop(L, 1);
5712
5713                         float trigger_interval = 10.0;
5714                         getfloatfield(L, current_abm, "interval", trigger_interval);
5715
5716                         int trigger_chance = 50;
5717                         getintfield(L, current_abm, "chance", trigger_chance);
5718
5719                         LuaABM *abm = new LuaABM(L, id, trigger_contents,
5720                                         required_neighbors, trigger_interval, trigger_chance);
5721
5722                         env->addActiveBlockModifier(abm);
5723
5724                         // removes value, keeps key for next iteration
5725                         lua_pop(L, 1);
5726                 }
5727         }
5728         lua_pop(L, 1);
5729 }
5730
5731 #if 0
5732 // Dump stack top with the dump2 function
5733 static void dump2(lua_State *L, const char *name)
5734 {
5735         // Dump object (debug)
5736         lua_getglobal(L, "dump2");
5737         luaL_checktype(L, -1, LUA_TFUNCTION);
5738         lua_pushvalue(L, -2); // Get previous stack top as first parameter
5739         lua_pushstring(L, name);
5740         if(lua_pcall(L, 2, 0, 0))
5741                 script_error(L, "error: %s", lua_tostring(L, -1));
5742 }
5743 #endif
5744
5745 /*
5746         object_reference
5747 */
5748
5749 void scriptapi_add_object_reference(lua_State *L, ServerActiveObject *cobj)
5750 {
5751         realitycheck(L);
5752         assert(lua_checkstack(L, 20));
5753         //infostream<<"scriptapi_add_object_reference: id="<<cobj->getId()<<std::endl;
5754         StackUnroller stack_unroller(L);
5755
5756         // Create object on stack
5757         ObjectRef::create(L, cobj); // Puts ObjectRef (as userdata) on stack
5758         int object = lua_gettop(L);
5759
5760         // Get minetest.object_refs table
5761         lua_getglobal(L, "minetest");
5762         lua_getfield(L, -1, "object_refs");
5763         luaL_checktype(L, -1, LUA_TTABLE);
5764         int objectstable = lua_gettop(L);
5765
5766         // object_refs[id] = object
5767         lua_pushnumber(L, cobj->getId()); // Push id
5768         lua_pushvalue(L, object); // Copy object to top of stack
5769         lua_settable(L, objectstable);
5770 }
5771
5772 void scriptapi_rm_object_reference(lua_State *L, ServerActiveObject *cobj)
5773 {
5774         realitycheck(L);
5775         assert(lua_checkstack(L, 20));
5776         //infostream<<"scriptapi_rm_object_reference: id="<<cobj->getId()<<std::endl;
5777         StackUnroller stack_unroller(L);
5778
5779         // Get minetest.object_refs table
5780         lua_getglobal(L, "minetest");
5781         lua_getfield(L, -1, "object_refs");
5782         luaL_checktype(L, -1, LUA_TTABLE);
5783         int objectstable = lua_gettop(L);
5784
5785         // Get object_refs[id]
5786         lua_pushnumber(L, cobj->getId()); // Push id
5787         lua_gettable(L, objectstable);
5788         // Set object reference to NULL
5789         ObjectRef::set_null(L);
5790         lua_pop(L, 1); // pop object
5791
5792         // Set object_refs[id] = nil
5793         lua_pushnumber(L, cobj->getId()); // Push id
5794         lua_pushnil(L);
5795         lua_settable(L, objectstable);
5796 }
5797
5798 /*
5799         misc
5800 */
5801
5802 // What scriptapi_run_callbacks does with the return values of callbacks.
5803 // Regardless of the mode, if only one callback is defined,
5804 // its return value is the total return value.
5805 // Modes only affect the case where 0 or >= 2 callbacks are defined.
5806 enum RunCallbacksMode
5807 {
5808         // Returns the return value of the first callback
5809         // Returns nil if list of callbacks is empty
5810         RUN_CALLBACKS_MODE_FIRST,
5811         // Returns the return value of the last callback
5812         // Returns nil if list of callbacks is empty
5813         RUN_CALLBACKS_MODE_LAST,
5814         // If any callback returns a false value, the first such is returned
5815         // Otherwise, the first callback's return value (trueish) is returned
5816         // Returns true if list of callbacks is empty
5817         RUN_CALLBACKS_MODE_AND,
5818         // Like above, but stops calling callbacks (short circuit)
5819         // after seeing the first false value
5820         RUN_CALLBACKS_MODE_AND_SC,
5821         // If any callback returns a true value, the first such is returned
5822         // Otherwise, the first callback's return value (falseish) is returned
5823         // Returns false if list of callbacks is empty
5824         RUN_CALLBACKS_MODE_OR,
5825         // Like above, but stops calling callbacks (short circuit)
5826         // after seeing the first true value
5827         RUN_CALLBACKS_MODE_OR_SC,
5828         // Note: "a true value" and "a false value" refer to values that
5829         // are converted by lua_toboolean to true or false, respectively.
5830 };
5831
5832 // Push the list of callbacks (a lua table).
5833 // Then push nargs arguments.
5834 // Then call this function, which
5835 // - runs the callbacks
5836 // - removes the table and arguments from the lua stack
5837 // - pushes the return value, computed depending on mode
5838 static void scriptapi_run_callbacks(lua_State *L, int nargs,
5839                 RunCallbacksMode mode)
5840 {
5841         // Insert the return value into the lua stack, below the table
5842         assert(lua_gettop(L) >= nargs + 1);
5843         lua_pushnil(L);
5844         lua_insert(L, -(nargs + 1) - 1);
5845         // Stack now looks like this:
5846         // ... <return value = nil> <table> <arg#1> <arg#2> ... <arg#n>
5847
5848         int rv = lua_gettop(L) - nargs - 1;
5849         int table = rv + 1;
5850         int arg = table + 1;
5851
5852         luaL_checktype(L, table, LUA_TTABLE);
5853
5854         // Foreach
5855         lua_pushnil(L);
5856         bool first_loop = true;
5857         while(lua_next(L, table) != 0){
5858                 // key at index -2 and value at index -1
5859                 luaL_checktype(L, -1, LUA_TFUNCTION);
5860                 // Call function
5861                 for(int i = 0; i < nargs; i++)
5862                         lua_pushvalue(L, arg+i);
5863                 if(lua_pcall(L, nargs, 1, 0))
5864                         script_error(L, "error: %s", lua_tostring(L, -1));
5865
5866                 // Move return value to designated space in stack
5867                 // Or pop it
5868                 if(first_loop){
5869                         // Result of first callback is always moved
5870                         lua_replace(L, rv);
5871                         first_loop = false;
5872                 } else {
5873                         // Otherwise, what happens depends on the mode
5874                         if(mode == RUN_CALLBACKS_MODE_FIRST)
5875                                 lua_pop(L, 1);
5876                         else if(mode == RUN_CALLBACKS_MODE_LAST)
5877                                 lua_replace(L, rv);
5878                         else if(mode == RUN_CALLBACKS_MODE_AND ||
5879                                         mode == RUN_CALLBACKS_MODE_AND_SC){
5880                                 if((bool)lua_toboolean(L, rv) == true &&
5881                                                 (bool)lua_toboolean(L, -1) == false)
5882                                         lua_replace(L, rv);
5883                                 else
5884                                         lua_pop(L, 1);
5885                         }
5886                         else if(mode == RUN_CALLBACKS_MODE_OR ||
5887                                         mode == RUN_CALLBACKS_MODE_OR_SC){
5888                                 if((bool)lua_toboolean(L, rv) == false &&
5889                                                 (bool)lua_toboolean(L, -1) == true)
5890                                         lua_replace(L, rv);
5891                                 else
5892                                         lua_pop(L, 1);
5893                         }
5894                         else
5895                                 assert(0);
5896                 }
5897
5898                 // Handle short circuit modes
5899                 if(mode == RUN_CALLBACKS_MODE_AND_SC &&
5900                                 (bool)lua_toboolean(L, rv) == false)
5901                         break;
5902                 else if(mode == RUN_CALLBACKS_MODE_OR_SC &&
5903                                 (bool)lua_toboolean(L, rv) == true)
5904                         break;
5905
5906                 // value removed, keep key for next iteration
5907         }
5908
5909         // Remove stuff from stack, leaving only the return value
5910         lua_settop(L, rv);
5911
5912         // Fix return value in case no callbacks were called
5913         if(first_loop){
5914                 if(mode == RUN_CALLBACKS_MODE_AND ||
5915                                 mode == RUN_CALLBACKS_MODE_AND_SC){
5916                         lua_pop(L, 1);
5917                         lua_pushboolean(L, true);
5918                 }
5919                 else if(mode == RUN_CALLBACKS_MODE_OR ||
5920                                 mode == RUN_CALLBACKS_MODE_OR_SC){
5921                         lua_pop(L, 1);
5922                         lua_pushboolean(L, false);
5923                 }
5924         }
5925 }
5926
5927 bool scriptapi_on_chat_message(lua_State *L, const std::string &name,
5928                 const std::string &message)
5929 {
5930         realitycheck(L);
5931         assert(lua_checkstack(L, 20));
5932         StackUnroller stack_unroller(L);
5933
5934         // Get minetest.registered_on_chat_messages
5935         lua_getglobal(L, "minetest");
5936         lua_getfield(L, -1, "registered_on_chat_messages");
5937         // Call callbacks
5938         lua_pushstring(L, name.c_str());
5939         lua_pushstring(L, message.c_str());
5940         scriptapi_run_callbacks(L, 2, RUN_CALLBACKS_MODE_OR_SC);
5941         bool ate = lua_toboolean(L, -1);
5942         return ate;
5943 }
5944
5945 void scriptapi_on_shutdown(lua_State *L)
5946 {
5947         realitycheck(L);
5948         assert(lua_checkstack(L, 20));
5949         StackUnroller stack_unroller(L);
5950
5951         // Get registered shutdown hooks
5952         lua_getglobal(L, "minetest");
5953         lua_getfield(L, -1, "registered_on_shutdown");
5954         // Call callbacks
5955         scriptapi_run_callbacks(L, 0, RUN_CALLBACKS_MODE_FIRST);
5956 }
5957
5958 void scriptapi_on_newplayer(lua_State *L, ServerActiveObject *player)
5959 {
5960         realitycheck(L);
5961         assert(lua_checkstack(L, 20));
5962         StackUnroller stack_unroller(L);
5963
5964         // Get minetest.registered_on_newplayers
5965         lua_getglobal(L, "minetest");
5966         lua_getfield(L, -1, "registered_on_newplayers");
5967         // Call callbacks
5968         objectref_get_or_create(L, player);
5969         scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
5970 }
5971
5972 void scriptapi_on_dieplayer(lua_State *L, ServerActiveObject *player)
5973 {
5974         realitycheck(L);
5975         assert(lua_checkstack(L, 20));
5976         StackUnroller stack_unroller(L);
5977
5978         // Get minetest.registered_on_dieplayers
5979         lua_getglobal(L, "minetest");
5980         lua_getfield(L, -1, "registered_on_dieplayers");
5981         // Call callbacks
5982         objectref_get_or_create(L, player);
5983         scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
5984 }
5985
5986 bool scriptapi_on_respawnplayer(lua_State *L, ServerActiveObject *player)
5987 {
5988         realitycheck(L);
5989         assert(lua_checkstack(L, 20));
5990         StackUnroller stack_unroller(L);
5991
5992         // Get minetest.registered_on_respawnplayers
5993         lua_getglobal(L, "minetest");
5994         lua_getfield(L, -1, "registered_on_respawnplayers");
5995         // Call callbacks
5996         objectref_get_or_create(L, player);
5997         scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_OR);
5998         bool positioning_handled_by_some = lua_toboolean(L, -1);
5999         return positioning_handled_by_some;
6000 }
6001
6002 void scriptapi_on_joinplayer(lua_State *L, ServerActiveObject *player)
6003 {
6004         realitycheck(L);
6005         assert(lua_checkstack(L, 20));
6006         StackUnroller stack_unroller(L);
6007
6008         // Get minetest.registered_on_joinplayers
6009         lua_getglobal(L, "minetest");
6010         lua_getfield(L, -1, "registered_on_joinplayers");
6011         // Call callbacks
6012         objectref_get_or_create(L, player);
6013         scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
6014 }
6015
6016 void scriptapi_on_leaveplayer(lua_State *L, ServerActiveObject *player)
6017 {
6018         realitycheck(L);
6019         assert(lua_checkstack(L, 20));
6020         StackUnroller stack_unroller(L);
6021
6022         // Get minetest.registered_on_leaveplayers
6023         lua_getglobal(L, "minetest");
6024         lua_getfield(L, -1, "registered_on_leaveplayers");
6025         // Call callbacks
6026         objectref_get_or_create(L, player);
6027         scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
6028 }
6029
6030 static void get_auth_handler(lua_State *L)
6031 {
6032         lua_getglobal(L, "minetest");
6033         lua_getfield(L, -1, "registered_auth_handler");
6034         if(lua_isnil(L, -1)){
6035                 lua_pop(L, 1);
6036                 lua_getfield(L, -1, "builtin_auth_handler");
6037         }
6038         if(lua_type(L, -1) != LUA_TTABLE)
6039                 throw LuaError(L, "Authentication handler table not valid");
6040 }
6041
6042 bool scriptapi_get_auth(lua_State *L, const std::string &playername,
6043                 std::string *dst_password, std::set<std::string> *dst_privs)
6044 {
6045         realitycheck(L);
6046         assert(lua_checkstack(L, 20));
6047         StackUnroller stack_unroller(L);
6048
6049         get_auth_handler(L);
6050         lua_getfield(L, -1, "get_auth");
6051         if(lua_type(L, -1) != LUA_TFUNCTION)
6052                 throw LuaError(L, "Authentication handler missing get_auth");
6053         lua_pushstring(L, playername.c_str());
6054         if(lua_pcall(L, 1, 1, 0))
6055                 script_error(L, "error: %s", lua_tostring(L, -1));
6056
6057         // nil = login not allowed
6058         if(lua_isnil(L, -1))
6059                 return false;
6060         luaL_checktype(L, -1, LUA_TTABLE);
6061
6062         std::string password;
6063         bool found = getstringfield(L, -1, "password", password);
6064         if(!found)
6065                 throw LuaError(L, "Authentication handler didn't return password");
6066         if(dst_password)
6067                 *dst_password = password;
6068
6069         lua_getfield(L, -1, "privileges");
6070         if(!lua_istable(L, -1))
6071                 throw LuaError(L,
6072                                 "Authentication handler didn't return privilege table");
6073         if(dst_privs)
6074                 read_privileges(L, -1, *dst_privs);
6075         lua_pop(L, 1);
6076
6077         return true;
6078 }
6079
6080 void scriptapi_create_auth(lua_State *L, const std::string &playername,
6081                 const std::string &password)
6082 {
6083         realitycheck(L);
6084         assert(lua_checkstack(L, 20));
6085         StackUnroller stack_unroller(L);
6086
6087         get_auth_handler(L);
6088         lua_getfield(L, -1, "create_auth");
6089         if(lua_type(L, -1) != LUA_TFUNCTION)
6090                 throw LuaError(L, "Authentication handler missing create_auth");
6091         lua_pushstring(L, playername.c_str());
6092         lua_pushstring(L, password.c_str());
6093         if(lua_pcall(L, 2, 0, 0))
6094                 script_error(L, "error: %s", lua_tostring(L, -1));
6095 }
6096
6097 bool scriptapi_set_password(lua_State *L, const std::string &playername,
6098                 const std::string &password)
6099 {
6100         realitycheck(L);
6101         assert(lua_checkstack(L, 20));
6102         StackUnroller stack_unroller(L);
6103
6104         get_auth_handler(L);
6105         lua_getfield(L, -1, "set_password");
6106         if(lua_type(L, -1) != LUA_TFUNCTION)
6107                 throw LuaError(L, "Authentication handler missing set_password");
6108         lua_pushstring(L, playername.c_str());
6109         lua_pushstring(L, password.c_str());
6110         if(lua_pcall(L, 2, 1, 0))
6111                 script_error(L, "error: %s", lua_tostring(L, -1));
6112         return lua_toboolean(L, -1);
6113 }
6114
6115 /*
6116         player
6117 */
6118
6119 void scriptapi_on_player_receive_fields(lua_State *L,
6120                 ServerActiveObject *player,
6121                 const std::string &formname,
6122                 const std::map<std::string, std::string> &fields)
6123 {
6124         realitycheck(L);
6125         assert(lua_checkstack(L, 20));
6126         StackUnroller stack_unroller(L);
6127
6128         // Get minetest.registered_on_chat_messages
6129         lua_getglobal(L, "minetest");
6130         lua_getfield(L, -1, "registered_on_player_receive_fields");
6131         // Call callbacks
6132         // param 1
6133         objectref_get_or_create(L, player);
6134         // param 2
6135         lua_pushstring(L, formname.c_str());
6136         // param 3
6137         lua_newtable(L);
6138         for(std::map<std::string, std::string>::const_iterator
6139                         i = fields.begin(); i != fields.end(); i++){
6140                 const std::string &name = i->first;
6141                 const std::string &value = i->second;
6142                 lua_pushstring(L, name.c_str());
6143                 lua_pushlstring(L, value.c_str(), value.size());
6144                 lua_settable(L, -3);
6145         }
6146         scriptapi_run_callbacks(L, 3, RUN_CALLBACKS_MODE_OR_SC);
6147 }
6148
6149 /*
6150         item callbacks and node callbacks
6151 */
6152
6153 // Retrieves minetest.registered_items[name][callbackname]
6154 // If that is nil or on error, return false and stack is unchanged
6155 // If that is a function, returns true and pushes the
6156 // function onto the stack
6157 // If minetest.registered_items[name] doesn't exist, minetest.nodedef_default
6158 // is tried instead so unknown items can still be manipulated to some degree
6159 static bool get_item_callback(lua_State *L,
6160                 const char *name, const char *callbackname)
6161 {
6162         lua_getglobal(L, "minetest");
6163         lua_getfield(L, -1, "registered_items");
6164         lua_remove(L, -2);
6165         luaL_checktype(L, -1, LUA_TTABLE);
6166         lua_getfield(L, -1, name);
6167         lua_remove(L, -2);
6168         // Should be a table
6169         if(lua_type(L, -1) != LUA_TTABLE)
6170         {
6171                 // Report error and clean up
6172                 errorstream<<"Item \""<<name<<"\" not defined"<<std::endl;
6173                 lua_pop(L, 1);
6174
6175                 // Try minetest.nodedef_default instead
6176                 lua_getglobal(L, "minetest");
6177                 lua_getfield(L, -1, "nodedef_default");
6178                 lua_remove(L, -2);
6179                 luaL_checktype(L, -1, LUA_TTABLE);
6180         }
6181         lua_getfield(L, -1, callbackname);
6182         lua_remove(L, -2);
6183         // Should be a function or nil
6184         if(lua_type(L, -1) == LUA_TFUNCTION)
6185         {
6186                 return true;
6187         }
6188         else if(lua_isnil(L, -1))
6189         {
6190                 lua_pop(L, 1);
6191                 return false;
6192         }
6193         else
6194         {
6195                 errorstream<<"Item \""<<name<<"\" callback \""
6196                         <<callbackname<<" is not a function"<<std::endl;
6197                 lua_pop(L, 1);
6198                 return false;
6199         }
6200 }
6201
6202 bool scriptapi_item_on_drop(lua_State *L, ItemStack &item,
6203                 ServerActiveObject *dropper, v3f pos)
6204 {
6205         realitycheck(L);
6206         assert(lua_checkstack(L, 20));
6207         StackUnroller stack_unroller(L);
6208
6209         // Push callback function on stack
6210         if(!get_item_callback(L, item.name.c_str(), "on_drop"))
6211                 return false;
6212
6213         // Call function
6214         LuaItemStack::create(L, item);
6215         objectref_get_or_create(L, dropper);
6216         pushFloatPos(L, pos);
6217         if(lua_pcall(L, 3, 1, 0))
6218                 script_error(L, "error: %s", lua_tostring(L, -1));
6219         if(!lua_isnil(L, -1))
6220                 item = read_item(L, -1);
6221         return true;
6222 }
6223
6224 bool scriptapi_item_on_place(lua_State *L, ItemStack &item,
6225                 ServerActiveObject *placer, const PointedThing &pointed)
6226 {
6227         realitycheck(L);
6228         assert(lua_checkstack(L, 20));
6229         StackUnroller stack_unroller(L);
6230
6231         // Push callback function on stack
6232         if(!get_item_callback(L, item.name.c_str(), "on_place"))
6233                 return false;
6234
6235         // Call function
6236         LuaItemStack::create(L, item);
6237         objectref_get_or_create(L, placer);
6238         push_pointed_thing(L, pointed);
6239         if(lua_pcall(L, 3, 1, 0))
6240                 script_error(L, "error: %s", lua_tostring(L, -1));
6241         if(!lua_isnil(L, -1))
6242                 item = read_item(L, -1);
6243         return true;
6244 }
6245
6246 bool scriptapi_item_on_use(lua_State *L, ItemStack &item,
6247                 ServerActiveObject *user, const PointedThing &pointed)
6248 {
6249         realitycheck(L);
6250         assert(lua_checkstack(L, 20));
6251         StackUnroller stack_unroller(L);
6252
6253         // Push callback function on stack
6254         if(!get_item_callback(L, item.name.c_str(), "on_use"))
6255                 return false;
6256
6257         // Call function
6258         LuaItemStack::create(L, item);
6259         objectref_get_or_create(L, user);
6260         push_pointed_thing(L, pointed);
6261         if(lua_pcall(L, 3, 1, 0))
6262                 script_error(L, "error: %s", lua_tostring(L, -1));
6263         if(!lua_isnil(L, -1))
6264                 item = read_item(L, -1);
6265         return true;
6266 }
6267
6268 bool scriptapi_node_on_punch(lua_State *L, v3s16 p, MapNode node,
6269                 ServerActiveObject *puncher)
6270 {
6271         realitycheck(L);
6272         assert(lua_checkstack(L, 20));
6273         StackUnroller stack_unroller(L);
6274
6275         INodeDefManager *ndef = get_server(L)->ndef();
6276
6277         // Push callback function on stack
6278         if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_punch"))
6279                 return false;
6280
6281         // Call function
6282         push_v3s16(L, p);
6283         pushnode(L, node, ndef);
6284         objectref_get_or_create(L, puncher);
6285         if(lua_pcall(L, 3, 0, 0))
6286                 script_error(L, "error: %s", lua_tostring(L, -1));
6287         return true;
6288 }
6289
6290 bool scriptapi_node_on_dig(lua_State *L, v3s16 p, MapNode node,
6291                 ServerActiveObject *digger)
6292 {
6293         realitycheck(L);
6294         assert(lua_checkstack(L, 20));
6295         StackUnroller stack_unroller(L);
6296
6297         INodeDefManager *ndef = get_server(L)->ndef();
6298
6299         // Push callback function on stack
6300         if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_dig"))
6301                 return false;
6302
6303         // Call function
6304         push_v3s16(L, p);
6305         pushnode(L, node, ndef);
6306         objectref_get_or_create(L, digger);
6307         if(lua_pcall(L, 3, 0, 0))
6308                 script_error(L, "error: %s", lua_tostring(L, -1));
6309         return true;
6310 }
6311
6312 void scriptapi_node_on_construct(lua_State *L, v3s16 p, MapNode node)
6313 {
6314         realitycheck(L);
6315         assert(lua_checkstack(L, 20));
6316         StackUnroller stack_unroller(L);
6317
6318         INodeDefManager *ndef = get_server(L)->ndef();
6319
6320         // Push callback function on stack
6321         if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_construct"))
6322                 return;
6323
6324         // Call function
6325         push_v3s16(L, p);
6326         if(lua_pcall(L, 1, 0, 0))
6327                 script_error(L, "error: %s", lua_tostring(L, -1));
6328 }
6329
6330 void scriptapi_node_on_destruct(lua_State *L, v3s16 p, MapNode node)
6331 {
6332         realitycheck(L);
6333         assert(lua_checkstack(L, 20));
6334         StackUnroller stack_unroller(L);
6335
6336         INodeDefManager *ndef = get_server(L)->ndef();
6337
6338         // Push callback function on stack
6339         if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_destruct"))
6340                 return;
6341
6342         // Call function
6343         push_v3s16(L, p);
6344         if(lua_pcall(L, 1, 0, 0))
6345                 script_error(L, "error: %s", lua_tostring(L, -1));
6346 }
6347
6348 void scriptapi_node_after_destruct(lua_State *L, v3s16 p, MapNode node)
6349 {
6350         realitycheck(L);
6351         assert(lua_checkstack(L, 20));
6352         StackUnroller stack_unroller(L);
6353
6354         INodeDefManager *ndef = get_server(L)->ndef();
6355
6356         // Push callback function on stack
6357         if(!get_item_callback(L, ndef->get(node).name.c_str(), "after_destruct"))
6358                 return;
6359
6360         // Call function
6361         push_v3s16(L, p);
6362         pushnode(L, node, ndef);
6363         if(lua_pcall(L, 2, 0, 0))
6364                 script_error(L, "error: %s", lua_tostring(L, -1));
6365 }
6366
6367 bool scriptapi_node_on_timer(lua_State *L, v3s16 p, MapNode node, f32 dtime)
6368 {
6369         realitycheck(L);
6370         assert(lua_checkstack(L, 20));
6371         StackUnroller stack_unroller(L);
6372
6373         INodeDefManager *ndef = get_server(L)->ndef();
6374
6375         // Push callback function on stack
6376         if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_timer"))
6377                 return false;
6378
6379         // Call function
6380         push_v3s16(L, p);
6381         lua_pushnumber(L,dtime);
6382         if(lua_pcall(L, 2, 1, 0))
6383                 script_error(L, "error: %s", lua_tostring(L, -1));
6384         if((bool)lua_isboolean(L,-1) && (bool)lua_toboolean(L,-1) == true)
6385                 return true;
6386
6387         return false;
6388 }
6389
6390 void scriptapi_node_on_receive_fields(lua_State *L, v3s16 p,
6391                 const std::string &formname,
6392                 const std::map<std::string, std::string> &fields,
6393                 ServerActiveObject *sender)
6394 {
6395         realitycheck(L);
6396         assert(lua_checkstack(L, 20));
6397         StackUnroller stack_unroller(L);
6398
6399         INodeDefManager *ndef = get_server(L)->ndef();
6400
6401         // If node doesn't exist, we don't know what callback to call
6402         MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6403         if(node.getContent() == CONTENT_IGNORE)
6404                 return;
6405
6406         // Push callback function on stack
6407         if(!get_item_callback(L, ndef->get(node).name.c_str(), "on_receive_fields"))
6408                 return;
6409
6410         // Call function
6411         // param 1
6412         push_v3s16(L, p);
6413         // param 2
6414         lua_pushstring(L, formname.c_str());
6415         // param 3
6416         lua_newtable(L);
6417         for(std::map<std::string, std::string>::const_iterator
6418                         i = fields.begin(); i != fields.end(); i++){
6419                 const std::string &name = i->first;
6420                 const std::string &value = i->second;
6421                 lua_pushstring(L, name.c_str());
6422                 lua_pushlstring(L, value.c_str(), value.size());
6423                 lua_settable(L, -3);
6424         }
6425         // param 4
6426         objectref_get_or_create(L, sender);
6427         if(lua_pcall(L, 4, 0, 0))
6428                 script_error(L, "error: %s", lua_tostring(L, -1));
6429 }
6430
6431 /*
6432         Node metadata inventory callbacks
6433 */
6434
6435 // Return number of accepted items to be moved
6436 int scriptapi_nodemeta_inventory_allow_move(lua_State *L, v3s16 p,
6437                 const std::string &from_list, int from_index,
6438                 const std::string &to_list, int to_index,
6439                 int count, ServerActiveObject *player)
6440 {
6441         realitycheck(L);
6442         assert(lua_checkstack(L, 20));
6443         StackUnroller stack_unroller(L);
6444
6445         INodeDefManager *ndef = get_server(L)->ndef();
6446
6447         // If node doesn't exist, we don't know what callback to call
6448         MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6449         if(node.getContent() == CONTENT_IGNORE)
6450                 return 0;
6451
6452         // Push callback function on stack
6453         if(!get_item_callback(L, ndef->get(node).name.c_str(),
6454                         "allow_metadata_inventory_move"))
6455                 return count;
6456
6457         // function(pos, from_list, from_index, to_list, to_index, count, player)
6458         // pos
6459         push_v3s16(L, p);
6460         // from_list
6461         lua_pushstring(L, from_list.c_str());
6462         // from_index
6463         lua_pushinteger(L, from_index + 1);
6464         // to_list
6465         lua_pushstring(L, to_list.c_str());
6466         // to_index
6467         lua_pushinteger(L, to_index + 1);
6468         // count
6469         lua_pushinteger(L, count);
6470         // player
6471         objectref_get_or_create(L, player);
6472         if(lua_pcall(L, 7, 1, 0))
6473                 script_error(L, "error: %s", lua_tostring(L, -1));
6474         if(!lua_isnumber(L, -1))
6475                 throw LuaError(L, "allow_metadata_inventory_move should return a number");
6476         return luaL_checkinteger(L, -1);
6477 }
6478
6479 // Return number of accepted items to be put
6480 int scriptapi_nodemeta_inventory_allow_put(lua_State *L, v3s16 p,
6481                 const std::string &listname, int index, ItemStack &stack,
6482                 ServerActiveObject *player)
6483 {
6484         realitycheck(L);
6485         assert(lua_checkstack(L, 20));
6486         StackUnroller stack_unroller(L);
6487
6488         INodeDefManager *ndef = get_server(L)->ndef();
6489
6490         // If node doesn't exist, we don't know what callback to call
6491         MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6492         if(node.getContent() == CONTENT_IGNORE)
6493                 return 0;
6494
6495         // Push callback function on stack
6496         if(!get_item_callback(L, ndef->get(node).name.c_str(),
6497                         "allow_metadata_inventory_put"))
6498                 return stack.count;
6499
6500         // Call function(pos, listname, index, stack, player)
6501         // pos
6502         push_v3s16(L, p);
6503         // listname
6504         lua_pushstring(L, listname.c_str());
6505         // index
6506         lua_pushinteger(L, index + 1);
6507         // stack
6508         LuaItemStack::create(L, stack);
6509         // player
6510         objectref_get_or_create(L, player);
6511         if(lua_pcall(L, 5, 1, 0))
6512                 script_error(L, "error: %s", lua_tostring(L, -1));
6513         if(!lua_isnumber(L, -1))
6514                 throw LuaError(L, "allow_metadata_inventory_put should return a number");
6515         return luaL_checkinteger(L, -1);
6516 }
6517
6518 // Return number of accepted items to be taken
6519 int scriptapi_nodemeta_inventory_allow_take(lua_State *L, v3s16 p,
6520                 const std::string &listname, int index, ItemStack &stack,
6521                 ServerActiveObject *player)
6522 {
6523         realitycheck(L);
6524         assert(lua_checkstack(L, 20));
6525         StackUnroller stack_unroller(L);
6526
6527         INodeDefManager *ndef = get_server(L)->ndef();
6528
6529         // If node doesn't exist, we don't know what callback to call
6530         MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6531         if(node.getContent() == CONTENT_IGNORE)
6532                 return 0;
6533
6534         // Push callback function on stack
6535         if(!get_item_callback(L, ndef->get(node).name.c_str(),
6536                         "allow_metadata_inventory_take"))
6537                 return stack.count;
6538
6539         // Call function(pos, listname, index, count, player)
6540         // pos
6541         push_v3s16(L, p);
6542         // listname
6543         lua_pushstring(L, listname.c_str());
6544         // index
6545         lua_pushinteger(L, index + 1);
6546         // stack
6547         LuaItemStack::create(L, stack);
6548         // player
6549         objectref_get_or_create(L, player);
6550         if(lua_pcall(L, 5, 1, 0))
6551                 script_error(L, "error: %s", lua_tostring(L, -1));
6552         if(!lua_isnumber(L, -1))
6553                 throw LuaError(L, "allow_metadata_inventory_take should return a number");
6554         return luaL_checkinteger(L, -1);
6555 }
6556
6557 // Report moved items
6558 void scriptapi_nodemeta_inventory_on_move(lua_State *L, v3s16 p,
6559                 const std::string &from_list, int from_index,
6560                 const std::string &to_list, int to_index,
6561                 int count, ServerActiveObject *player)
6562 {
6563         realitycheck(L);
6564         assert(lua_checkstack(L, 20));
6565         StackUnroller stack_unroller(L);
6566
6567         INodeDefManager *ndef = get_server(L)->ndef();
6568
6569         // If node doesn't exist, we don't know what callback to call
6570         MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6571         if(node.getContent() == CONTENT_IGNORE)
6572                 return;
6573
6574         // Push callback function on stack
6575         if(!get_item_callback(L, ndef->get(node).name.c_str(),
6576                         "on_metadata_inventory_move"))
6577                 return;
6578
6579         // function(pos, from_list, from_index, to_list, to_index, count, player)
6580         // pos
6581         push_v3s16(L, p);
6582         // from_list
6583         lua_pushstring(L, from_list.c_str());
6584         // from_index
6585         lua_pushinteger(L, from_index + 1);
6586         // to_list
6587         lua_pushstring(L, to_list.c_str());
6588         // to_index
6589         lua_pushinteger(L, to_index + 1);
6590         // count
6591         lua_pushinteger(L, count);
6592         // player
6593         objectref_get_or_create(L, player);
6594         if(lua_pcall(L, 7, 0, 0))
6595                 script_error(L, "error: %s", lua_tostring(L, -1));
6596 }
6597
6598 // Report put items
6599 void scriptapi_nodemeta_inventory_on_put(lua_State *L, v3s16 p,
6600                 const std::string &listname, int index, ItemStack &stack,
6601                 ServerActiveObject *player)
6602 {
6603         realitycheck(L);
6604         assert(lua_checkstack(L, 20));
6605         StackUnroller stack_unroller(L);
6606
6607         INodeDefManager *ndef = get_server(L)->ndef();
6608
6609         // If node doesn't exist, we don't know what callback to call
6610         MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6611         if(node.getContent() == CONTENT_IGNORE)
6612                 return;
6613
6614         // Push callback function on stack
6615         if(!get_item_callback(L, ndef->get(node).name.c_str(),
6616                         "on_metadata_inventory_put"))
6617                 return;
6618
6619         // Call function(pos, listname, index, stack, player)
6620         // pos
6621         push_v3s16(L, p);
6622         // listname
6623         lua_pushstring(L, listname.c_str());
6624         // index
6625         lua_pushinteger(L, index + 1);
6626         // stack
6627         LuaItemStack::create(L, stack);
6628         // player
6629         objectref_get_or_create(L, player);
6630         if(lua_pcall(L, 5, 0, 0))
6631                 script_error(L, "error: %s", lua_tostring(L, -1));
6632 }
6633
6634 // Report taken items
6635 void scriptapi_nodemeta_inventory_on_take(lua_State *L, v3s16 p,
6636                 const std::string &listname, int index, ItemStack &stack,
6637                 ServerActiveObject *player)
6638 {
6639         realitycheck(L);
6640         assert(lua_checkstack(L, 20));
6641         StackUnroller stack_unroller(L);
6642
6643         INodeDefManager *ndef = get_server(L)->ndef();
6644
6645         // If node doesn't exist, we don't know what callback to call
6646         MapNode node = get_env(L)->getMap().getNodeNoEx(p);
6647         if(node.getContent() == CONTENT_IGNORE)
6648                 return;
6649
6650         // Push callback function on stack
6651         if(!get_item_callback(L, ndef->get(node).name.c_str(),
6652                         "on_metadata_inventory_take"))
6653                 return;
6654
6655         // Call function(pos, listname, index, stack, player)
6656         // pos
6657         push_v3s16(L, p);
6658         // listname
6659         lua_pushstring(L, listname.c_str());
6660         // index
6661         lua_pushinteger(L, index + 1);
6662         // stack
6663         LuaItemStack::create(L, stack);
6664         // player
6665         objectref_get_or_create(L, player);
6666         if(lua_pcall(L, 5, 0, 0))
6667                 script_error(L, "error: %s", lua_tostring(L, -1));
6668 }
6669
6670 /*
6671         Detached inventory callbacks
6672 */
6673
6674 // Retrieves minetest.detached_inventories[name][callbackname]
6675 // If that is nil or on error, return false and stack is unchanged
6676 // If that is a function, returns true and pushes the
6677 // function onto the stack
6678 static bool get_detached_inventory_callback(lua_State *L,
6679                 const std::string &name, const char *callbackname)
6680 {
6681         lua_getglobal(L, "minetest");
6682         lua_getfield(L, -1, "detached_inventories");
6683         lua_remove(L, -2);
6684         luaL_checktype(L, -1, LUA_TTABLE);
6685         lua_getfield(L, -1, name.c_str());
6686         lua_remove(L, -2);
6687         // Should be a table
6688         if(lua_type(L, -1) != LUA_TTABLE)
6689         {
6690                 errorstream<<"Item \""<<name<<"\" not defined"<<std::endl;
6691                 lua_pop(L, 1);
6692                 return false;
6693         }
6694         lua_getfield(L, -1, callbackname);
6695         lua_remove(L, -2);
6696         // Should be a function or nil
6697         if(lua_type(L, -1) == LUA_TFUNCTION)
6698         {
6699                 return true;
6700         }
6701         else if(lua_isnil(L, -1))
6702         {
6703                 lua_pop(L, 1);
6704                 return false;
6705         }
6706         else
6707         {
6708                 errorstream<<"Detached inventory \""<<name<<"\" callback \""
6709                         <<callbackname<<"\" is not a function"<<std::endl;
6710                 lua_pop(L, 1);
6711                 return false;
6712         }
6713 }
6714
6715 // Return number of accepted items to be moved
6716 int scriptapi_detached_inventory_allow_move(lua_State *L,
6717                 const std::string &name,
6718                 const std::string &from_list, int from_index,
6719                 const std::string &to_list, int to_index,
6720                 int count, ServerActiveObject *player)
6721 {
6722         realitycheck(L);
6723         assert(lua_checkstack(L, 20));
6724         StackUnroller stack_unroller(L);
6725
6726         // Push callback function on stack
6727         if(!get_detached_inventory_callback(L, name, "allow_move"))
6728                 return count;
6729
6730         // function(inv, from_list, from_index, to_list, to_index, count, player)
6731         // inv
6732         InventoryLocation loc;
6733         loc.setDetached(name);
6734         InvRef::create(L, loc);
6735         // from_list
6736         lua_pushstring(L, from_list.c_str());
6737         // from_index
6738         lua_pushinteger(L, from_index + 1);
6739         // to_list
6740         lua_pushstring(L, to_list.c_str());
6741         // to_index
6742         lua_pushinteger(L, to_index + 1);
6743         // count
6744         lua_pushinteger(L, count);
6745         // player
6746         objectref_get_or_create(L, player);
6747         if(lua_pcall(L, 7, 1, 0))
6748                 script_error(L, "error: %s", lua_tostring(L, -1));
6749         if(!lua_isnumber(L, -1))
6750                 throw LuaError(L, "allow_move should return a number");
6751         return luaL_checkinteger(L, -1);
6752 }
6753
6754 // Return number of accepted items to be put
6755 int scriptapi_detached_inventory_allow_put(lua_State *L,
6756                 const std::string &name,
6757                 const std::string &listname, int index, ItemStack &stack,
6758                 ServerActiveObject *player)
6759 {
6760         realitycheck(L);
6761         assert(lua_checkstack(L, 20));
6762         StackUnroller stack_unroller(L);
6763
6764         // Push callback function on stack
6765         if(!get_detached_inventory_callback(L, name, "allow_put"))
6766                 return stack.count; // All will be accepted
6767
6768         // Call function(inv, listname, index, stack, player)
6769         // inv
6770         InventoryLocation loc;
6771         loc.setDetached(name);
6772         InvRef::create(L, loc);
6773         // listname
6774         lua_pushstring(L, listname.c_str());
6775         // index
6776         lua_pushinteger(L, index + 1);
6777         // stack
6778         LuaItemStack::create(L, stack);
6779         // player
6780         objectref_get_or_create(L, player);
6781         if(lua_pcall(L, 5, 1, 0))
6782                 script_error(L, "error: %s", lua_tostring(L, -1));
6783         if(!lua_isnumber(L, -1))
6784                 throw LuaError(L, "allow_put should return a number");
6785         return luaL_checkinteger(L, -1);
6786 }
6787
6788 // Return number of accepted items to be taken
6789 int scriptapi_detached_inventory_allow_take(lua_State *L,
6790                 const std::string &name,
6791                 const std::string &listname, int index, ItemStack &stack,
6792                 ServerActiveObject *player)
6793 {
6794         realitycheck(L);
6795         assert(lua_checkstack(L, 20));
6796         StackUnroller stack_unroller(L);
6797
6798         // Push callback function on stack
6799         if(!get_detached_inventory_callback(L, name, "allow_take"))
6800                 return stack.count; // All will be accepted
6801
6802         // Call function(inv, listname, index, stack, player)
6803         // inv
6804         InventoryLocation loc;
6805         loc.setDetached(name);
6806         InvRef::create(L, loc);
6807         // listname
6808         lua_pushstring(L, listname.c_str());
6809         // index
6810         lua_pushinteger(L, index + 1);
6811         // stack
6812         LuaItemStack::create(L, stack);
6813         // player
6814         objectref_get_or_create(L, player);
6815         if(lua_pcall(L, 5, 1, 0))
6816                 script_error(L, "error: %s", lua_tostring(L, -1));
6817         if(!lua_isnumber(L, -1))
6818                 throw LuaError(L, "allow_take should return a number");
6819         return luaL_checkinteger(L, -1);
6820 }
6821
6822 // Report moved items
6823 void scriptapi_detached_inventory_on_move(lua_State *L,
6824                 const std::string &name,
6825                 const std::string &from_list, int from_index,
6826                 const std::string &to_list, int to_index,
6827                 int count, ServerActiveObject *player)
6828 {
6829         realitycheck(L);
6830         assert(lua_checkstack(L, 20));
6831         StackUnroller stack_unroller(L);
6832
6833         // Push callback function on stack
6834         if(!get_detached_inventory_callback(L, name, "on_move"))
6835                 return;
6836
6837         // function(inv, from_list, from_index, to_list, to_index, count, player)
6838         // inv
6839         InventoryLocation loc;
6840         loc.setDetached(name);
6841         InvRef::create(L, loc);
6842         // from_list
6843         lua_pushstring(L, from_list.c_str());
6844         // from_index
6845         lua_pushinteger(L, from_index + 1);
6846         // to_list
6847         lua_pushstring(L, to_list.c_str());
6848         // to_index
6849         lua_pushinteger(L, to_index + 1);
6850         // count
6851         lua_pushinteger(L, count);
6852         // player
6853         objectref_get_or_create(L, player);
6854         if(lua_pcall(L, 7, 0, 0))
6855                 script_error(L, "error: %s", lua_tostring(L, -1));
6856 }
6857
6858 // Report put items
6859 void scriptapi_detached_inventory_on_put(lua_State *L,
6860                 const std::string &name,
6861                 const std::string &listname, int index, ItemStack &stack,
6862                 ServerActiveObject *player)
6863 {
6864         realitycheck(L);
6865         assert(lua_checkstack(L, 20));
6866         StackUnroller stack_unroller(L);
6867
6868         // Push callback function on stack
6869         if(!get_detached_inventory_callback(L, name, "on_put"))
6870                 return;
6871
6872         // Call function(inv, listname, index, stack, player)
6873         // inv
6874         InventoryLocation loc;
6875         loc.setDetached(name);
6876         InvRef::create(L, loc);
6877         // listname
6878         lua_pushstring(L, listname.c_str());
6879         // index
6880         lua_pushinteger(L, index + 1);
6881         // stack
6882         LuaItemStack::create(L, stack);
6883         // player
6884         objectref_get_or_create(L, player);
6885         if(lua_pcall(L, 5, 0, 0))
6886                 script_error(L, "error: %s", lua_tostring(L, -1));
6887 }
6888
6889 // Report taken items
6890 void scriptapi_detached_inventory_on_take(lua_State *L,
6891                 const std::string &name,
6892                 const std::string &listname, int index, ItemStack &stack,
6893                 ServerActiveObject *player)
6894 {
6895         realitycheck(L);
6896         assert(lua_checkstack(L, 20));
6897         StackUnroller stack_unroller(L);
6898
6899         // Push callback function on stack
6900         if(!get_detached_inventory_callback(L, name, "on_take"))
6901                 return;
6902
6903         // Call function(inv, listname, index, stack, player)
6904         // inv
6905         InventoryLocation loc;
6906         loc.setDetached(name);
6907         InvRef::create(L, loc);
6908         // listname
6909         lua_pushstring(L, listname.c_str());
6910         // index
6911         lua_pushinteger(L, index + 1);
6912         // stack
6913         LuaItemStack::create(L, stack);
6914         // player
6915         objectref_get_or_create(L, player);
6916         if(lua_pcall(L, 5, 0, 0))
6917                 script_error(L, "error: %s", lua_tostring(L, -1));
6918 }
6919
6920 /*
6921         environment
6922 */
6923
6924 void scriptapi_environment_step(lua_State *L, float dtime)
6925 {
6926         realitycheck(L);
6927         assert(lua_checkstack(L, 20));
6928         //infostream<<"scriptapi_environment_step"<<std::endl;
6929         StackUnroller stack_unroller(L);
6930
6931         // Get minetest.registered_globalsteps
6932         lua_getglobal(L, "minetest");
6933         lua_getfield(L, -1, "registered_globalsteps");
6934         // Call callbacks
6935         lua_pushnumber(L, dtime);
6936         scriptapi_run_callbacks(L, 1, RUN_CALLBACKS_MODE_FIRST);
6937 }
6938
6939 void scriptapi_environment_on_generated(lua_State *L, v3s16 minp, v3s16 maxp,
6940                 u32 blockseed)
6941 {
6942         realitycheck(L);
6943         assert(lua_checkstack(L, 20));
6944         //infostream<<"scriptapi_environment_on_generated"<<std::endl;
6945         StackUnroller stack_unroller(L);
6946
6947         // Get minetest.registered_on_generateds
6948         lua_getglobal(L, "minetest");
6949         lua_getfield(L, -1, "registered_on_generateds");
6950         // Call callbacks
6951         push_v3s16(L, minp);
6952         push_v3s16(L, maxp);
6953         lua_pushnumber(L, blockseed);
6954         scriptapi_run_callbacks(L, 3, RUN_CALLBACKS_MODE_FIRST);
6955 }
6956
6957 /*
6958         luaentity
6959 */
6960
6961 bool scriptapi_luaentity_add(lua_State *L, u16 id, const char *name)
6962 {
6963         realitycheck(L);
6964         assert(lua_checkstack(L, 20));
6965         verbosestream<<"scriptapi_luaentity_add: id="<<id<<" name=\""
6966                         <<name<<"\""<<std::endl;
6967         StackUnroller stack_unroller(L);
6968
6969         // Get minetest.registered_entities[name]
6970         lua_getglobal(L, "minetest");
6971         lua_getfield(L, -1, "registered_entities");
6972         luaL_checktype(L, -1, LUA_TTABLE);
6973         lua_pushstring(L, name);
6974         lua_gettable(L, -2);
6975         // Should be a table, which we will use as a prototype
6976         //luaL_checktype(L, -1, LUA_TTABLE);
6977         if(lua_type(L, -1) != LUA_TTABLE){
6978                 errorstream<<"LuaEntity name \""<<name<<"\" not defined"<<std::endl;
6979                 return false;
6980         }
6981         int prototype_table = lua_gettop(L);
6982         //dump2(L, "prototype_table");
6983
6984         // Create entity object
6985         lua_newtable(L);
6986         int object = lua_gettop(L);
6987
6988         // Set object metatable
6989         lua_pushvalue(L, prototype_table);
6990         lua_setmetatable(L, -2);
6991
6992         // Add object reference
6993         // This should be userdata with metatable ObjectRef
6994         objectref_get(L, id);
6995         luaL_checktype(L, -1, LUA_TUSERDATA);
6996         if(!luaL_checkudata(L, -1, "ObjectRef"))
6997                 luaL_typerror(L, -1, "ObjectRef");
6998         lua_setfield(L, -2, "object");
6999
7000         // minetest.luaentities[id] = object
7001         lua_getglobal(L, "minetest");
7002         lua_getfield(L, -1, "luaentities");
7003         luaL_checktype(L, -1, LUA_TTABLE);
7004         lua_pushnumber(L, id); // Push id
7005         lua_pushvalue(L, object); // Copy object to top of stack
7006         lua_settable(L, -3);
7007
7008         return true;
7009 }
7010
7011 void scriptapi_luaentity_activate(lua_State *L, u16 id,
7012                 const std::string &staticdata, u32 dtime_s)
7013 {
7014         realitycheck(L);
7015         assert(lua_checkstack(L, 20));
7016         verbosestream<<"scriptapi_luaentity_activate: id="<<id<<std::endl;
7017         StackUnroller stack_unroller(L);
7018
7019         // Get minetest.luaentities[id]
7020         luaentity_get(L, id);
7021         int object = lua_gettop(L);
7022
7023         // Get on_activate function
7024         lua_pushvalue(L, object);
7025         lua_getfield(L, -1, "on_activate");
7026         if(!lua_isnil(L, -1)){
7027                 luaL_checktype(L, -1, LUA_TFUNCTION);
7028                 lua_pushvalue(L, object); // self
7029                 lua_pushlstring(L, staticdata.c_str(), staticdata.size());
7030                 lua_pushinteger(L, dtime_s);
7031                 // Call with 3 arguments, 0 results
7032                 if(lua_pcall(L, 3, 0, 0))
7033                         script_error(L, "error running function on_activate: %s\n",
7034                                         lua_tostring(L, -1));
7035         }
7036 }
7037
7038 void scriptapi_luaentity_rm(lua_State *L, u16 id)
7039 {
7040         realitycheck(L);
7041         assert(lua_checkstack(L, 20));
7042         verbosestream<<"scriptapi_luaentity_rm: id="<<id<<std::endl;
7043
7044         // Get minetest.luaentities table
7045         lua_getglobal(L, "minetest");
7046         lua_getfield(L, -1, "luaentities");
7047         luaL_checktype(L, -1, LUA_TTABLE);
7048         int objectstable = lua_gettop(L);
7049
7050         // Set luaentities[id] = nil
7051         lua_pushnumber(L, id); // Push id
7052         lua_pushnil(L);
7053         lua_settable(L, objectstable);
7054
7055         lua_pop(L, 2); // pop luaentities, minetest
7056 }
7057
7058 std::string scriptapi_luaentity_get_staticdata(lua_State *L, u16 id)
7059 {
7060         realitycheck(L);
7061         assert(lua_checkstack(L, 20));
7062         //infostream<<"scriptapi_luaentity_get_staticdata: id="<<id<<std::endl;
7063         StackUnroller stack_unroller(L);
7064
7065         // Get minetest.luaentities[id]
7066         luaentity_get(L, id);
7067         int object = lua_gettop(L);
7068
7069         // Get get_staticdata function
7070         lua_pushvalue(L, object);
7071         lua_getfield(L, -1, "get_staticdata");
7072         if(lua_isnil(L, -1))
7073                 return "";
7074
7075         luaL_checktype(L, -1, LUA_TFUNCTION);
7076         lua_pushvalue(L, object); // self
7077         // Call with 1 arguments, 1 results
7078         if(lua_pcall(L, 1, 1, 0))
7079                 script_error(L, "error running function get_staticdata: %s\n",
7080                                 lua_tostring(L, -1));
7081
7082         size_t len=0;
7083         const char *s = lua_tolstring(L, -1, &len);
7084         return std::string(s, len);
7085 }
7086
7087 void scriptapi_luaentity_get_properties(lua_State *L, u16 id,
7088                 ObjectProperties *prop)
7089 {
7090         realitycheck(L);
7091         assert(lua_checkstack(L, 20));
7092         //infostream<<"scriptapi_luaentity_get_properties: id="<<id<<std::endl;
7093         StackUnroller stack_unroller(L);
7094
7095         // Get minetest.luaentities[id]
7096         luaentity_get(L, id);
7097         //int object = lua_gettop(L);
7098
7099         // Set default values that differ from ObjectProperties defaults
7100         prop->hp_max = 10;
7101
7102         /* Read stuff */
7103
7104         prop->hp_max = getintfield_default(L, -1, "hp_max", 10);
7105
7106         getboolfield(L, -1, "physical", prop->physical);
7107
7108         getfloatfield(L, -1, "weight", prop->weight);
7109
7110         lua_getfield(L, -1, "collisionbox");
7111         if(lua_istable(L, -1))
7112                 prop->collisionbox = read_aabb3f(L, -1, 1.0);
7113         lua_pop(L, 1);
7114
7115         getstringfield(L, -1, "visual", prop->visual);
7116
7117         getstringfield(L, -1, "mesh", prop->mesh);
7118
7119         // Deprecated: read object properties directly
7120         read_object_properties(L, -1, prop);
7121
7122         // Read initial_properties
7123         lua_getfield(L, -1, "initial_properties");
7124         read_object_properties(L, -1, prop);
7125         lua_pop(L, 1);
7126 }
7127
7128 void scriptapi_luaentity_step(lua_State *L, u16 id, float dtime)
7129 {
7130         realitycheck(L);
7131         assert(lua_checkstack(L, 20));
7132         //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
7133         StackUnroller stack_unroller(L);
7134
7135         // Get minetest.luaentities[id]
7136         luaentity_get(L, id);
7137         int object = lua_gettop(L);
7138         // State: object is at top of stack
7139         // Get step function
7140         lua_getfield(L, -1, "on_step");
7141         if(lua_isnil(L, -1))
7142                 return;
7143         luaL_checktype(L, -1, LUA_TFUNCTION);
7144         lua_pushvalue(L, object); // self
7145         lua_pushnumber(L, dtime); // dtime
7146         // Call with 2 arguments, 0 results
7147         if(lua_pcall(L, 2, 0, 0))
7148                 script_error(L, "error running function 'on_step': %s\n", lua_tostring(L, -1));
7149 }
7150
7151 // Calls entity:on_punch(ObjectRef puncher, time_from_last_punch,
7152 //                       tool_capabilities, direction)
7153 void scriptapi_luaentity_punch(lua_State *L, u16 id,
7154                 ServerActiveObject *puncher, float time_from_last_punch,
7155                 const ToolCapabilities *toolcap, v3f dir)
7156 {
7157         realitycheck(L);
7158         assert(lua_checkstack(L, 20));
7159         //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
7160         StackUnroller stack_unroller(L);
7161
7162         // Get minetest.luaentities[id]
7163         luaentity_get(L, id);
7164         int object = lua_gettop(L);
7165         // State: object is at top of stack
7166         // Get function
7167         lua_getfield(L, -1, "on_punch");
7168         if(lua_isnil(L, -1))
7169                 return;
7170         luaL_checktype(L, -1, LUA_TFUNCTION);
7171         lua_pushvalue(L, object); // self
7172         objectref_get_or_create(L, puncher); // Clicker reference
7173         lua_pushnumber(L, time_from_last_punch);
7174         push_tool_capabilities(L, *toolcap);
7175         push_v3f(L, dir);
7176         // Call with 5 arguments, 0 results
7177         if(lua_pcall(L, 5, 0, 0))
7178                 script_error(L, "error running function 'on_punch': %s\n", lua_tostring(L, -1));
7179 }
7180
7181 // Calls entity:on_rightclick(ObjectRef clicker)
7182 void scriptapi_luaentity_rightclick(lua_State *L, u16 id,
7183                 ServerActiveObject *clicker)
7184 {
7185         realitycheck(L);
7186         assert(lua_checkstack(L, 20));
7187         //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
7188         StackUnroller stack_unroller(L);
7189
7190         // Get minetest.luaentities[id]
7191         luaentity_get(L, id);
7192         int object = lua_gettop(L);
7193         // State: object is at top of stack
7194         // Get function
7195         lua_getfield(L, -1, "on_rightclick");
7196         if(lua_isnil(L, -1))
7197                 return;
7198         luaL_checktype(L, -1, LUA_TFUNCTION);
7199         lua_pushvalue(L, object); // self
7200         objectref_get_or_create(L, clicker); // Clicker reference
7201         // Call with 2 arguments, 0 results
7202         if(lua_pcall(L, 2, 0, 0))
7203                 script_error(L, "error running function 'on_rightclick': %s\n", lua_tostring(L, -1));
7204 }
7205