]> git.lizzy.rs Git - minetest.git/blob - src/script/common/c_content.cpp
Fix parsing JSON with large integers (#9674)
[minetest.git] / src / script / common / c_content.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 #include "common/c_content.h"
20 #include "common/c_converter.h"
21 #include "common/c_types.h"
22 #include "nodedef.h"
23 #include "object_properties.h"
24 #include "cpp_api/s_node.h"
25 #include "lua_api/l_object.h"
26 #include "lua_api/l_item.h"
27 #include "common/c_internal.h"
28 #include "server.h"
29 #include "log.h"
30 #include "tool.h"
31 #include "porting.h"
32 #include "mapgen/mg_schematic.h"
33 #include "noise.h"
34 #include "server/player_sao.h"
35 #include "util/pointedthing.h"
36 #include "debug.h" // For FATAL_ERROR
37 #include <json/json.h>
38
39 struct EnumString es_TileAnimationType[] =
40 {
41         {TAT_NONE, "none"},
42         {TAT_VERTICAL_FRAMES, "vertical_frames"},
43         {TAT_SHEET_2D, "sheet_2d"},
44         {0, NULL},
45 };
46
47 /******************************************************************************/
48 void read_item_definition(lua_State* L, int index,
49                 const ItemDefinition &default_def, ItemDefinition &def)
50 {
51         if (index < 0)
52                 index = lua_gettop(L) + 1 + index;
53
54         def.type = (ItemType)getenumfield(L, index, "type",
55                         es_ItemType, ITEM_NONE);
56         getstringfield(L, index, "name", def.name);
57         getstringfield(L, index, "description", def.description);
58         getstringfield(L, index, "inventory_image", def.inventory_image);
59         getstringfield(L, index, "inventory_overlay", def.inventory_overlay);
60         getstringfield(L, index, "wield_image", def.wield_image);
61         getstringfield(L, index, "wield_overlay", def.wield_overlay);
62         getstringfield(L, index, "palette", def.palette_image);
63
64         // Read item color.
65         lua_getfield(L, index, "color");
66         read_color(L, -1, &def.color);
67         lua_pop(L, 1);
68
69         lua_getfield(L, index, "wield_scale");
70         if(lua_istable(L, -1)){
71                 def.wield_scale = check_v3f(L, -1);
72         }
73         lua_pop(L, 1);
74
75         int stack_max = getintfield_default(L, index, "stack_max", def.stack_max);
76         def.stack_max = rangelim(stack_max, 1, U16_MAX);
77
78         lua_getfield(L, index, "on_use");
79         def.usable = lua_isfunction(L, -1);
80         lua_pop(L, 1);
81
82         getboolfield(L, index, "liquids_pointable", def.liquids_pointable);
83
84         warn_if_field_exists(L, index, "tool_digging_properties",
85                         "Obsolete; use tool_capabilities");
86
87         lua_getfield(L, index, "tool_capabilities");
88         if(lua_istable(L, -1)){
89                 def.tool_capabilities = new ToolCapabilities(
90                                 read_tool_capabilities(L, -1));
91         }
92
93         // If name is "" (hand), ensure there are ToolCapabilities
94         // because it will be looked up there whenever any other item has
95         // no ToolCapabilities
96         if (def.name.empty() && def.tool_capabilities == NULL){
97                 def.tool_capabilities = new ToolCapabilities();
98         }
99
100         lua_getfield(L, index, "groups");
101         read_groups(L, -1, def.groups);
102         lua_pop(L, 1);
103
104         lua_getfield(L, index, "sounds");
105         if(lua_istable(L, -1)){
106                 lua_getfield(L, -1, "place");
107                 read_soundspec(L, -1, def.sound_place);
108                 lua_pop(L, 1);
109                 lua_getfield(L, -1, "place_failed");
110                 read_soundspec(L, -1, def.sound_place_failed);
111                 lua_pop(L, 1);
112         }
113         lua_pop(L, 1);
114
115         def.range = getfloatfield_default(L, index, "range", def.range);
116
117         // Client shall immediately place this node when player places the item.
118         // Server will update the precise end result a moment later.
119         // "" = no prediction
120         getstringfield(L, index, "node_placement_prediction",
121                         def.node_placement_prediction);
122 }
123
124 /******************************************************************************/
125 void push_item_definition(lua_State *L, const ItemDefinition &i)
126 {
127         lua_newtable(L);
128         lua_pushstring(L, i.name.c_str());
129         lua_setfield(L, -2, "name");
130         lua_pushstring(L, i.description.c_str());
131         lua_setfield(L, -2, "description");
132 }
133
134 void push_item_definition_full(lua_State *L, const ItemDefinition &i)
135 {
136         std::string type(es_ItemType[(int)i.type].str);
137
138         lua_newtable(L);
139         lua_pushstring(L, i.name.c_str());
140         lua_setfield(L, -2, "name");
141         lua_pushstring(L, i.description.c_str());
142         lua_setfield(L, -2, "description");
143         lua_pushstring(L, type.c_str());
144         lua_setfield(L, -2, "type");
145         lua_pushstring(L, i.inventory_image.c_str());
146         lua_setfield(L, -2, "inventory_image");
147         lua_pushstring(L, i.inventory_overlay.c_str());
148         lua_setfield(L, -2, "inventory_overlay");
149         lua_pushstring(L, i.wield_image.c_str());
150         lua_setfield(L, -2, "wield_image");
151         lua_pushstring(L, i.wield_overlay.c_str());
152         lua_setfield(L, -2, "wield_overlay");
153         lua_pushstring(L, i.palette_image.c_str());
154         lua_setfield(L, -2, "palette_image");
155         push_ARGB8(L, i.color);
156         lua_setfield(L, -2, "color");
157         push_v3f(L, i.wield_scale);
158         lua_setfield(L, -2, "wield_scale");
159         lua_pushinteger(L, i.stack_max);
160         lua_setfield(L, -2, "stack_max");
161         lua_pushboolean(L, i.usable);
162         lua_setfield(L, -2, "usable");
163         lua_pushboolean(L, i.liquids_pointable);
164         lua_setfield(L, -2, "liquids_pointable");
165         if (i.type == ITEM_TOOL) {
166                 push_tool_capabilities(L, *i.tool_capabilities);
167                 lua_setfield(L, -2, "tool_capabilities");
168         }
169         push_groups(L, i.groups);
170         lua_setfield(L, -2, "groups");
171         push_soundspec(L, i.sound_place);
172         lua_setfield(L, -2, "sound_place");
173         push_soundspec(L, i.sound_place_failed);
174         lua_setfield(L, -2, "sound_place_failed");
175         lua_pushstring(L, i.node_placement_prediction.c_str());
176         lua_setfield(L, -2, "node_placement_prediction");
177 }
178
179 /******************************************************************************/
180 void read_object_properties(lua_State *L, int index,
181                 ServerActiveObject *sao, ObjectProperties *prop, IItemDefManager *idef)
182 {
183         if(index < 0)
184                 index = lua_gettop(L) + 1 + index;
185         if(!lua_istable(L, index))
186                 return;
187
188         int hp_max = 0;
189         if (getintfield(L, -1, "hp_max", hp_max)) {
190                 prop->hp_max = (u16)rangelim(hp_max, 0, U16_MAX);
191
192                 if (prop->hp_max < sao->getHP()) {
193                         PlayerHPChangeReason reason(PlayerHPChangeReason::SET_HP);
194                         sao->setHP(prop->hp_max, reason);
195                         if (sao->getType() == ACTIVEOBJECT_TYPE_PLAYER)
196                                 sao->getEnv()->getGameDef()->SendPlayerHPOrDie((PlayerSAO *)sao, reason);
197                 }
198         }
199
200         if (getintfield(L, -1, "breath_max", prop->breath_max)) {
201                 if (sao->getType() == ACTIVEOBJECT_TYPE_PLAYER) {
202                         PlayerSAO *player = (PlayerSAO *)sao;
203                         if (prop->breath_max < player->getBreath())
204                                 player->setBreath(prop->breath_max);
205                 }
206         }
207         getboolfield(L, -1, "physical", prop->physical);
208         getboolfield(L, -1, "collide_with_objects", prop->collideWithObjects);
209
210         lua_getfield(L, -1, "collisionbox");
211         bool collisionbox_defined = lua_istable(L, -1);
212         if (collisionbox_defined)
213                 prop->collisionbox = read_aabb3f(L, -1, 1.0);
214         lua_pop(L, 1);
215
216         lua_getfield(L, -1, "selectionbox");
217         if (lua_istable(L, -1))
218                 prop->selectionbox = read_aabb3f(L, -1, 1.0);
219         else if (collisionbox_defined)
220                 prop->selectionbox = prop->collisionbox;
221         lua_pop(L, 1);
222
223         getboolfield(L, -1, "pointable", prop->pointable);
224         getstringfield(L, -1, "visual", prop->visual);
225
226         getstringfield(L, -1, "mesh", prop->mesh);
227
228         lua_getfield(L, -1, "visual_size");
229         if (lua_istable(L, -1)) {
230                 // Backwards compatibility: Also accept { x = ?, y = ? }
231                 v2f scale_xy = read_v2f(L, -1);
232
233                 f32 scale_z = scale_xy.X;
234                 lua_getfield(L, -1, "z");
235                 if (lua_isnumber(L, -1))
236                         scale_z = lua_tonumber(L, -1);
237                 lua_pop(L, 1);
238
239                 prop->visual_size = v3f(scale_xy.X, scale_xy.Y, scale_z);
240         }
241         lua_pop(L, 1);
242
243         lua_getfield(L, -1, "textures");
244         if(lua_istable(L, -1)){
245                 prop->textures.clear();
246                 int table = lua_gettop(L);
247                 lua_pushnil(L);
248                 while(lua_next(L, table) != 0){
249                         // key at index -2 and value at index -1
250                         if(lua_isstring(L, -1))
251                                 prop->textures.emplace_back(lua_tostring(L, -1));
252                         else
253                                 prop->textures.emplace_back("");
254                         // removes value, keeps key for next iteration
255                         lua_pop(L, 1);
256                 }
257         }
258         lua_pop(L, 1);
259
260         lua_getfield(L, -1, "colors");
261         if (lua_istable(L, -1)) {
262                 int table = lua_gettop(L);
263                 prop->colors.clear();
264                 for (lua_pushnil(L); lua_next(L, table); lua_pop(L, 1)) {
265                         video::SColor color(255, 255, 255, 255);
266                         read_color(L, -1, &color);
267                         prop->colors.push_back(color);
268                 }
269         }
270         lua_pop(L, 1);
271
272         lua_getfield(L, -1, "spritediv");
273         if(lua_istable(L, -1))
274                 prop->spritediv = read_v2s16(L, -1);
275         lua_pop(L, 1);
276
277         lua_getfield(L, -1, "initial_sprite_basepos");
278         if(lua_istable(L, -1))
279                 prop->initial_sprite_basepos = read_v2s16(L, -1);
280         lua_pop(L, 1);
281
282         getboolfield(L, -1, "is_visible", prop->is_visible);
283         getboolfield(L, -1, "makes_footstep_sound", prop->makes_footstep_sound);
284         if (getfloatfield(L, -1, "stepheight", prop->stepheight))
285                 prop->stepheight *= BS;
286         getfloatfield(L, -1, "eye_height", prop->eye_height);
287
288         getfloatfield(L, -1, "automatic_rotate", prop->automatic_rotate);
289         lua_getfield(L, -1, "automatic_face_movement_dir");
290         if (lua_isnumber(L, -1)) {
291                 prop->automatic_face_movement_dir = true;
292                 prop->automatic_face_movement_dir_offset = luaL_checknumber(L, -1);
293         } else if (lua_isboolean(L, -1)) {
294                 prop->automatic_face_movement_dir = lua_toboolean(L, -1);
295                 prop->automatic_face_movement_dir_offset = 0.0;
296         }
297         lua_pop(L, 1);
298         getboolfield(L, -1, "backface_culling", prop->backface_culling);
299         getintfield(L, -1, "glow", prop->glow);
300
301         getstringfield(L, -1, "nametag", prop->nametag);
302         lua_getfield(L, -1, "nametag_color");
303         if (!lua_isnil(L, -1)) {
304                 video::SColor color = prop->nametag_color;
305                 if (read_color(L, -1, &color))
306                         prop->nametag_color = color;
307         }
308         lua_pop(L, 1);
309
310         lua_getfield(L, -1, "automatic_face_movement_max_rotation_per_sec");
311         if (lua_isnumber(L, -1)) {
312                 prop->automatic_face_movement_max_rotation_per_sec = luaL_checknumber(L, -1);
313         }
314         lua_pop(L, 1);
315
316         getstringfield(L, -1, "infotext", prop->infotext);
317         getboolfield(L, -1, "static_save", prop->static_save);
318
319         lua_getfield(L, -1, "wield_item");
320         if (!lua_isnil(L, -1))
321                 prop->wield_item = read_item(L, -1, idef).getItemString();
322         lua_pop(L, 1);
323
324         getfloatfield(L, -1, "zoom_fov", prop->zoom_fov);
325         getboolfield(L, -1, "use_texture_alpha", prop->use_texture_alpha);
326 }
327
328 /******************************************************************************/
329 void push_object_properties(lua_State *L, ObjectProperties *prop)
330 {
331         lua_newtable(L);
332         lua_pushnumber(L, prop->hp_max);
333         lua_setfield(L, -2, "hp_max");
334         lua_pushnumber(L, prop->breath_max);
335         lua_setfield(L, -2, "breath_max");
336         lua_pushboolean(L, prop->physical);
337         lua_setfield(L, -2, "physical");
338         lua_pushboolean(L, prop->collideWithObjects);
339         lua_setfield(L, -2, "collide_with_objects");
340         push_aabb3f(L, prop->collisionbox);
341         lua_setfield(L, -2, "collisionbox");
342         push_aabb3f(L, prop->selectionbox);
343         lua_setfield(L, -2, "selectionbox");
344         lua_pushboolean(L, prop->pointable);
345         lua_setfield(L, -2, "pointable");
346         lua_pushlstring(L, prop->visual.c_str(), prop->visual.size());
347         lua_setfield(L, -2, "visual");
348         lua_pushlstring(L, prop->mesh.c_str(), prop->mesh.size());
349         lua_setfield(L, -2, "mesh");
350         push_v3f(L, prop->visual_size);
351         lua_setfield(L, -2, "visual_size");
352
353         lua_createtable(L, prop->textures.size(), 0);
354         u16 i = 1;
355         for (const std::string &texture : prop->textures) {
356                 lua_pushlstring(L, texture.c_str(), texture.size());
357                 lua_rawseti(L, -2, i++);
358         }
359         lua_setfield(L, -2, "textures");
360
361         lua_createtable(L, prop->colors.size(), 0);
362         i = 1;
363         for (const video::SColor &color : prop->colors) {
364                 push_ARGB8(L, color);
365                 lua_rawseti(L, -2, i++);
366         }
367         lua_setfield(L, -2, "colors");
368
369         push_v2s16(L, prop->spritediv);
370         lua_setfield(L, -2, "spritediv");
371         push_v2s16(L, prop->initial_sprite_basepos);
372         lua_setfield(L, -2, "initial_sprite_basepos");
373         lua_pushboolean(L, prop->is_visible);
374         lua_setfield(L, -2, "is_visible");
375         lua_pushboolean(L, prop->makes_footstep_sound);
376         lua_setfield(L, -2, "makes_footstep_sound");
377         lua_pushnumber(L, prop->stepheight / BS);
378         lua_setfield(L, -2, "stepheight");
379         lua_pushnumber(L, prop->eye_height);
380         lua_setfield(L, -2, "eye_height");
381         lua_pushnumber(L, prop->automatic_rotate);
382         lua_setfield(L, -2, "automatic_rotate");
383         if (prop->automatic_face_movement_dir)
384                 lua_pushnumber(L, prop->automatic_face_movement_dir_offset);
385         else
386                 lua_pushboolean(L, false);
387         lua_setfield(L, -2, "automatic_face_movement_dir");
388         lua_pushboolean(L, prop->backface_culling);
389         lua_setfield(L, -2, "backface_culling");
390         lua_pushnumber(L, prop->glow);
391         lua_setfield(L, -2, "glow");
392         lua_pushlstring(L, prop->nametag.c_str(), prop->nametag.size());
393         lua_setfield(L, -2, "nametag");
394         push_ARGB8(L, prop->nametag_color);
395         lua_setfield(L, -2, "nametag_color");
396         lua_pushnumber(L, prop->automatic_face_movement_max_rotation_per_sec);
397         lua_setfield(L, -2, "automatic_face_movement_max_rotation_per_sec");
398         lua_pushlstring(L, prop->infotext.c_str(), prop->infotext.size());
399         lua_setfield(L, -2, "infotext");
400         lua_pushboolean(L, prop->static_save);
401         lua_setfield(L, -2, "static_save");
402         lua_pushlstring(L, prop->wield_item.c_str(), prop->wield_item.size());
403         lua_setfield(L, -2, "wield_item");
404         lua_pushnumber(L, prop->zoom_fov);
405         lua_setfield(L, -2, "zoom_fov");
406         lua_pushboolean(L, prop->use_texture_alpha);
407         lua_setfield(L, -2, "use_texture_alpha");
408 }
409
410 /******************************************************************************/
411 TileDef read_tiledef(lua_State *L, int index, u8 drawtype)
412 {
413         if(index < 0)
414                 index = lua_gettop(L) + 1 + index;
415
416         TileDef tiledef;
417
418         bool default_tiling = true;
419         bool default_culling = true;
420         switch (drawtype) {
421                 case NDT_PLANTLIKE:
422                 case NDT_PLANTLIKE_ROOTED:
423                 case NDT_FIRELIKE:
424                         default_tiling = false;
425                         // "break" is omitted here intentionaly, as PLANTLIKE
426                         // FIRELIKE drawtype both should default to having
427                         // backface_culling to false.
428                 case NDT_MESH:
429                 case NDT_LIQUID:
430                         default_culling = false;
431                         break;
432                 default:
433                         break;
434         }
435
436         // key at index -2 and value at index
437         if(lua_isstring(L, index)){
438                 // "default_lava.png"
439                 tiledef.name = lua_tostring(L, index);
440                 tiledef.tileable_vertical = default_tiling;
441                 tiledef.tileable_horizontal = default_tiling;
442                 tiledef.backface_culling = default_culling;
443         }
444         else if(lua_istable(L, index))
445         {
446                 // name="default_lava.png"
447                 tiledef.name = "";
448                 getstringfield(L, index, "name", tiledef.name);
449                 getstringfield(L, index, "image", tiledef.name); // MaterialSpec compat.
450                 tiledef.backface_culling = getboolfield_default(
451                         L, index, "backface_culling", default_culling);
452                 tiledef.tileable_horizontal = getboolfield_default(
453                         L, index, "tileable_horizontal", default_tiling);
454                 tiledef.tileable_vertical = getboolfield_default(
455                         L, index, "tileable_vertical", default_tiling);
456                 std::string align_style;
457                 if (getstringfield(L, index, "align_style", align_style)) {
458                         if (align_style == "user")
459                                 tiledef.align_style = ALIGN_STYLE_USER_DEFINED;
460                         else if (align_style == "world")
461                                 tiledef.align_style = ALIGN_STYLE_WORLD;
462                         else
463                                 tiledef.align_style = ALIGN_STYLE_NODE;
464                 }
465                 tiledef.scale = getintfield_default(L, index, "scale", 0);
466                 // color = ...
467                 lua_getfield(L, index, "color");
468                 tiledef.has_color = read_color(L, -1, &tiledef.color);
469                 lua_pop(L, 1);
470                 // animation = {}
471                 lua_getfield(L, index, "animation");
472                 tiledef.animation = read_animation_definition(L, -1);
473                 lua_pop(L, 1);
474         }
475
476         return tiledef;
477 }
478
479 /******************************************************************************/
480 ContentFeatures read_content_features(lua_State *L, int index)
481 {
482         if(index < 0)
483                 index = lua_gettop(L) + 1 + index;
484
485         ContentFeatures f;
486
487         /* Cache existence of some callbacks */
488         lua_getfield(L, index, "on_construct");
489         if(!lua_isnil(L, -1)) f.has_on_construct = true;
490         lua_pop(L, 1);
491         lua_getfield(L, index, "on_destruct");
492         if(!lua_isnil(L, -1)) f.has_on_destruct = true;
493         lua_pop(L, 1);
494         lua_getfield(L, index, "after_destruct");
495         if(!lua_isnil(L, -1)) f.has_after_destruct = true;
496         lua_pop(L, 1);
497
498         lua_getfield(L, index, "on_rightclick");
499         f.rightclickable = lua_isfunction(L, -1);
500         lua_pop(L, 1);
501
502         /* Name */
503         getstringfield(L, index, "name", f.name);
504
505         /* Groups */
506         lua_getfield(L, index, "groups");
507         read_groups(L, -1, f.groups);
508         lua_pop(L, 1);
509
510         /* Visual definition */
511
512         f.drawtype = (NodeDrawType)getenumfield(L, index, "drawtype",
513                         ScriptApiNode::es_DrawType,NDT_NORMAL);
514         getfloatfield(L, index, "visual_scale", f.visual_scale);
515
516         /* Meshnode model filename */
517         getstringfield(L, index, "mesh", f.mesh);
518
519         // tiles = {}
520         lua_getfield(L, index, "tiles");
521         // If nil, try the deprecated name "tile_images" instead
522         if(lua_isnil(L, -1)){
523                 lua_pop(L, 1);
524                 warn_if_field_exists(L, index, "tile_images",
525                                 "Deprecated; new name is \"tiles\".");
526                 lua_getfield(L, index, "tile_images");
527         }
528         if(lua_istable(L, -1)){
529                 int table = lua_gettop(L);
530                 lua_pushnil(L);
531                 int i = 0;
532                 while(lua_next(L, table) != 0){
533                         // Read tiledef from value
534                         f.tiledef[i] = read_tiledef(L, -1, f.drawtype);
535                         // removes value, keeps key for next iteration
536                         lua_pop(L, 1);
537                         i++;
538                         if(i==6){
539                                 lua_pop(L, 1);
540                                 break;
541                         }
542                 }
543                 // Copy last value to all remaining textures
544                 if(i >= 1){
545                         TileDef lasttile = f.tiledef[i-1];
546                         while(i < 6){
547                                 f.tiledef[i] = lasttile;
548                                 i++;
549                         }
550                 }
551         }
552         lua_pop(L, 1);
553
554         // overlay_tiles = {}
555         lua_getfield(L, index, "overlay_tiles");
556         if (lua_istable(L, -1)) {
557                 int table = lua_gettop(L);
558                 lua_pushnil(L);
559                 int i = 0;
560                 while (lua_next(L, table) != 0) {
561                         // Read tiledef from value
562                         f.tiledef_overlay[i] = read_tiledef(L, -1, f.drawtype);
563                         // removes value, keeps key for next iteration
564                         lua_pop(L, 1);
565                         i++;
566                         if (i == 6) {
567                                 lua_pop(L, 1);
568                                 break;
569                         }
570                 }
571                 // Copy last value to all remaining textures
572                 if (i >= 1) {
573                         TileDef lasttile = f.tiledef_overlay[i - 1];
574                         while (i < 6) {
575                                 f.tiledef_overlay[i] = lasttile;
576                                 i++;
577                         }
578                 }
579         }
580         lua_pop(L, 1);
581
582         // special_tiles = {}
583         lua_getfield(L, index, "special_tiles");
584         // If nil, try the deprecated name "special_materials" instead
585         if(lua_isnil(L, -1)){
586                 lua_pop(L, 1);
587                 warn_if_field_exists(L, index, "special_materials",
588                                 "Deprecated; new name is \"special_tiles\".");
589                 lua_getfield(L, index, "special_materials");
590         }
591         if(lua_istable(L, -1)){
592                 int table = lua_gettop(L);
593                 lua_pushnil(L);
594                 int i = 0;
595                 while(lua_next(L, table) != 0){
596                         // Read tiledef from value
597                         f.tiledef_special[i] = read_tiledef(L, -1, f.drawtype);
598                         // removes value, keeps key for next iteration
599                         lua_pop(L, 1);
600                         i++;
601                         if(i==CF_SPECIAL_COUNT){
602                                 lua_pop(L, 1);
603                                 break;
604                         }
605                 }
606         }
607         lua_pop(L, 1);
608
609         f.alpha = getintfield_default(L, index, "alpha", 255);
610
611         bool usealpha = getboolfield_default(L, index,
612                         "use_texture_alpha", false);
613         if (usealpha)
614                 f.alpha = 0;
615
616         // Read node color.
617         lua_getfield(L, index, "color");
618         read_color(L, -1, &f.color);
619         lua_pop(L, 1);
620
621         getstringfield(L, index, "palette", f.palette_name);
622
623         /* Other stuff */
624
625         lua_getfield(L, index, "post_effect_color");
626         read_color(L, -1, &f.post_effect_color);
627         lua_pop(L, 1);
628
629         f.param_type = (ContentParamType)getenumfield(L, index, "paramtype",
630                         ScriptApiNode::es_ContentParamType, CPT_NONE);
631         f.param_type_2 = (ContentParamType2)getenumfield(L, index, "paramtype2",
632                         ScriptApiNode::es_ContentParamType2, CPT2_NONE);
633
634         if (!f.palette_name.empty() &&
635                         !(f.param_type_2 == CPT2_COLOR ||
636                         f.param_type_2 == CPT2_COLORED_FACEDIR ||
637                         f.param_type_2 == CPT2_COLORED_WALLMOUNTED))
638                 warningstream << "Node " << f.name.c_str()
639                         << " has a palette, but not a suitable paramtype2." << std::endl;
640
641         // Warn about some obsolete fields
642         warn_if_field_exists(L, index, "wall_mounted",
643                         "Obsolete; use paramtype2 = 'wallmounted'");
644         warn_if_field_exists(L, index, "light_propagates",
645                         "Obsolete; determined from paramtype");
646         warn_if_field_exists(L, index, "dug_item",
647                         "Obsolete; use 'drop' field");
648         warn_if_field_exists(L, index, "extra_dug_item",
649                         "Obsolete; use 'drop' field");
650         warn_if_field_exists(L, index, "extra_dug_item_rarity",
651                         "Obsolete; use 'drop' field");
652         warn_if_field_exists(L, index, "metadata_name",
653                         "Obsolete; use on_add and metadata callbacks");
654
655         // True for all ground-like things like stone and mud, false for eg. trees
656         getboolfield(L, index, "is_ground_content", f.is_ground_content);
657         f.light_propagates = (f.param_type == CPT_LIGHT);
658         getboolfield(L, index, "sunlight_propagates", f.sunlight_propagates);
659         // This is used for collision detection.
660         // Also for general solidness queries.
661         getboolfield(L, index, "walkable", f.walkable);
662         // Player can point to these
663         getboolfield(L, index, "pointable", f.pointable);
664         // Player can dig these
665         getboolfield(L, index, "diggable", f.diggable);
666         // Player can climb these
667         getboolfield(L, index, "climbable", f.climbable);
668         // Player can build on these
669         getboolfield(L, index, "buildable_to", f.buildable_to);
670         // Liquids flow into and replace node
671         getboolfield(L, index, "floodable", f.floodable);
672         // Whether the node is non-liquid, source liquid or flowing liquid
673         f.liquid_type = (LiquidType)getenumfield(L, index, "liquidtype",
674                         ScriptApiNode::es_LiquidType, LIQUID_NONE);
675         // If the content is liquid, this is the flowing version of the liquid.
676         getstringfield(L, index, "liquid_alternative_flowing",
677                         f.liquid_alternative_flowing);
678         // If the content is liquid, this is the source version of the liquid.
679         getstringfield(L, index, "liquid_alternative_source",
680                         f.liquid_alternative_source);
681         // Viscosity for fluid flow, ranging from 1 to 7, with
682         // 1 giving almost instantaneous propagation and 7 being
683         // the slowest possible
684         f.liquid_viscosity = getintfield_default(L, index,
685                         "liquid_viscosity", f.liquid_viscosity);
686         f.liquid_range = getintfield_default(L, index,
687                         "liquid_range", f.liquid_range);
688         f.leveled = getintfield_default(L, index, "leveled", f.leveled);
689
690         getboolfield(L, index, "liquid_renewable", f.liquid_renewable);
691         f.drowning = getintfield_default(L, index,
692                         "drowning", f.drowning);
693         // Amount of light the node emits
694         f.light_source = getintfield_default(L, index,
695                         "light_source", f.light_source);
696         if (f.light_source > LIGHT_MAX) {
697                 warningstream << "Node " << f.name.c_str()
698                         << " had greater light_source than " << LIGHT_MAX
699                         << ", it was reduced." << std::endl;
700                 f.light_source = LIGHT_MAX;
701         }
702         f.damage_per_second = getintfield_default(L, index,
703                         "damage_per_second", f.damage_per_second);
704
705         lua_getfield(L, index, "node_box");
706         if(lua_istable(L, -1))
707                 f.node_box = read_nodebox(L, -1);
708         lua_pop(L, 1);
709
710         lua_getfield(L, index, "connects_to");
711         if (lua_istable(L, -1)) {
712                 int table = lua_gettop(L);
713                 lua_pushnil(L);
714                 while (lua_next(L, table) != 0) {
715                         // Value at -1
716                         f.connects_to.emplace_back(lua_tostring(L, -1));
717                         lua_pop(L, 1);
718                 }
719         }
720         lua_pop(L, 1);
721
722         lua_getfield(L, index, "connect_sides");
723         if (lua_istable(L, -1)) {
724                 int table = lua_gettop(L);
725                 lua_pushnil(L);
726                 while (lua_next(L, table) != 0) {
727                         // Value at -1
728                         std::string side(lua_tostring(L, -1));
729                         // Note faces are flipped to make checking easier
730                         if (side == "top")
731                                 f.connect_sides |= 2;
732                         else if (side == "bottom")
733                                 f.connect_sides |= 1;
734                         else if (side == "front")
735                                 f.connect_sides |= 16;
736                         else if (side == "left")
737                                 f.connect_sides |= 32;
738                         else if (side == "back")
739                                 f.connect_sides |= 4;
740                         else if (side == "right")
741                                 f.connect_sides |= 8;
742                         else
743                                 warningstream << "Unknown value for \"connect_sides\": "
744                                         << side << std::endl;
745                         lua_pop(L, 1);
746                 }
747         }
748         lua_pop(L, 1);
749
750         lua_getfield(L, index, "selection_box");
751         if(lua_istable(L, -1))
752                 f.selection_box = read_nodebox(L, -1);
753         lua_pop(L, 1);
754
755         lua_getfield(L, index, "collision_box");
756         if(lua_istable(L, -1))
757                 f.collision_box = read_nodebox(L, -1);
758         lua_pop(L, 1);
759
760         f.waving = getintfield_default(L, index,
761                         "waving", f.waving);
762
763         // Set to true if paramtype used to be 'facedir_simple'
764         getboolfield(L, index, "legacy_facedir_simple", f.legacy_facedir_simple);
765         // Set to true if wall_mounted used to be set to true
766         getboolfield(L, index, "legacy_wallmounted", f.legacy_wallmounted);
767
768         // Sound table
769         lua_getfield(L, index, "sounds");
770         if(lua_istable(L, -1)){
771                 lua_getfield(L, -1, "footstep");
772                 read_soundspec(L, -1, f.sound_footstep);
773                 lua_pop(L, 1);
774                 lua_getfield(L, -1, "dig");
775                 read_soundspec(L, -1, f.sound_dig);
776                 lua_pop(L, 1);
777                 lua_getfield(L, -1, "dug");
778                 read_soundspec(L, -1, f.sound_dug);
779                 lua_pop(L, 1);
780         }
781         lua_pop(L, 1);
782
783         // Node immediately placed by client when node is dug
784         getstringfield(L, index, "node_dig_prediction",
785                 f.node_dig_prediction);
786
787         return f;
788 }
789
790 void push_content_features(lua_State *L, const ContentFeatures &c)
791 {
792         std::string paramtype(ScriptApiNode::es_ContentParamType[(int)c.param_type].str);
793         std::string paramtype2(ScriptApiNode::es_ContentParamType2[(int)c.param_type_2].str);
794         std::string drawtype(ScriptApiNode::es_DrawType[(int)c.drawtype].str);
795         std::string liquid_type(ScriptApiNode::es_LiquidType[(int)c.liquid_type].str);
796
797         /* Missing "tiles" because I don't see a usecase (at least not yet). */
798
799         lua_newtable(L);
800         lua_pushboolean(L, c.has_on_construct);
801         lua_setfield(L, -2, "has_on_construct");
802         lua_pushboolean(L, c.has_on_destruct);
803         lua_setfield(L, -2, "has_on_destruct");
804         lua_pushboolean(L, c.has_after_destruct);
805         lua_setfield(L, -2, "has_after_destruct");
806         lua_pushstring(L, c.name.c_str());
807         lua_setfield(L, -2, "name");
808         push_groups(L, c.groups);
809         lua_setfield(L, -2, "groups");
810         lua_pushstring(L, paramtype.c_str());
811         lua_setfield(L, -2, "paramtype");
812         lua_pushstring(L, paramtype2.c_str());
813         lua_setfield(L, -2, "paramtype2");
814         lua_pushstring(L, drawtype.c_str());
815         lua_setfield(L, -2, "drawtype");
816         if (!c.mesh.empty()) {
817                 lua_pushstring(L, c.mesh.c_str());
818                 lua_setfield(L, -2, "mesh");
819         }
820 #ifndef SERVER
821         push_ARGB8(L, c.minimap_color);       // I know this is not set-able w/ register_node,
822         lua_setfield(L, -2, "minimap_color"); // but the people need to know!
823 #endif
824         lua_pushnumber(L, c.visual_scale);
825         lua_setfield(L, -2, "visual_scale");
826         lua_pushnumber(L, c.alpha);
827         lua_setfield(L, -2, "alpha");
828         if (!c.palette_name.empty()) {
829                 push_ARGB8(L, c.color);
830                 lua_setfield(L, -2, "color");
831
832                 lua_pushstring(L, c.palette_name.c_str());
833                 lua_setfield(L, -2, "palette_name");
834
835                 push_palette(L, c.palette);
836                 lua_setfield(L, -2, "palette");
837         }
838         lua_pushnumber(L, c.waving);
839         lua_setfield(L, -2, "waving");
840         lua_pushnumber(L, c.connect_sides);
841         lua_setfield(L, -2, "connect_sides");
842
843         lua_createtable(L, c.connects_to.size(), 0);
844         u16 i = 1;
845         for (const std::string &it : c.connects_to) {
846                 lua_pushlstring(L, it.c_str(), it.size());
847                 lua_rawseti(L, -2, i++);
848         }
849         lua_setfield(L, -2, "connects_to");
850
851         push_ARGB8(L, c.post_effect_color);
852         lua_setfield(L, -2, "post_effect_color");
853         lua_pushnumber(L, c.leveled);
854         lua_setfield(L, -2, "leveled");
855         lua_pushboolean(L, c.sunlight_propagates);
856         lua_setfield(L, -2, "sunlight_propagates");
857         lua_pushnumber(L, c.light_source);
858         lua_setfield(L, -2, "light_source");
859         lua_pushboolean(L, c.is_ground_content);
860         lua_setfield(L, -2, "is_ground_content");
861         lua_pushboolean(L, c.walkable);
862         lua_setfield(L, -2, "walkable");
863         lua_pushboolean(L, c.pointable);
864         lua_setfield(L, -2, "pointable");
865         lua_pushboolean(L, c.diggable);
866         lua_setfield(L, -2, "diggable");
867         lua_pushboolean(L, c.climbable);
868         lua_setfield(L, -2, "climbable");
869         lua_pushboolean(L, c.buildable_to);
870         lua_setfield(L, -2, "buildable_to");
871         lua_pushboolean(L, c.rightclickable);
872         lua_setfield(L, -2, "rightclickable");
873         lua_pushnumber(L, c.damage_per_second);
874         lua_setfield(L, -2, "damage_per_second");
875         if (c.isLiquid()) {
876                 lua_pushstring(L, liquid_type.c_str());
877                 lua_setfield(L, -2, "liquid_type");
878                 lua_pushstring(L, c.liquid_alternative_flowing.c_str());
879                 lua_setfield(L, -2, "liquid_alternative_flowing");
880                 lua_pushstring(L, c.liquid_alternative_source.c_str());
881                 lua_setfield(L, -2, "liquid_alternative_source");
882                 lua_pushnumber(L, c.liquid_viscosity);
883                 lua_setfield(L, -2, "liquid_viscosity");
884                 lua_pushboolean(L, c.liquid_renewable);
885                 lua_setfield(L, -2, "liquid_renewable");
886                 lua_pushnumber(L, c.liquid_range);
887                 lua_setfield(L, -2, "liquid_range");
888         }
889         lua_pushnumber(L, c.drowning);
890         lua_setfield(L, -2, "drowning");
891         lua_pushboolean(L, c.floodable);
892         lua_setfield(L, -2, "floodable");
893         push_nodebox(L, c.node_box);
894         lua_setfield(L, -2, "node_box");
895         push_nodebox(L, c.selection_box);
896         lua_setfield(L, -2, "selection_box");
897         push_nodebox(L, c.collision_box);
898         lua_setfield(L, -2, "collision_box");
899         lua_newtable(L);
900         push_soundspec(L, c.sound_footstep);
901         lua_setfield(L, -2, "sound_footstep");
902         push_soundspec(L, c.sound_dig);
903         lua_setfield(L, -2, "sound_dig");
904         push_soundspec(L, c.sound_dug);
905         lua_setfield(L, -2, "sound_dug");
906         lua_setfield(L, -2, "sounds");
907         lua_pushboolean(L, c.legacy_facedir_simple);
908         lua_setfield(L, -2, "legacy_facedir_simple");
909         lua_pushboolean(L, c.legacy_wallmounted);
910         lua_setfield(L, -2, "legacy_wallmounted");
911         lua_pushstring(L, c.node_dig_prediction.c_str());
912         lua_setfield(L, -2, "node_dig_prediction");
913 }
914
915 /******************************************************************************/
916 void push_nodebox(lua_State *L, const NodeBox &box)
917 {
918         lua_newtable(L);
919         switch (box.type)
920         {
921                 case NODEBOX_REGULAR:
922                         lua_pushstring(L, "regular");
923                         lua_setfield(L, -2, "type");
924                         break;
925                 case NODEBOX_LEVELED:
926                 case NODEBOX_FIXED:
927                         lua_pushstring(L, "fixed");
928                         lua_setfield(L, -2, "type");
929                         push_box(L, box.fixed);
930                         lua_setfield(L, -2, "fixed");
931                         break;
932                 case NODEBOX_WALLMOUNTED:
933                         lua_pushstring(L, "wallmounted");
934                         lua_setfield(L, -2, "type");
935                         push_aabb3f(L, box.wall_top);
936                         lua_setfield(L, -2, "wall_top");
937                         push_aabb3f(L, box.wall_bottom);
938                         lua_setfield(L, -2, "wall_bottom");
939                         push_aabb3f(L, box.wall_side);
940                         lua_setfield(L, -2, "wall_side");
941                         break;
942                 case NODEBOX_CONNECTED:
943                         lua_pushstring(L, "connected");
944                         lua_setfield(L, -2, "type");
945                         push_box(L, box.connect_top);
946                         lua_setfield(L, -2, "connect_top");
947                         push_box(L, box.connect_bottom);
948                         lua_setfield(L, -2, "connect_bottom");
949                         push_box(L, box.connect_front);
950                         lua_setfield(L, -2, "connect_front");
951                         push_box(L, box.connect_back);
952                         lua_setfield(L, -2, "connect_back");
953                         push_box(L, box.connect_left);
954                         lua_setfield(L, -2, "connect_left");
955                         push_box(L, box.connect_right);
956                         lua_setfield(L, -2, "connect_right");
957                         break;
958                 default:
959                         FATAL_ERROR("Invalid box.type");
960                         break;
961         }
962 }
963
964 void push_box(lua_State *L, const std::vector<aabb3f> &box)
965 {
966         lua_createtable(L, box.size(), 0);
967         u8 i = 1;
968         for (const aabb3f &it : box) {
969                 push_aabb3f(L, it);
970                 lua_rawseti(L, -2, i++);
971         }
972 }
973
974 /******************************************************************************/
975 void push_palette(lua_State *L, const std::vector<video::SColor> *palette)
976 {
977         lua_createtable(L, palette->size(), 0);
978         int newTable = lua_gettop(L);
979         int index = 1;
980         std::vector<video::SColor>::const_iterator iter;
981         for (iter = palette->begin(); iter != palette->end(); ++iter) {
982                 push_ARGB8(L, (*iter));
983                 lua_rawseti(L, newTable, index);
984                 index++;
985         }
986 }
987
988 /******************************************************************************/
989 void read_server_sound_params(lua_State *L, int index,
990                 ServerSoundParams &params)
991 {
992         if(index < 0)
993                 index = lua_gettop(L) + 1 + index;
994         // Clear
995         params = ServerSoundParams();
996         if(lua_istable(L, index)){
997                 getfloatfield(L, index, "gain", params.gain);
998                 getstringfield(L, index, "to_player", params.to_player);
999                 getfloatfield(L, index, "fade", params.fade);
1000                 getfloatfield(L, index, "pitch", params.pitch);
1001                 lua_getfield(L, index, "pos");
1002                 if(!lua_isnil(L, -1)){
1003                         v3f p = read_v3f(L, -1)*BS;
1004                         params.pos = p;
1005                         params.type = ServerSoundParams::SSP_POSITIONAL;
1006                 }
1007                 lua_pop(L, 1);
1008                 lua_getfield(L, index, "object");
1009                 if(!lua_isnil(L, -1)){
1010                         ObjectRef *ref = ObjectRef::checkobject(L, -1);
1011                         ServerActiveObject *sao = ObjectRef::getobject(ref);
1012                         if(sao){
1013                                 params.object = sao->getId();
1014                                 params.type = ServerSoundParams::SSP_OBJECT;
1015                         }
1016                 }
1017                 lua_pop(L, 1);
1018                 params.max_hear_distance = BS*getfloatfield_default(L, index,
1019                                 "max_hear_distance", params.max_hear_distance/BS);
1020                 getboolfield(L, index, "loop", params.loop);
1021                 getstringfield(L, index, "exclude_player", params.exclude_player);
1022         }
1023 }
1024
1025 /******************************************************************************/
1026 void read_soundspec(lua_State *L, int index, SimpleSoundSpec &spec)
1027 {
1028         if(index < 0)
1029                 index = lua_gettop(L) + 1 + index;
1030         if(lua_isnil(L, index)){
1031         } else if(lua_istable(L, index)){
1032                 getstringfield(L, index, "name", spec.name);
1033                 getfloatfield(L, index, "gain", spec.gain);
1034                 getfloatfield(L, index, "fade", spec.fade);
1035                 getfloatfield(L, index, "pitch", spec.pitch);
1036         } else if(lua_isstring(L, index)){
1037                 spec.name = lua_tostring(L, index);
1038         }
1039 }
1040
1041 void push_soundspec(lua_State *L, const SimpleSoundSpec &spec)
1042 {
1043         lua_createtable(L, 0, 3);
1044         lua_pushstring(L, spec.name.c_str());
1045         lua_setfield(L, -2, "name");
1046         lua_pushnumber(L, spec.gain);
1047         lua_setfield(L, -2, "gain");
1048         lua_pushnumber(L, spec.fade);
1049         lua_setfield(L, -2, "fade");
1050         lua_pushnumber(L, spec.pitch);
1051         lua_setfield(L, -2, "pitch");
1052 }
1053
1054 /******************************************************************************/
1055 NodeBox read_nodebox(lua_State *L, int index)
1056 {
1057         NodeBox nodebox;
1058         if(lua_istable(L, -1)){
1059                 nodebox.type = (NodeBoxType)getenumfield(L, index, "type",
1060                                 ScriptApiNode::es_NodeBoxType, NODEBOX_REGULAR);
1061
1062 #define NODEBOXREAD(n, s){ \
1063                 lua_getfield(L, index, (s)); \
1064                 if (lua_istable(L, -1)) \
1065                         (n) = read_aabb3f(L, -1, BS); \
1066                 lua_pop(L, 1); \
1067         }
1068
1069 #define NODEBOXREADVEC(n, s) \
1070                 lua_getfield(L, index, (s)); \
1071                 if (lua_istable(L, -1)) \
1072                         (n) = read_aabb3f_vector(L, -1, BS); \
1073                 lua_pop(L, 1);
1074
1075                 NODEBOXREADVEC(nodebox.fixed, "fixed");
1076                 NODEBOXREAD(nodebox.wall_top, "wall_top");
1077                 NODEBOXREAD(nodebox.wall_bottom, "wall_bottom");
1078                 NODEBOXREAD(nodebox.wall_side, "wall_side");
1079                 NODEBOXREADVEC(nodebox.connect_top, "connect_top");
1080                 NODEBOXREADVEC(nodebox.connect_bottom, "connect_bottom");
1081                 NODEBOXREADVEC(nodebox.connect_front, "connect_front");
1082                 NODEBOXREADVEC(nodebox.connect_left, "connect_left");
1083                 NODEBOXREADVEC(nodebox.connect_back, "connect_back");
1084                 NODEBOXREADVEC(nodebox.connect_right, "connect_right");
1085                 NODEBOXREADVEC(nodebox.disconnected_top, "disconnected_top");
1086                 NODEBOXREADVEC(nodebox.disconnected_bottom, "disconnected_bottom");
1087                 NODEBOXREADVEC(nodebox.disconnected_front, "disconnected_front");
1088                 NODEBOXREADVEC(nodebox.disconnected_left, "disconnected_left");
1089                 NODEBOXREADVEC(nodebox.disconnected_back, "disconnected_back");
1090                 NODEBOXREADVEC(nodebox.disconnected_right, "disconnected_right");
1091                 NODEBOXREADVEC(nodebox.disconnected, "disconnected");
1092                 NODEBOXREADVEC(nodebox.disconnected_sides, "disconnected_sides");
1093         }
1094         return nodebox;
1095 }
1096
1097 /******************************************************************************/
1098 MapNode readnode(lua_State *L, int index, const NodeDefManager *ndef)
1099 {
1100         lua_getfield(L, index, "name");
1101         if (!lua_isstring(L, -1))
1102                 throw LuaError("Node name is not set or is not a string!");
1103         std::string name = lua_tostring(L, -1);
1104         lua_pop(L, 1);
1105
1106         u8 param1 = 0;
1107         lua_getfield(L, index, "param1");
1108         if (!lua_isnil(L, -1))
1109                 param1 = lua_tonumber(L, -1);
1110         lua_pop(L, 1);
1111
1112         u8 param2 = 0;
1113         lua_getfield(L, index, "param2");
1114         if (!lua_isnil(L, -1))
1115                 param2 = lua_tonumber(L, -1);
1116         lua_pop(L, 1);
1117
1118         content_t id = CONTENT_IGNORE;
1119         if (!ndef->getId(name, id))
1120                 throw LuaError("\"" + name + "\" is not a registered node!");
1121
1122         return {id, param1, param2};
1123 }
1124
1125 /******************************************************************************/
1126 void pushnode(lua_State *L, const MapNode &n, const NodeDefManager *ndef)
1127 {
1128         lua_createtable(L, 0, 3);
1129         lua_pushstring(L, ndef->get(n).name.c_str());
1130         lua_setfield(L, -2, "name");
1131         lua_pushinteger(L, n.getParam1());
1132         lua_setfield(L, -2, "param1");
1133         lua_pushinteger(L, n.getParam2());
1134         lua_setfield(L, -2, "param2");
1135 }
1136
1137 /******************************************************************************/
1138 void warn_if_field_exists(lua_State *L, int table,
1139                 const char *name, const std::string &message)
1140 {
1141         lua_getfield(L, table, name);
1142         if (!lua_isnil(L, -1)) {
1143                 warningstream << "Field \"" << name << "\": "
1144                                 << message << std::endl;
1145                 infostream << script_get_backtrace(L) << std::endl;
1146         }
1147         lua_pop(L, 1);
1148 }
1149
1150 /******************************************************************************/
1151 int getenumfield(lua_State *L, int table,
1152                 const char *fieldname, const EnumString *spec, int default_)
1153 {
1154         int result = default_;
1155         string_to_enum(spec, result,
1156                         getstringfield_default(L, table, fieldname, ""));
1157         return result;
1158 }
1159
1160 /******************************************************************************/
1161 bool string_to_enum(const EnumString *spec, int &result,
1162                 const std::string &str)
1163 {
1164         const EnumString *esp = spec;
1165         while(esp->str){
1166                 if (!strcmp(str.c_str(), esp->str)) {
1167                         result = esp->num;
1168                         return true;
1169                 }
1170                 esp++;
1171         }
1172         return false;
1173 }
1174
1175 /******************************************************************************/
1176 ItemStack read_item(lua_State* L, int index, IItemDefManager *idef)
1177 {
1178         if(index < 0)
1179                 index = lua_gettop(L) + 1 + index;
1180
1181         if (lua_isnil(L, index)) {
1182                 return ItemStack();
1183         }
1184
1185         if (lua_isuserdata(L, index)) {
1186                 // Convert from LuaItemStack
1187                 LuaItemStack *o = LuaItemStack::checkobject(L, index);
1188                 return o->getItem();
1189         }
1190
1191         if (lua_isstring(L, index)) {
1192                 // Convert from itemstring
1193                 std::string itemstring = lua_tostring(L, index);
1194                 try
1195                 {
1196                         ItemStack item;
1197                         item.deSerialize(itemstring, idef);
1198                         return item;
1199                 }
1200                 catch(SerializationError &e)
1201                 {
1202                         warningstream<<"unable to create item from itemstring"
1203                                         <<": "<<itemstring<<std::endl;
1204                         return ItemStack();
1205                 }
1206         }
1207         else if(lua_istable(L, index))
1208         {
1209                 // Convert from table
1210                 std::string name = getstringfield_default(L, index, "name", "");
1211                 int count = getintfield_default(L, index, "count", 1);
1212                 int wear = getintfield_default(L, index, "wear", 0);
1213
1214                 ItemStack istack(name, count, wear, idef);
1215
1216                 // BACKWARDS COMPATIBLITY
1217                 std::string value = getstringfield_default(L, index, "metadata", "");
1218                 istack.metadata.setString("", value);
1219
1220                 // Get meta
1221                 lua_getfield(L, index, "meta");
1222                 int fieldstable = lua_gettop(L);
1223                 if (lua_istable(L, fieldstable)) {
1224                         lua_pushnil(L);
1225                         while (lua_next(L, fieldstable) != 0) {
1226                                 // key at index -2 and value at index -1
1227                                 std::string key = lua_tostring(L, -2);
1228                                 size_t value_len;
1229                                 const char *value_cs = lua_tolstring(L, -1, &value_len);
1230                                 std::string value(value_cs, value_len);
1231                                 istack.metadata.setString(key, value);
1232                                 lua_pop(L, 1); // removes value, keeps key for next iteration
1233                         }
1234                 }
1235
1236                 return istack;
1237         } else {
1238                 throw LuaError("Expecting itemstack, itemstring, table or nil");
1239         }
1240 }
1241
1242 /******************************************************************************/
1243 void push_tool_capabilities(lua_State *L,
1244                 const ToolCapabilities &toolcap)
1245 {
1246         lua_newtable(L);
1247         setfloatfield(L, -1, "full_punch_interval", toolcap.full_punch_interval);
1248         setintfield(L, -1, "max_drop_level", toolcap.max_drop_level);
1249         setintfield(L, -1, "punch_attack_uses", toolcap.punch_attack_uses);
1250                 // Create groupcaps table
1251                 lua_newtable(L);
1252                 // For each groupcap
1253                 for (const auto &gc_it : toolcap.groupcaps) {
1254                         // Create groupcap table
1255                         lua_newtable(L);
1256                         const std::string &name = gc_it.first;
1257                         const ToolGroupCap &groupcap = gc_it.second;
1258                         // Create subtable "times"
1259                         lua_newtable(L);
1260                         for (auto time : groupcap.times) {
1261                                 lua_pushinteger(L, time.first);
1262                                 lua_pushnumber(L, time.second);
1263                                 lua_settable(L, -3);
1264                         }
1265                         // Set subtable "times"
1266                         lua_setfield(L, -2, "times");
1267                         // Set simple parameters
1268                         setintfield(L, -1, "maxlevel", groupcap.maxlevel);
1269                         setintfield(L, -1, "uses", groupcap.uses);
1270                         // Insert groupcap table into groupcaps table
1271                         lua_setfield(L, -2, name.c_str());
1272                 }
1273                 // Set groupcaps table
1274                 lua_setfield(L, -2, "groupcaps");
1275                 //Create damage_groups table
1276                 lua_newtable(L);
1277                 // For each damage group
1278                 for (const auto &damageGroup : toolcap.damageGroups) {
1279                         // Create damage group table
1280                         lua_pushinteger(L, damageGroup.second);
1281                         lua_setfield(L, -2, damageGroup.first.c_str());
1282                 }
1283                 lua_setfield(L, -2, "damage_groups");
1284 }
1285
1286 /******************************************************************************/
1287 void push_inventory_list(lua_State *L, Inventory *inv, const char *name)
1288 {
1289         InventoryList *invlist = inv->getList(name);
1290         if(invlist == NULL){
1291                 lua_pushnil(L);
1292                 return;
1293         }
1294         std::vector<ItemStack> items;
1295         for(u32 i=0; i<invlist->getSize(); i++)
1296                 items.push_back(invlist->getItem(i));
1297         push_items(L, items);
1298 }
1299
1300 /******************************************************************************/
1301 void read_inventory_list(lua_State *L, int tableindex,
1302                 Inventory *inv, const char *name, Server* srv, int forcesize)
1303 {
1304         if(tableindex < 0)
1305                 tableindex = lua_gettop(L) + 1 + tableindex;
1306         // If nil, delete list
1307         if(lua_isnil(L, tableindex)){
1308                 inv->deleteList(name);
1309                 return;
1310         }
1311         // Otherwise set list
1312         std::vector<ItemStack> items = read_items(L, tableindex,srv);
1313         int listsize = (forcesize != -1) ? forcesize : items.size();
1314         InventoryList *invlist = inv->addList(name, listsize);
1315         int index = 0;
1316         for(std::vector<ItemStack>::const_iterator
1317                         i = items.begin(); i != items.end(); ++i){
1318                 if(forcesize != -1 && index == forcesize)
1319                         break;
1320                 invlist->changeItem(index, *i);
1321                 index++;
1322         }
1323         while(forcesize != -1 && index < forcesize){
1324                 invlist->deleteItem(index);
1325                 index++;
1326         }
1327 }
1328
1329 /******************************************************************************/
1330 struct TileAnimationParams read_animation_definition(lua_State *L, int index)
1331 {
1332         if(index < 0)
1333                 index = lua_gettop(L) + 1 + index;
1334
1335         struct TileAnimationParams anim;
1336         anim.type = TAT_NONE;
1337         if (!lua_istable(L, index))
1338                 return anim;
1339
1340         anim.type = (TileAnimationType)
1341                 getenumfield(L, index, "type", es_TileAnimationType,
1342                 TAT_NONE);
1343         if (anim.type == TAT_VERTICAL_FRAMES) {
1344                 // {type="vertical_frames", aspect_w=16, aspect_h=16, length=2.0}
1345                 anim.vertical_frames.aspect_w =
1346                         getintfield_default(L, index, "aspect_w", 16);
1347                 anim.vertical_frames.aspect_h =
1348                         getintfield_default(L, index, "aspect_h", 16);
1349                 anim.vertical_frames.length =
1350                         getfloatfield_default(L, index, "length", 1.0);
1351         } else if (anim.type == TAT_SHEET_2D) {
1352                 // {type="sheet_2d", frames_w=5, frames_h=3, frame_length=0.5}
1353                 getintfield(L, index, "frames_w",
1354                         anim.sheet_2d.frames_w);
1355                 getintfield(L, index, "frames_h",
1356                         anim.sheet_2d.frames_h);
1357                 getfloatfield(L, index, "frame_length",
1358                         anim.sheet_2d.frame_length);
1359         }
1360
1361         return anim;
1362 }
1363
1364 /******************************************************************************/
1365 ToolCapabilities read_tool_capabilities(
1366                 lua_State *L, int table)
1367 {
1368         ToolCapabilities toolcap;
1369         getfloatfield(L, table, "full_punch_interval", toolcap.full_punch_interval);
1370         getintfield(L, table, "max_drop_level", toolcap.max_drop_level);
1371         getintfield(L, table, "punch_attack_uses", toolcap.punch_attack_uses);
1372         lua_getfield(L, table, "groupcaps");
1373         if(lua_istable(L, -1)){
1374                 int table_groupcaps = lua_gettop(L);
1375                 lua_pushnil(L);
1376                 while(lua_next(L, table_groupcaps) != 0){
1377                         // key at index -2 and value at index -1
1378                         std::string groupname = luaL_checkstring(L, -2);
1379                         if(lua_istable(L, -1)){
1380                                 int table_groupcap = lua_gettop(L);
1381                                 // This will be created
1382                                 ToolGroupCap groupcap;
1383                                 // Read simple parameters
1384                                 getintfield(L, table_groupcap, "maxlevel", groupcap.maxlevel);
1385                                 getintfield(L, table_groupcap, "uses", groupcap.uses);
1386                                 // DEPRECATED: maxwear
1387                                 float maxwear = 0;
1388                                 if (getfloatfield(L, table_groupcap, "maxwear", maxwear)){
1389                                         if (maxwear != 0)
1390                                                 groupcap.uses = 1.0/maxwear;
1391                                         else
1392                                                 groupcap.uses = 0;
1393                                         warningstream << "Field \"maxwear\" is deprecated; "
1394                                                         << "replace with uses=1/maxwear" << std::endl;
1395                                         infostream << script_get_backtrace(L) << std::endl;
1396                                 }
1397                                 // Read "times" table
1398                                 lua_getfield(L, table_groupcap, "times");
1399                                 if(lua_istable(L, -1)){
1400                                         int table_times = lua_gettop(L);
1401                                         lua_pushnil(L);
1402                                         while(lua_next(L, table_times) != 0){
1403                                                 // key at index -2 and value at index -1
1404                                                 int rating = luaL_checkinteger(L, -2);
1405                                                 float time = luaL_checknumber(L, -1);
1406                                                 groupcap.times[rating] = time;
1407                                                 // removes value, keeps key for next iteration
1408                                                 lua_pop(L, 1);
1409                                         }
1410                                 }
1411                                 lua_pop(L, 1);
1412                                 // Insert groupcap into toolcap
1413                                 toolcap.groupcaps[groupname] = groupcap;
1414                         }
1415                         // removes value, keeps key for next iteration
1416                         lua_pop(L, 1);
1417                 }
1418         }
1419         lua_pop(L, 1);
1420
1421         lua_getfield(L, table, "damage_groups");
1422         if(lua_istable(L, -1)){
1423                 int table_damage_groups = lua_gettop(L);
1424                 lua_pushnil(L);
1425                 while(lua_next(L, table_damage_groups) != 0){
1426                         // key at index -2 and value at index -1
1427                         std::string groupname = luaL_checkstring(L, -2);
1428                         u16 value = luaL_checkinteger(L, -1);
1429                         toolcap.damageGroups[groupname] = value;
1430                         // removes value, keeps key for next iteration
1431                         lua_pop(L, 1);
1432                 }
1433         }
1434         lua_pop(L, 1);
1435         return toolcap;
1436 }
1437
1438 /******************************************************************************/
1439 void push_dig_params(lua_State *L,const DigParams &params)
1440 {
1441         lua_createtable(L, 0, 3);
1442         setboolfield(L, -1, "diggable", params.diggable);
1443         setfloatfield(L, -1, "time", params.time);
1444         setintfield(L, -1, "wear", params.wear);
1445 }
1446
1447 /******************************************************************************/
1448 void push_hit_params(lua_State *L,const HitParams &params)
1449 {
1450         lua_createtable(L, 0, 3);
1451         setintfield(L, -1, "hp", params.hp);
1452         setintfield(L, -1, "wear", params.wear);
1453 }
1454
1455 /******************************************************************************/
1456
1457 bool getflagsfield(lua_State *L, int table, const char *fieldname,
1458         FlagDesc *flagdesc, u32 *flags, u32 *flagmask)
1459 {
1460         lua_getfield(L, table, fieldname);
1461
1462         bool success = read_flags(L, -1, flagdesc, flags, flagmask);
1463
1464         lua_pop(L, 1);
1465
1466         return success;
1467 }
1468
1469 bool read_flags(lua_State *L, int index, FlagDesc *flagdesc,
1470         u32 *flags, u32 *flagmask)
1471 {
1472         if (lua_isstring(L, index)) {
1473                 std::string flagstr = lua_tostring(L, index);
1474                 *flags = readFlagString(flagstr, flagdesc, flagmask);
1475         } else if (lua_istable(L, index)) {
1476                 *flags = read_flags_table(L, index, flagdesc, flagmask);
1477         } else {
1478                 return false;
1479         }
1480
1481         return true;
1482 }
1483
1484 u32 read_flags_table(lua_State *L, int table, FlagDesc *flagdesc, u32 *flagmask)
1485 {
1486         u32 flags = 0, mask = 0;
1487         char fnamebuf[64] = "no";
1488
1489         for (int i = 0; flagdesc[i].name; i++) {
1490                 bool result;
1491
1492                 if (getboolfield(L, table, flagdesc[i].name, result)) {
1493                         mask |= flagdesc[i].flag;
1494                         if (result)
1495                                 flags |= flagdesc[i].flag;
1496                 }
1497
1498                 strlcpy(fnamebuf + 2, flagdesc[i].name, sizeof(fnamebuf) - 2);
1499                 if (getboolfield(L, table, fnamebuf, result))
1500                         mask |= flagdesc[i].flag;
1501         }
1502
1503         if (flagmask)
1504                 *flagmask = mask;
1505
1506         return flags;
1507 }
1508
1509 void push_flags_string(lua_State *L, FlagDesc *flagdesc, u32 flags, u32 flagmask)
1510 {
1511         std::string flagstring = writeFlagString(flags, flagdesc, flagmask);
1512         lua_pushlstring(L, flagstring.c_str(), flagstring.size());
1513 }
1514
1515 /******************************************************************************/
1516 /* Lua Stored data!                                                           */
1517 /******************************************************************************/
1518
1519 /******************************************************************************/
1520 void read_groups(lua_State *L, int index, ItemGroupList &result)
1521 {
1522         if (!lua_istable(L,index))
1523                 return;
1524         result.clear();
1525         lua_pushnil(L);
1526         if (index < 0)
1527                 index -= 1;
1528         while (lua_next(L, index) != 0) {
1529                 // key at index -2 and value at index -1
1530                 std::string name = luaL_checkstring(L, -2);
1531                 int rating = luaL_checkinteger(L, -1);
1532                 // zero rating indicates not in the group
1533                 if (rating != 0)
1534                         result[name] = rating;
1535                 // removes value, keeps key for next iteration
1536                 lua_pop(L, 1);
1537         }
1538 }
1539
1540 /******************************************************************************/
1541 void push_groups(lua_State *L, const ItemGroupList &groups)
1542 {
1543         lua_createtable(L, 0, groups.size());
1544         for (const auto &group : groups) {
1545                 lua_pushinteger(L, group.second);
1546                 lua_setfield(L, -2, group.first.c_str());
1547         }
1548 }
1549
1550 /******************************************************************************/
1551 void push_items(lua_State *L, const std::vector<ItemStack> &items)
1552 {
1553         lua_createtable(L, items.size(), 0);
1554         for (u32 i = 0; i != items.size(); i++) {
1555                 LuaItemStack::create(L, items[i]);
1556                 lua_rawseti(L, -2, i + 1);
1557         }
1558 }
1559
1560 /******************************************************************************/
1561 std::vector<ItemStack> read_items(lua_State *L, int index, Server *srv)
1562 {
1563         if(index < 0)
1564                 index = lua_gettop(L) + 1 + index;
1565
1566         std::vector<ItemStack> items;
1567         luaL_checktype(L, index, LUA_TTABLE);
1568         lua_pushnil(L);
1569         while (lua_next(L, index)) {
1570                 s32 key = luaL_checkinteger(L, -2);
1571                 if (key < 1) {
1572                         throw LuaError("Invalid inventory list index");
1573                 }
1574                 if (items.size() < (u32) key) {
1575                         items.resize(key);
1576                 }
1577                 items[key - 1] = read_item(L, -1, srv->idef());
1578                 lua_pop(L, 1);
1579         }
1580         return items;
1581 }
1582
1583 /******************************************************************************/
1584 void luaentity_get(lua_State *L, u16 id)
1585 {
1586         // Get luaentities[i]
1587         lua_getglobal(L, "core");
1588         lua_getfield(L, -1, "luaentities");
1589         luaL_checktype(L, -1, LUA_TTABLE);
1590         lua_pushinteger(L, id);
1591         lua_gettable(L, -2);
1592         lua_remove(L, -2); // Remove luaentities
1593         lua_remove(L, -2); // Remove core
1594 }
1595
1596 /******************************************************************************/
1597 bool read_noiseparams(lua_State *L, int index, NoiseParams *np)
1598 {
1599         if (index < 0)
1600                 index = lua_gettop(L) + 1 + index;
1601
1602         if (!lua_istable(L, index))
1603                 return false;
1604
1605         getfloatfield(L, index, "offset",      np->offset);
1606         getfloatfield(L, index, "scale",       np->scale);
1607         getfloatfield(L, index, "persist",     np->persist);
1608         getfloatfield(L, index, "persistence", np->persist);
1609         getfloatfield(L, index, "lacunarity",  np->lacunarity);
1610         getintfield(L,   index, "seed",        np->seed);
1611         getintfield(L,   index, "octaves",     np->octaves);
1612
1613         u32 flags    = 0;
1614         u32 flagmask = 0;
1615         np->flags = getflagsfield(L, index, "flags", flagdesc_noiseparams,
1616                 &flags, &flagmask) ? flags : NOISE_FLAG_DEFAULTS;
1617
1618         lua_getfield(L, index, "spread");
1619         np->spread  = read_v3f(L, -1);
1620         lua_pop(L, 1);
1621
1622         return true;
1623 }
1624
1625 void push_noiseparams(lua_State *L, NoiseParams *np)
1626 {
1627         lua_newtable(L);
1628         push_float_string(L, np->offset);
1629         lua_setfield(L, -2, "offset");
1630         push_float_string(L, np->scale);
1631         lua_setfield(L, -2, "scale");
1632         push_float_string(L, np->persist);
1633         lua_setfield(L, -2, "persistence");
1634         push_float_string(L, np->lacunarity);
1635         lua_setfield(L, -2, "lacunarity");
1636         lua_pushnumber(L, np->seed);
1637         lua_setfield(L, -2, "seed");
1638         lua_pushnumber(L, np->octaves);
1639         lua_setfield(L, -2, "octaves");
1640
1641         push_flags_string(L, flagdesc_noiseparams, np->flags,
1642                 np->flags);
1643         lua_setfield(L, -2, "flags");
1644
1645         push_v3_float_string(L, np->spread);
1646         lua_setfield(L, -2, "spread");
1647 }
1648
1649 /******************************************************************************/
1650 // Returns depth of json value tree
1651 static int push_json_value_getdepth(const Json::Value &value)
1652 {
1653         if (!value.isArray() && !value.isObject())
1654                 return 1;
1655
1656         int maxdepth = 0;
1657         for (const auto &it : value) {
1658                 int elemdepth = push_json_value_getdepth(it);
1659                 if (elemdepth > maxdepth)
1660                         maxdepth = elemdepth;
1661         }
1662         return maxdepth + 1;
1663 }
1664 // Recursive function to convert JSON --> Lua table
1665 static bool push_json_value_helper(lua_State *L, const Json::Value &value,
1666                 int nullindex)
1667 {
1668         switch(value.type()) {
1669                 case Json::nullValue:
1670                 default:
1671                         lua_pushvalue(L, nullindex);
1672                         break;
1673                 case Json::intValue:
1674                         lua_pushinteger(L, value.asLargestInt());
1675                         break;
1676                 case Json::uintValue:
1677                         lua_pushinteger(L, value.asLargestUInt());
1678                         break;
1679                 case Json::realValue:
1680                         lua_pushnumber(L, value.asDouble());
1681                         break;
1682                 case Json::stringValue:
1683                         {
1684                                 const char *str = value.asCString();
1685                                 lua_pushstring(L, str ? str : "");
1686                         }
1687                         break;
1688                 case Json::booleanValue:
1689                         lua_pushboolean(L, value.asInt());
1690                         break;
1691                 case Json::arrayValue:
1692                         lua_createtable(L, value.size(), 0);
1693                         for (Json::Value::const_iterator it = value.begin();
1694                                         it != value.end(); ++it) {
1695                                 push_json_value_helper(L, *it, nullindex);
1696                                 lua_rawseti(L, -2, it.index() + 1);
1697                         }
1698                         break;
1699                 case Json::objectValue:
1700                         lua_createtable(L, 0, value.size());
1701                         for (Json::Value::const_iterator it = value.begin();
1702                                         it != value.end(); ++it) {
1703 #if !defined(JSONCPP_STRING) && (JSONCPP_VERSION_MAJOR < 1 || JSONCPP_VERSION_MINOR < 9)
1704                                 const char *str = it.memberName();
1705                                 lua_pushstring(L, str ? str : "");
1706 #else
1707                                 std::string str = it.name();
1708                                 lua_pushstring(L, str.c_str());
1709 #endif
1710                                 push_json_value_helper(L, *it, nullindex);
1711                                 lua_rawset(L, -3);
1712                         }
1713                         break;
1714         }
1715         return true;
1716 }
1717 // converts JSON --> Lua table; returns false if lua stack limit exceeded
1718 // nullindex: Lua stack index of value to use in place of JSON null
1719 bool push_json_value(lua_State *L, const Json::Value &value, int nullindex)
1720 {
1721         if(nullindex < 0)
1722                 nullindex = lua_gettop(L) + 1 + nullindex;
1723
1724         int depth = push_json_value_getdepth(value);
1725
1726         // The maximum number of Lua stack slots used at each recursion level
1727         // of push_json_value_helper is 2, so make sure there a depth * 2 slots
1728         if (lua_checkstack(L, depth * 2))
1729                 return push_json_value_helper(L, value, nullindex);
1730
1731         return false;
1732 }
1733
1734 // Converts Lua table --> JSON
1735 void read_json_value(lua_State *L, Json::Value &root, int index, u8 recursion)
1736 {
1737         if (recursion > 16) {
1738                 throw SerializationError("Maximum recursion depth exceeded");
1739         }
1740         int type = lua_type(L, index);
1741         if (type == LUA_TBOOLEAN) {
1742                 root = (bool) lua_toboolean(L, index);
1743         } else if (type == LUA_TNUMBER) {
1744                 root = lua_tonumber(L, index);
1745         } else if (type == LUA_TSTRING) {
1746                 size_t len;
1747                 const char *str = lua_tolstring(L, index, &len);
1748                 root = std::string(str, len);
1749         } else if (type == LUA_TTABLE) {
1750                 lua_pushnil(L);
1751                 while (lua_next(L, index)) {
1752                         // Key is at -2 and value is at -1
1753                         Json::Value value;
1754                         read_json_value(L, value, lua_gettop(L), recursion + 1);
1755
1756                         Json::ValueType roottype = root.type();
1757                         int keytype = lua_type(L, -1);
1758                         if (keytype == LUA_TNUMBER) {
1759                                 lua_Number key = lua_tonumber(L, -1);
1760                                 if (roottype != Json::nullValue && roottype != Json::arrayValue) {
1761                                         throw SerializationError("Can't mix array and object values in JSON");
1762                                 } else if (key < 1) {
1763                                         throw SerializationError("Can't use zero-based or negative indexes in JSON");
1764                                 } else if (floor(key) != key) {
1765                                         throw SerializationError("Can't use indexes with a fractional part in JSON");
1766                                 }
1767                                 root[(Json::ArrayIndex) key - 1] = value;
1768                         } else if (keytype == LUA_TSTRING) {
1769                                 if (roottype != Json::nullValue && roottype != Json::objectValue) {
1770                                         throw SerializationError("Can't mix array and object values in JSON");
1771                                 }
1772                                 root[lua_tostring(L, -1)] = value;
1773                         } else {
1774                                 throw SerializationError("Lua key to convert to JSON is not a string or number");
1775                         }
1776                 }
1777         } else if (type == LUA_TNIL) {
1778                 root = Json::nullValue;
1779         } else {
1780                 throw SerializationError("Can only store booleans, numbers, strings, objects, arrays, and null in JSON");
1781         }
1782         lua_pop(L, 1); // Pop value
1783 }
1784
1785 void push_pointed_thing(lua_State *L, const PointedThing &pointed, bool csm,
1786         bool hitpoint)
1787 {
1788         lua_newtable(L);
1789         if (pointed.type == POINTEDTHING_NODE) {
1790                 lua_pushstring(L, "node");
1791                 lua_setfield(L, -2, "type");
1792                 push_v3s16(L, pointed.node_undersurface);
1793                 lua_setfield(L, -2, "under");
1794                 push_v3s16(L, pointed.node_abovesurface);
1795                 lua_setfield(L, -2, "above");
1796         } else if (pointed.type == POINTEDTHING_OBJECT) {
1797                 lua_pushstring(L, "object");
1798                 lua_setfield(L, -2, "type");
1799
1800                 if (csm) {
1801                         lua_pushinteger(L, pointed.object_id);
1802                         lua_setfield(L, -2, "id");
1803                 } else {
1804                         push_objectRef(L, pointed.object_id);
1805                         lua_setfield(L, -2, "ref");
1806                 }
1807         } else {
1808                 lua_pushstring(L, "nothing");
1809                 lua_setfield(L, -2, "type");
1810         }
1811         if (hitpoint && (pointed.type != POINTEDTHING_NOTHING)) {
1812                 push_v3f(L, pointed.intersection_point / BS); // convert to node coords
1813                 lua_setfield(L, -2, "intersection_point");
1814                 push_v3s16(L, pointed.intersection_normal);
1815                 lua_setfield(L, -2, "intersection_normal");
1816                 lua_pushinteger(L, pointed.box_id + 1); // change to Lua array index
1817                 lua_setfield(L, -2, "box_id");
1818         }
1819 }
1820
1821 void push_objectRef(lua_State *L, const u16 id)
1822 {
1823         // Get core.object_refs[i]
1824         lua_getglobal(L, "core");
1825         lua_getfield(L, -1, "object_refs");
1826         luaL_checktype(L, -1, LUA_TTABLE);
1827         lua_pushinteger(L, id);
1828         lua_gettable(L, -2);
1829         lua_remove(L, -2); // object_refs
1830         lua_remove(L, -2); // core
1831 }
1832
1833 void read_hud_element(lua_State *L, HudElement *elem)
1834 {
1835         elem->type = (HudElementType)getenumfield(L, 2, "hud_elem_type",
1836                                                                         es_HudElementType, HUD_ELEM_TEXT);
1837
1838         lua_getfield(L, 2, "position");
1839         elem->pos = lua_istable(L, -1) ? read_v2f(L, -1) : v2f();
1840         lua_pop(L, 1);
1841
1842         lua_getfield(L, 2, "scale");
1843         elem->scale = lua_istable(L, -1) ? read_v2f(L, -1) : v2f();
1844         lua_pop(L, 1);
1845
1846         lua_getfield(L, 2, "size");
1847         elem->size = lua_istable(L, -1) ? read_v2s32(L, -1) : v2s32();
1848         lua_pop(L, 1);
1849
1850         elem->name    = getstringfield_default(L, 2, "name", "");
1851         elem->text    = getstringfield_default(L, 2, "text", "");
1852         elem->number  = getintfield_default(L, 2, "number", 0);
1853         if (elem->type == HUD_ELEM_WAYPOINT)
1854                 // waypoints reuse the item field to store precision, item = precision + 1
1855                 elem->item = getintfield_default(L, 2, "precision", -1) + 1;
1856         else
1857                 elem->item = getintfield_default(L, 2, "item", 0);
1858         elem->dir     = getintfield_default(L, 2, "direction", 0);
1859         elem->z_index = MYMAX(S16_MIN, MYMIN(S16_MAX,
1860                         getintfield_default(L, 2, "z_index", 0)));
1861
1862         // Deprecated, only for compatibility's sake
1863         if (elem->dir == 0)
1864                 elem->dir = getintfield_default(L, 2, "dir", 0);
1865
1866         lua_getfield(L, 2, "alignment");
1867         elem->align = lua_istable(L, -1) ? read_v2f(L, -1) : v2f();
1868         lua_pop(L, 1);
1869
1870         lua_getfield(L, 2, "offset");
1871         elem->offset = lua_istable(L, -1) ? read_v2f(L, -1) : v2f();
1872         lua_pop(L, 1);
1873
1874         lua_getfield(L, 2, "world_pos");
1875         elem->world_pos = lua_istable(L, -1) ? read_v3f(L, -1) : v3f();
1876         lua_pop(L, 1);
1877
1878         /* check for known deprecated element usage */
1879         if ((elem->type  == HUD_ELEM_STATBAR) && (elem->size == v2s32()))
1880                 log_deprecated(L,"Deprecated usage of statbar without size!");
1881 }
1882
1883 void push_hud_element(lua_State *L, HudElement *elem)
1884 {
1885         lua_newtable(L);
1886
1887         lua_pushstring(L, es_HudElementType[(u8)elem->type].str);
1888         lua_setfield(L, -2, "type");
1889
1890         push_v2f(L, elem->pos);
1891         lua_setfield(L, -2, "position");
1892
1893         lua_pushstring(L, elem->name.c_str());
1894         lua_setfield(L, -2, "name");
1895
1896         push_v2f(L, elem->scale);
1897         lua_setfield(L, -2, "scale");
1898
1899         lua_pushstring(L, elem->text.c_str());
1900         lua_setfield(L, -2, "text");
1901
1902         lua_pushnumber(L, elem->number);
1903         lua_setfield(L, -2, "number");
1904
1905         lua_pushnumber(L, elem->item);
1906         lua_setfield(L, -2, "item");
1907
1908         lua_pushnumber(L, elem->dir);
1909         lua_setfield(L, -2, "direction");
1910
1911         push_v2f(L, elem->offset);
1912         lua_setfield(L, -2, "offset");
1913
1914         push_v2f(L, elem->align);
1915         lua_setfield(L, -2, "alignment");
1916
1917         push_v2s32(L, elem->size);
1918         lua_setfield(L, -2, "size");
1919
1920         // Deprecated, only for compatibility's sake
1921         lua_pushnumber(L, elem->dir);
1922         lua_setfield(L, -2, "dir");
1923
1924         push_v3f(L, elem->world_pos);
1925         lua_setfield(L, -2, "world_pos");
1926
1927         lua_pushnumber(L, elem->z_index);
1928         lua_setfield(L, -2, "z_index");
1929 }
1930
1931 HudElementStat read_hud_change(lua_State *L, HudElement *elem, void **value)
1932 {
1933         HudElementStat stat = HUD_STAT_NUMBER;
1934         if (lua_isstring(L, 3)) {
1935                 int statint;
1936                 std::string statstr = lua_tostring(L, 3);
1937                 stat = string_to_enum(es_HudElementStat, statint, statstr) ?
1938                                 (HudElementStat)statint : stat;
1939         }
1940
1941         switch (stat) {
1942                 case HUD_STAT_POS:
1943                         elem->pos = read_v2f(L, 4);
1944                         *value = &elem->pos;
1945                         break;
1946                 case HUD_STAT_NAME:
1947                         elem->name = luaL_checkstring(L, 4);
1948                         *value = &elem->name;
1949                         break;
1950                 case HUD_STAT_SCALE:
1951                         elem->scale = read_v2f(L, 4);
1952                         *value = &elem->scale;
1953                         break;
1954                 case HUD_STAT_TEXT:
1955                         elem->text = luaL_checkstring(L, 4);
1956                         *value = &elem->text;
1957                         break;
1958                 case HUD_STAT_NUMBER:
1959                         elem->number = luaL_checknumber(L, 4);
1960                         *value = &elem->number;
1961                         break;
1962                 case HUD_STAT_ITEM:
1963                         elem->item = luaL_checknumber(L, 4);
1964                         *value = &elem->item;
1965                         break;
1966                 case HUD_STAT_DIR:
1967                         elem->dir = luaL_checknumber(L, 4);
1968                         *value = &elem->dir;
1969                         break;
1970                 case HUD_STAT_ALIGN:
1971                         elem->align = read_v2f(L, 4);
1972                         *value = &elem->align;
1973                         break;
1974                 case HUD_STAT_OFFSET:
1975                         elem->offset = read_v2f(L, 4);
1976                         *value = &elem->offset;
1977                         break;
1978                 case HUD_STAT_WORLD_POS:
1979                         elem->world_pos = read_v3f(L, 4);
1980                         *value = &elem->world_pos;
1981                         break;
1982                 case HUD_STAT_SIZE:
1983                         elem->size = read_v2s32(L, 4);
1984                         *value = &elem->size;
1985                         break;
1986                 case HUD_STAT_Z_INDEX:
1987                         elem->z_index = MYMAX(S16_MIN, MYMIN(S16_MAX, luaL_checknumber(L, 4)));
1988                         *value = &elem->z_index;
1989                         break;
1990         }
1991         return stat;
1992 }