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