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