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