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