]> git.lizzy.rs Git - dragonfireclient.git/blob - src/script/common/c_content.cpp
Push error handler afresh each time lua_pcall is used
[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 "itemdef.h"
24 #include "object_properties.h"
25 #include "cpp_api/s_node.h"
26 #include "lua_api/l_object.h"
27 #include "lua_api/l_item.h"
28 #include "common/c_internal.h"
29 #include "server.h"
30 #include "log.h"
31 #include "tool.h"
32 #include "serverobject.h"
33 #include "porting.h"
34 #include "mg_schematic.h"
35 #include "noise.h"
36 #include "json/json.h"
37
38 struct EnumString es_TileAnimationType[] =
39 {
40         {TAT_NONE, "none"},
41         {TAT_VERTICAL_FRAMES, "vertical_frames"},
42         {0, NULL},
43 };
44
45 /******************************************************************************/
46 ItemDefinition read_item_definition(lua_State* L,int index,
47                 ItemDefinition default_def)
48 {
49         if(index < 0)
50                 index = lua_gettop(L) + 1 + index;
51
52         // Read the item definition
53         ItemDefinition def = default_def;
54
55         def.type = (ItemType)getenumfield(L, index, "type",
56                         es_ItemType, ITEM_NONE);
57         getstringfield(L, index, "name", def.name);
58         getstringfield(L, index, "description", def.description);
59         getstringfield(L, index, "inventory_image", def.inventory_image);
60         getstringfield(L, index, "wield_image", def.wield_image);
61
62         lua_getfield(L, index, "wield_scale");
63         if(lua_istable(L, -1)){
64                 def.wield_scale = check_v3f(L, -1);
65         }
66         lua_pop(L, 1);
67
68         def.stack_max = getintfield_default(L, index, "stack_max", def.stack_max);
69         if(def.stack_max == 0)
70                 def.stack_max = 1;
71
72         lua_getfield(L, index, "on_use");
73         def.usable = lua_isfunction(L, -1);
74         lua_pop(L, 1);
75
76         getboolfield(L, index, "liquids_pointable", def.liquids_pointable);
77
78         warn_if_field_exists(L, index, "tool_digging_properties",
79                         "deprecated: use tool_capabilities");
80
81         lua_getfield(L, index, "tool_capabilities");
82         if(lua_istable(L, -1)){
83                 def.tool_capabilities = new ToolCapabilities(
84                                 read_tool_capabilities(L, -1));
85         }
86
87         // If name is "" (hand), ensure there are ToolCapabilities
88         // because it will be looked up there whenever any other item has
89         // no ToolCapabilities
90         if(def.name == "" && def.tool_capabilities == NULL){
91                 def.tool_capabilities = new ToolCapabilities();
92         }
93
94         lua_getfield(L, index, "groups");
95         read_groups(L, -1, def.groups);
96         lua_pop(L, 1);
97
98         lua_getfield(L, index, "sounds");
99         if(lua_istable(L, -1)){
100                 lua_getfield(L, -1, "place");
101                 read_soundspec(L, -1, def.sound_place);
102                 lua_pop(L, 1);
103         }
104         lua_pop(L, 1);
105
106         def.range = getfloatfield_default(L, index, "range", def.range);
107
108         // Client shall immediately place this node when player places the item.
109         // Server will update the precise end result a moment later.
110         // "" = no prediction
111         getstringfield(L, index, "node_placement_prediction",
112                         def.node_placement_prediction);
113
114         return def;
115 }
116
117 /******************************************************************************/
118 void read_object_properties(lua_State *L, int index,
119                 ObjectProperties *prop)
120 {
121         if(index < 0)
122                 index = lua_gettop(L) + 1 + index;
123         if(!lua_istable(L, index))
124                 return;
125
126         prop->hp_max = getintfield_default(L, -1, "hp_max", 10);
127
128         getboolfield(L, -1, "physical", prop->physical);
129         getboolfield(L, -1, "collide_with_objects", prop->collideWithObjects);
130
131         getfloatfield(L, -1, "weight", prop->weight);
132
133         lua_getfield(L, -1, "collisionbox");
134         if(lua_istable(L, -1))
135                 prop->collisionbox = read_aabb3f(L, -1, 1.0);
136         lua_pop(L, 1);
137
138         getstringfield(L, -1, "visual", prop->visual);
139
140         getstringfield(L, -1, "mesh", prop->mesh);
141
142         lua_getfield(L, -1, "visual_size");
143         if(lua_istable(L, -1))
144                 prop->visual_size = read_v2f(L, -1);
145         lua_pop(L, 1);
146
147         lua_getfield(L, -1, "textures");
148         if(lua_istable(L, -1)){
149                 prop->textures.clear();
150                 int table = lua_gettop(L);
151                 lua_pushnil(L);
152                 while(lua_next(L, table) != 0){
153                         // key at index -2 and value at index -1
154                         if(lua_isstring(L, -1))
155                                 prop->textures.push_back(lua_tostring(L, -1));
156                         else
157                                 prop->textures.push_back("");
158                         // removes value, keeps key for next iteration
159                         lua_pop(L, 1);
160                 }
161         }
162         lua_pop(L, 1);
163
164         lua_getfield(L, -1, "colors");
165         if (lua_istable(L, -1)) {
166                 int table = lua_gettop(L);
167                 prop->colors.clear();
168                 for (lua_pushnil(L); lua_next(L, table); lua_pop(L, 1)) {
169                         video::SColor color(255, 255, 255, 255);
170                         read_color(L, -1, &color);
171                         prop->colors.push_back(color);
172                 }
173         }
174         lua_pop(L, 1);
175
176         lua_getfield(L, -1, "spritediv");
177         if(lua_istable(L, -1))
178                 prop->spritediv = read_v2s16(L, -1);
179         lua_pop(L, 1);
180
181         lua_getfield(L, -1, "initial_sprite_basepos");
182         if(lua_istable(L, -1))
183                 prop->initial_sprite_basepos = read_v2s16(L, -1);
184         lua_pop(L, 1);
185
186         getboolfield(L, -1, "is_visible", prop->is_visible);
187         getboolfield(L, -1, "makes_footstep_sound", prop->makes_footstep_sound);
188         getfloatfield(L, -1, "automatic_rotate", prop->automatic_rotate);
189         if (getfloatfield(L, -1, "stepheight", prop->stepheight))
190                 prop->stepheight *= BS;
191         lua_getfield(L, -1, "automatic_face_movement_dir");
192         if (lua_isnumber(L, -1)) {
193                 prop->automatic_face_movement_dir = true;
194                 prop->automatic_face_movement_dir_offset = luaL_checknumber(L, -1);
195         } else if (lua_isboolean(L, -1)) {
196                 prop->automatic_face_movement_dir = lua_toboolean(L, -1);
197                 prop->automatic_face_movement_dir_offset = 0.0;
198         }
199         lua_pop(L, 1);
200 }
201
202 /******************************************************************************/
203 void push_object_properties(lua_State *L, ObjectProperties *prop)
204 {
205         lua_newtable(L);
206         lua_pushnumber(L, prop->hp_max);
207         lua_setfield(L, -2, "hp_max");
208         lua_pushboolean(L, prop->physical);
209         lua_setfield(L, -2, "physical");
210         lua_pushboolean(L, prop->collideWithObjects);
211         lua_setfield(L, -2, "collide_with_objects");
212         lua_pushnumber(L, prop->weight);
213         lua_setfield(L, -2, "weight");
214         push_aabb3f(L, prop->collisionbox);
215         lua_setfield(L, -2, "collisionbox");
216         lua_pushlstring(L, prop->visual.c_str(), prop->visual.size());
217         lua_setfield(L, -2, "visual");
218         lua_pushlstring(L, prop->mesh.c_str(), prop->mesh.size());
219         lua_setfield(L, -2, "mesh");
220         push_v2f(L, prop->visual_size);
221         lua_setfield(L, -2, "visual_size");
222
223         lua_newtable(L);
224         u16 i = 1;
225         for (std::vector<std::string>::iterator it = prop->textures.begin();
226                         it != prop->textures.end(); ++it) {
227                 lua_pushlstring(L, it->c_str(), it->size());
228                 lua_rawseti(L, -2, i);
229         }
230         lua_setfield(L, -2, "textures");
231
232         lua_newtable(L);
233         i = 1;
234         for (std::vector<video::SColor>::iterator it = prop->colors.begin();
235                         it != prop->colors.end(); ++it) {
236                 push_ARGB8(L, *it);
237                 lua_rawseti(L, -2, i);
238         }
239         lua_setfield(L, -2, "colors");
240
241         push_v2s16(L, prop->spritediv);
242         lua_setfield(L, -2, "spritediv");
243         push_v2s16(L, prop->initial_sprite_basepos);
244         lua_setfield(L, -2, "initial_sprite_basepos");
245         lua_pushboolean(L, prop->is_visible);
246         lua_setfield(L, -2, "is_visible");
247         lua_pushboolean(L, prop->makes_footstep_sound);
248         lua_setfield(L, -2, "makes_footstep_sound");
249         lua_pushnumber(L, prop->automatic_rotate);
250         lua_setfield(L, -2, "automatic_rotate");
251         lua_pushnumber(L, prop->stepheight / BS);
252         lua_setfield(L, -2, "stepheight");
253         if (prop->automatic_face_movement_dir)
254                 lua_pushnumber(L, prop->automatic_face_movement_dir_offset);
255         else
256                 lua_pushboolean(L, false);
257         lua_setfield(L, -2, "automatic_face_movement_dir");
258 }
259
260 /******************************************************************************/
261 TileDef read_tiledef(lua_State *L, int index, u8 drawtype)
262 {
263         if(index < 0)
264                 index = lua_gettop(L) + 1 + index;
265
266         TileDef tiledef;
267         bool default_tiling = (drawtype == NDT_PLANTLIKE || drawtype == NDT_FIRELIKE)
268                 ? false : true;
269         // key at index -2 and value at index
270         if(lua_isstring(L, index)){
271                 // "default_lava.png"
272                 tiledef.name = lua_tostring(L, index);
273                 tiledef.tileable_vertical = default_tiling;
274                 tiledef.tileable_horizontal = default_tiling;
275         }
276         else if(lua_istable(L, index))
277         {
278                 // {name="default_lava.png", animation={}}
279                 tiledef.name = "";
280                 getstringfield(L, index, "name", tiledef.name);
281                 getstringfield(L, index, "image", tiledef.name); // MaterialSpec compat.
282                 tiledef.backface_culling = getboolfield_default(
283                         L, index, "backface_culling", true);
284                 tiledef.tileable_horizontal = getboolfield_default(
285                         L, index, "tileable_horizontal", default_tiling);
286                 tiledef.tileable_vertical = getboolfield_default(
287                         L, index, "tileable_vertical", default_tiling);
288                 // animation = {}
289                 lua_getfield(L, index, "animation");
290                 if(lua_istable(L, -1)){
291                         // {type="vertical_frames", aspect_w=16, aspect_h=16, length=2.0}
292                         tiledef.animation.type = (TileAnimationType)
293                                 getenumfield(L, -1, "type", es_TileAnimationType,
294                                 TAT_NONE);
295                         tiledef.animation.aspect_w =
296                                 getintfield_default(L, -1, "aspect_w", 16);
297                         tiledef.animation.aspect_h =
298                                 getintfield_default(L, -1, "aspect_h", 16);
299                         tiledef.animation.length =
300                                 getfloatfield_default(L, -1, "length", 1.0);
301                 }
302                 lua_pop(L, 1);
303         }
304
305         return tiledef;
306 }
307
308 /******************************************************************************/
309 ContentFeatures read_content_features(lua_State *L, int index)
310 {
311         if(index < 0)
312                 index = lua_gettop(L) + 1 + index;
313
314         ContentFeatures f;
315
316         /* Cache existence of some callbacks */
317         lua_getfield(L, index, "on_construct");
318         if(!lua_isnil(L, -1)) f.has_on_construct = true;
319         lua_pop(L, 1);
320         lua_getfield(L, index, "on_destruct");
321         if(!lua_isnil(L, -1)) f.has_on_destruct = true;
322         lua_pop(L, 1);
323         lua_getfield(L, index, "after_destruct");
324         if(!lua_isnil(L, -1)) f.has_after_destruct = true;
325         lua_pop(L, 1);
326
327         lua_getfield(L, index, "on_rightclick");
328         f.rightclickable = lua_isfunction(L, -1);
329         lua_pop(L, 1);
330
331         /* Name */
332         getstringfield(L, index, "name", f.name);
333
334         /* Groups */
335         lua_getfield(L, index, "groups");
336         read_groups(L, -1, f.groups);
337         lua_pop(L, 1);
338
339         /* Visual definition */
340
341         f.drawtype = (NodeDrawType)getenumfield(L, index, "drawtype",
342                         ScriptApiNode::es_DrawType,NDT_NORMAL);
343         getfloatfield(L, index, "visual_scale", f.visual_scale);
344
345         /* Meshnode model filename */
346         getstringfield(L, index, "mesh", f.mesh);
347
348         // tiles = {}
349         lua_getfield(L, index, "tiles");
350         // If nil, try the deprecated name "tile_images" instead
351         if(lua_isnil(L, -1)){
352                 lua_pop(L, 1);
353                 warn_if_field_exists(L, index, "tile_images",
354                                 "Deprecated; new name is \"tiles\".");
355                 lua_getfield(L, index, "tile_images");
356         }
357         if(lua_istable(L, -1)){
358                 int table = lua_gettop(L);
359                 lua_pushnil(L);
360                 int i = 0;
361                 while(lua_next(L, table) != 0){
362                         // Read tiledef from value
363                         f.tiledef[i] = read_tiledef(L, -1, f.drawtype);
364                         // removes value, keeps key for next iteration
365                         lua_pop(L, 1);
366                         i++;
367                         if(i==6){
368                                 lua_pop(L, 1);
369                                 break;
370                         }
371                 }
372                 // Copy last value to all remaining textures
373                 if(i >= 1){
374                         TileDef lasttile = f.tiledef[i-1];
375                         while(i < 6){
376                                 f.tiledef[i] = lasttile;
377                                 i++;
378                         }
379                 }
380         }
381         lua_pop(L, 1);
382
383         // special_tiles = {}
384         lua_getfield(L, index, "special_tiles");
385         // If nil, try the deprecated name "special_materials" instead
386         if(lua_isnil(L, -1)){
387                 lua_pop(L, 1);
388                 warn_if_field_exists(L, index, "special_materials",
389                                 "Deprecated; new name is \"special_tiles\".");
390                 lua_getfield(L, index, "special_materials");
391         }
392         if(lua_istable(L, -1)){
393                 int table = lua_gettop(L);
394                 lua_pushnil(L);
395                 int i = 0;
396                 while(lua_next(L, table) != 0){
397                         // Read tiledef from value
398                         f.tiledef_special[i] = read_tiledef(L, -1, f.drawtype);
399                         // removes value, keeps key for next iteration
400                         lua_pop(L, 1);
401                         i++;
402                         if(i==CF_SPECIAL_COUNT){
403                                 lua_pop(L, 1);
404                                 break;
405                         }
406                 }
407         }
408         lua_pop(L, 1);
409
410         f.alpha = getintfield_default(L, index, "alpha", 255);
411
412         bool usealpha = getboolfield_default(L, index,
413                         "use_texture_alpha", false);
414         if (usealpha)
415                 f.alpha = 0;
416
417         /* Other stuff */
418
419         lua_getfield(L, index, "post_effect_color");
420         read_color(L, -1, &f.post_effect_color);
421         lua_pop(L, 1);
422
423         f.param_type = (ContentParamType)getenumfield(L, index, "paramtype",
424                         ScriptApiNode::es_ContentParamType, CPT_NONE);
425         f.param_type_2 = (ContentParamType2)getenumfield(L, index, "paramtype2",
426                         ScriptApiNode::es_ContentParamType2, CPT2_NONE);
427
428         // Warn about some deprecated fields
429         warn_if_field_exists(L, index, "wall_mounted",
430                         "deprecated: use paramtype2 = 'wallmounted'");
431         warn_if_field_exists(L, index, "light_propagates",
432                         "deprecated: determined from paramtype");
433         warn_if_field_exists(L, index, "dug_item",
434                         "deprecated: use 'drop' field");
435         warn_if_field_exists(L, index, "extra_dug_item",
436                         "deprecated: use 'drop' field");
437         warn_if_field_exists(L, index, "extra_dug_item_rarity",
438                         "deprecated: use 'drop' field");
439         warn_if_field_exists(L, index, "metadata_name",
440                         "deprecated: use on_add and metadata callbacks");
441
442         // True for all ground-like things like stone and mud, false for eg. trees
443         getboolfield(L, index, "is_ground_content", f.is_ground_content);
444         f.light_propagates = (f.param_type == CPT_LIGHT);
445         getboolfield(L, index, "sunlight_propagates", f.sunlight_propagates);
446         // This is used for collision detection.
447         // Also for general solidness queries.
448         getboolfield(L, index, "walkable", f.walkable);
449         // Player can point to these
450         getboolfield(L, index, "pointable", f.pointable);
451         // Player can dig these
452         getboolfield(L, index, "diggable", f.diggable);
453         // Player can climb these
454         getboolfield(L, index, "climbable", f.climbable);
455         // Player can build on these
456         getboolfield(L, index, "buildable_to", f.buildable_to);
457         // Whether the node is non-liquid, source liquid or flowing liquid
458         f.liquid_type = (LiquidType)getenumfield(L, index, "liquidtype",
459                         ScriptApiNode::es_LiquidType, LIQUID_NONE);
460         // If the content is liquid, this is the flowing version of the liquid.
461         getstringfield(L, index, "liquid_alternative_flowing",
462                         f.liquid_alternative_flowing);
463         // If the content is liquid, this is the source version of the liquid.
464         getstringfield(L, index, "liquid_alternative_source",
465                         f.liquid_alternative_source);
466         // Viscosity for fluid flow, ranging from 1 to 7, with
467         // 1 giving almost instantaneous propagation and 7 being
468         // the slowest possible
469         f.liquid_viscosity = getintfield_default(L, index,
470                         "liquid_viscosity", f.liquid_viscosity);
471         f.liquid_range = getintfield_default(L, index,
472                         "liquid_range", f.liquid_range);
473         f.leveled = getintfield_default(L, index, "leveled", f.leveled);
474
475         getboolfield(L, index, "liquid_renewable", f.liquid_renewable);
476         f.drowning = getintfield_default(L, index,
477                         "drowning", f.drowning);
478         // Amount of light the node emits
479         f.light_source = getintfield_default(L, index,
480                         "light_source", f.light_source);
481         f.damage_per_second = getintfield_default(L, index,
482                         "damage_per_second", f.damage_per_second);
483
484         lua_getfield(L, index, "node_box");
485         if(lua_istable(L, -1))
486                 f.node_box = read_nodebox(L, -1);
487         lua_pop(L, 1);
488
489         lua_getfield(L, index, "selection_box");
490         if(lua_istable(L, -1))
491                 f.selection_box = read_nodebox(L, -1);
492         lua_pop(L, 1);
493
494         lua_getfield(L, index, "collision_box");
495         if(lua_istable(L, -1))
496                 f.collision_box = read_nodebox(L, -1);
497         lua_pop(L, 1);
498
499         f.waving = getintfield_default(L, index,
500                         "waving", f.waving);
501
502         // Set to true if paramtype used to be 'facedir_simple'
503         getboolfield(L, index, "legacy_facedir_simple", f.legacy_facedir_simple);
504         // Set to true if wall_mounted used to be set to true
505         getboolfield(L, index, "legacy_wallmounted", f.legacy_wallmounted);
506
507         // Sound table
508         lua_getfield(L, index, "sounds");
509         if(lua_istable(L, -1)){
510                 lua_getfield(L, -1, "footstep");
511                 read_soundspec(L, -1, f.sound_footstep);
512                 lua_pop(L, 1);
513                 lua_getfield(L, -1, "dig");
514                 read_soundspec(L, -1, f.sound_dig);
515                 lua_pop(L, 1);
516                 lua_getfield(L, -1, "dug");
517                 read_soundspec(L, -1, f.sound_dug);
518                 lua_pop(L, 1);
519         }
520         lua_pop(L, 1);
521
522         return f;
523 }
524
525 /******************************************************************************/
526 void read_server_sound_params(lua_State *L, int index,
527                 ServerSoundParams &params)
528 {
529         if(index < 0)
530                 index = lua_gettop(L) + 1 + index;
531         // Clear
532         params = ServerSoundParams();
533         if(lua_istable(L, index)){
534                 getfloatfield(L, index, "gain", params.gain);
535                 getstringfield(L, index, "to_player", params.to_player);
536                 lua_getfield(L, index, "pos");
537                 if(!lua_isnil(L, -1)){
538                         v3f p = read_v3f(L, -1)*BS;
539                         params.pos = p;
540                         params.type = ServerSoundParams::SSP_POSITIONAL;
541                 }
542                 lua_pop(L, 1);
543                 lua_getfield(L, index, "object");
544                 if(!lua_isnil(L, -1)){
545                         ObjectRef *ref = ObjectRef::checkobject(L, -1);
546                         ServerActiveObject *sao = ObjectRef::getobject(ref);
547                         if(sao){
548                                 params.object = sao->getId();
549                                 params.type = ServerSoundParams::SSP_OBJECT;
550                         }
551                 }
552                 lua_pop(L, 1);
553                 params.max_hear_distance = BS*getfloatfield_default(L, index,
554                                 "max_hear_distance", params.max_hear_distance/BS);
555                 getboolfield(L, index, "loop", params.loop);
556         }
557 }
558
559 /******************************************************************************/
560 void read_soundspec(lua_State *L, int index, SimpleSoundSpec &spec)
561 {
562         if(index < 0)
563                 index = lua_gettop(L) + 1 + index;
564         if(lua_isnil(L, index)){
565         } else if(lua_istable(L, index)){
566                 getstringfield(L, index, "name", spec.name);
567                 getfloatfield(L, index, "gain", spec.gain);
568         } else if(lua_isstring(L, index)){
569                 spec.name = lua_tostring(L, index);
570         }
571 }
572
573 /******************************************************************************/
574 NodeBox read_nodebox(lua_State *L, int index)
575 {
576         NodeBox nodebox;
577         if(lua_istable(L, -1)){
578                 nodebox.type = (NodeBoxType)getenumfield(L, index, "type",
579                                 ScriptApiNode::es_NodeBoxType, NODEBOX_REGULAR);
580
581                 lua_getfield(L, index, "fixed");
582                 if(lua_istable(L, -1))
583                         nodebox.fixed = read_aabb3f_vector(L, -1, BS);
584                 lua_pop(L, 1);
585
586                 lua_getfield(L, index, "wall_top");
587                 if(lua_istable(L, -1))
588                         nodebox.wall_top = read_aabb3f(L, -1, BS);
589                 lua_pop(L, 1);
590
591                 lua_getfield(L, index, "wall_bottom");
592                 if(lua_istable(L, -1))
593                         nodebox.wall_bottom = read_aabb3f(L, -1, BS);
594                 lua_pop(L, 1);
595
596                 lua_getfield(L, index, "wall_side");
597                 if(lua_istable(L, -1))
598                         nodebox.wall_side = read_aabb3f(L, -1, BS);
599                 lua_pop(L, 1);
600         }
601         return nodebox;
602 }
603
604 /******************************************************************************/
605 MapNode readnode(lua_State *L, int index, INodeDefManager *ndef)
606 {
607         lua_getfield(L, index, "name");
608         if (!lua_isstring(L, -1))
609                 throw LuaError("Node name is not set or is not a string!");
610         const char *name = lua_tostring(L, -1);
611         lua_pop(L, 1);
612
613         u8 param1 = 0;
614         lua_getfield(L, index, "param1");
615         if (!lua_isnil(L, -1))
616                 param1 = lua_tonumber(L, -1);
617         lua_pop(L, 1);
618
619         u8 param2 = 0;
620         lua_getfield(L, index, "param2");
621         if (!lua_isnil(L, -1))
622                 param2 = lua_tonumber(L, -1);
623         lua_pop(L, 1);
624
625         return MapNode(ndef, name, param1, param2);
626 }
627
628 /******************************************************************************/
629 void pushnode(lua_State *L, const MapNode &n, INodeDefManager *ndef)
630 {
631         lua_newtable(L);
632         lua_pushstring(L, ndef->get(n).name.c_str());
633         lua_setfield(L, -2, "name");
634         lua_pushnumber(L, n.getParam1());
635         lua_setfield(L, -2, "param1");
636         lua_pushnumber(L, n.getParam2());
637         lua_setfield(L, -2, "param2");
638 }
639
640 /******************************************************************************/
641 void warn_if_field_exists(lua_State *L, int table,
642                 const char *fieldname, const std::string &message)
643 {
644         lua_getfield(L, table, fieldname);
645         if(!lua_isnil(L, -1)){
646 //TODO find way to access backtrace fct from here
647                 //              infostream<<script_get_backtrace(L)<<std::endl;
648                 infostream<<"WARNING: field \""<<fieldname<<"\": "
649                                 <<message<<std::endl;
650         }
651         lua_pop(L, 1);
652 }
653
654 /******************************************************************************/
655 int getenumfield(lua_State *L, int table,
656                 const char *fieldname, const EnumString *spec, int default_)
657 {
658         int result = default_;
659         string_to_enum(spec, result,
660                         getstringfield_default(L, table, fieldname, ""));
661         return result;
662 }
663
664 /******************************************************************************/
665 bool string_to_enum(const EnumString *spec, int &result,
666                 const std::string &str)
667 {
668         const EnumString *esp = spec;
669         while(esp->str){
670                 if(str == std::string(esp->str)){
671                         result = esp->num;
672                         return true;
673                 }
674                 esp++;
675         }
676         return false;
677 }
678
679 /******************************************************************************/
680 ItemStack read_item(lua_State* L, int index,Server* srv)
681 {
682         if(index < 0)
683                 index = lua_gettop(L) + 1 + index;
684
685         if(lua_isnil(L, index))
686         {
687                 return ItemStack();
688         }
689         else if(lua_isuserdata(L, index))
690         {
691                 // Convert from LuaItemStack
692                 LuaItemStack *o = LuaItemStack::checkobject(L, index);
693                 return o->getItem();
694         }
695         else if(lua_isstring(L, index))
696         {
697                 // Convert from itemstring
698                 std::string itemstring = lua_tostring(L, index);
699                 IItemDefManager *idef = srv->idef();
700                 try
701                 {
702                         ItemStack item;
703                         item.deSerialize(itemstring, idef);
704                         return item;
705                 }
706                 catch(SerializationError &e)
707                 {
708                         infostream<<"WARNING: unable to create item from itemstring"
709                                         <<": "<<itemstring<<std::endl;
710                         return ItemStack();
711                 }
712         }
713         else if(lua_istable(L, index))
714         {
715                 // Convert from table
716                 IItemDefManager *idef = srv->idef();
717                 std::string name = getstringfield_default(L, index, "name", "");
718                 int count = getintfield_default(L, index, "count", 1);
719                 int wear = getintfield_default(L, index, "wear", 0);
720                 std::string metadata = getstringfield_default(L, index, "metadata", "");
721                 return ItemStack(name, count, wear, metadata, idef);
722         }
723         else
724         {
725                 throw LuaError("Expecting itemstack, itemstring, table or nil");
726         }
727 }
728
729 /******************************************************************************/
730 void push_tool_capabilities(lua_State *L,
731                 const ToolCapabilities &toolcap)
732 {
733         lua_newtable(L);
734         setfloatfield(L, -1, "full_punch_interval", toolcap.full_punch_interval);
735                 setintfield(L, -1, "max_drop_level", toolcap.max_drop_level);
736                 // Create groupcaps table
737                 lua_newtable(L);
738                 // For each groupcap
739                 for(std::map<std::string, ToolGroupCap>::const_iterator
740                                 i = toolcap.groupcaps.begin(); i != toolcap.groupcaps.end(); i++){
741                         // Create groupcap table
742                         lua_newtable(L);
743                         const std::string &name = i->first;
744                         const ToolGroupCap &groupcap = i->second;
745                         // Create subtable "times"
746                         lua_newtable(L);
747                         for(std::map<int, float>::const_iterator
748                                         i = groupcap.times.begin(); i != groupcap.times.end(); i++){
749                                 int rating = i->first;
750                                 float time = i->second;
751                                 lua_pushinteger(L, rating);
752                                 lua_pushnumber(L, time);
753                                 lua_settable(L, -3);
754                         }
755                         // Set subtable "times"
756                         lua_setfield(L, -2, "times");
757                         // Set simple parameters
758                         setintfield(L, -1, "maxlevel", groupcap.maxlevel);
759                         setintfield(L, -1, "uses", groupcap.uses);
760                         // Insert groupcap table into groupcaps table
761                         lua_setfield(L, -2, name.c_str());
762                 }
763                 // Set groupcaps table
764                 lua_setfield(L, -2, "groupcaps");
765                 //Create damage_groups table
766                 lua_newtable(L);
767                 // For each damage group
768                 for(std::map<std::string, s16>::const_iterator
769                                 i = toolcap.damageGroups.begin(); i != toolcap.damageGroups.end(); i++){
770                         // Create damage group table
771                         lua_pushinteger(L, i->second);
772                         lua_setfield(L, -2, i->first.c_str());
773                 }
774                 lua_setfield(L, -2, "damage_groups");
775 }
776
777 /******************************************************************************/
778 void push_inventory_list(lua_State *L, Inventory *inv, const char *name)
779 {
780         InventoryList *invlist = inv->getList(name);
781         if(invlist == NULL){
782                 lua_pushnil(L);
783                 return;
784         }
785         std::vector<ItemStack> items;
786         for(u32 i=0; i<invlist->getSize(); i++)
787                 items.push_back(invlist->getItem(i));
788         push_items(L, items);
789 }
790
791 /******************************************************************************/
792 void read_inventory_list(lua_State *L, int tableindex,
793                 Inventory *inv, const char *name, Server* srv, int forcesize)
794 {
795         if(tableindex < 0)
796                 tableindex = lua_gettop(L) + 1 + tableindex;
797         // If nil, delete list
798         if(lua_isnil(L, tableindex)){
799                 inv->deleteList(name);
800                 return;
801         }
802         // Otherwise set list
803         std::vector<ItemStack> items = read_items(L, tableindex,srv);
804         int listsize = (forcesize != -1) ? forcesize : items.size();
805         InventoryList *invlist = inv->addList(name, listsize);
806         int index = 0;
807         for(std::vector<ItemStack>::const_iterator
808                         i = items.begin(); i != items.end(); i++){
809                 if(forcesize != -1 && index == forcesize)
810                         break;
811                 invlist->changeItem(index, *i);
812                 index++;
813         }
814         while(forcesize != -1 && index < forcesize){
815                 invlist->deleteItem(index);
816                 index++;
817         }
818 }
819
820 /******************************************************************************/
821 ToolCapabilities read_tool_capabilities(
822                 lua_State *L, int table)
823 {
824         ToolCapabilities toolcap;
825         getfloatfield(L, table, "full_punch_interval", toolcap.full_punch_interval);
826         getintfield(L, table, "max_drop_level", toolcap.max_drop_level);
827         lua_getfield(L, table, "groupcaps");
828         if(lua_istable(L, -1)){
829                 int table_groupcaps = lua_gettop(L);
830                 lua_pushnil(L);
831                 while(lua_next(L, table_groupcaps) != 0){
832                         // key at index -2 and value at index -1
833                         std::string groupname = luaL_checkstring(L, -2);
834                         if(lua_istable(L, -1)){
835                                 int table_groupcap = lua_gettop(L);
836                                 // This will be created
837                                 ToolGroupCap groupcap;
838                                 // Read simple parameters
839                                 getintfield(L, table_groupcap, "maxlevel", groupcap.maxlevel);
840                                 getintfield(L, table_groupcap, "uses", groupcap.uses);
841                                 // DEPRECATED: maxwear
842                                 float maxwear = 0;
843                                 if(getfloatfield(L, table_groupcap, "maxwear", maxwear)){
844                                         if(maxwear != 0)
845                                                 groupcap.uses = 1.0/maxwear;
846                                         else
847                                                 groupcap.uses = 0;
848                                         infostream<<script_get_backtrace(L)<<std::endl;
849                                         infostream<<"WARNING: field \"maxwear\" is deprecated; "
850                                                         <<"should replace with uses=1/maxwear"<<std::endl;
851                                 }
852                                 // Read "times" table
853                                 lua_getfield(L, table_groupcap, "times");
854                                 if(lua_istable(L, -1)){
855                                         int table_times = lua_gettop(L);
856                                         lua_pushnil(L);
857                                         while(lua_next(L, table_times) != 0){
858                                                 // key at index -2 and value at index -1
859                                                 int rating = luaL_checkinteger(L, -2);
860                                                 float time = luaL_checknumber(L, -1);
861                                                 groupcap.times[rating] = time;
862                                                 // removes value, keeps key for next iteration
863                                                 lua_pop(L, 1);
864                                         }
865                                 }
866                                 lua_pop(L, 1);
867                                 // Insert groupcap into toolcap
868                                 toolcap.groupcaps[groupname] = groupcap;
869                         }
870                         // removes value, keeps key for next iteration
871                         lua_pop(L, 1);
872                 }
873         }
874         lua_pop(L, 1);
875
876         lua_getfield(L, table, "damage_groups");
877         if(lua_istable(L, -1)){
878                 int table_damage_groups = lua_gettop(L);
879                 lua_pushnil(L);
880                 while(lua_next(L, table_damage_groups) != 0){
881                         // key at index -2 and value at index -1
882                         std::string groupname = luaL_checkstring(L, -2);
883                         u16 value = luaL_checkinteger(L, -1);
884                         toolcap.damageGroups[groupname] = value;
885                         // removes value, keeps key for next iteration
886                         lua_pop(L, 1);
887                 }
888         }
889         lua_pop(L, 1);
890         return toolcap;
891 }
892
893 /******************************************************************************/
894 void push_dig_params(lua_State *L,const DigParams &params)
895 {
896         lua_newtable(L);
897         setboolfield(L, -1, "diggable", params.diggable);
898         setfloatfield(L, -1, "time", params.time);
899         setintfield(L, -1, "wear", params.wear);
900 }
901
902 /******************************************************************************/
903 void push_hit_params(lua_State *L,const HitParams &params)
904 {
905         lua_newtable(L);
906         setintfield(L, -1, "hp", params.hp);
907         setintfield(L, -1, "wear", params.wear);
908 }
909
910 /******************************************************************************/
911
912 bool getflagsfield(lua_State *L, int table, const char *fieldname,
913         FlagDesc *flagdesc, u32 *flags, u32 *flagmask)
914 {
915         lua_getfield(L, table, fieldname);
916
917         bool success = read_flags(L, -1, flagdesc, flags, flagmask);
918
919         lua_pop(L, 1);
920
921         return success;
922 }
923
924 bool read_flags(lua_State *L, int index, FlagDesc *flagdesc,
925         u32 *flags, u32 *flagmask)
926 {
927         if (lua_isstring(L, index)) {
928                 std::string flagstr = lua_tostring(L, index);
929                 *flags = readFlagString(flagstr, flagdesc, flagmask);
930         } else if (lua_istable(L, index)) {
931                 *flags = read_flags_table(L, index, flagdesc, flagmask);
932         } else {
933                 return false;
934         }
935
936         return true;
937 }
938
939 u32 read_flags_table(lua_State *L, int table, FlagDesc *flagdesc, u32 *flagmask)
940 {
941         u32 flags = 0, mask = 0;
942         char fnamebuf[64] = "no";
943
944         for (int i = 0; flagdesc[i].name; i++) {
945                 bool result;
946
947                 if (getboolfield(L, table, flagdesc[i].name, result)) {
948                         mask |= flagdesc[i].flag;
949                         if (result)
950                                 flags |= flagdesc[i].flag;
951                 }
952
953                 strlcpy(fnamebuf + 2, flagdesc[i].name, sizeof(fnamebuf) - 2);
954                 if (getboolfield(L, table, fnamebuf, result))
955                         mask |= flagdesc[i].flag;
956         }
957
958         if (flagmask)
959                 *flagmask = mask;
960
961         return flags;
962 }
963
964 void push_flags_string(lua_State *L, FlagDesc *flagdesc, u32 flags, u32 flagmask)
965 {
966         std::string flagstring = writeFlagString(flags, flagdesc, flagmask);
967         lua_pushlstring(L, flagstring.c_str(), flagstring.size());
968 }
969
970 /******************************************************************************/
971 /* Lua Stored data!                                                           */
972 /******************************************************************************/
973
974 /******************************************************************************/
975 void read_groups(lua_State *L, int index,
976                 std::map<std::string, int> &result)
977 {
978         if (!lua_istable(L,index))
979                 return;
980         result.clear();
981         lua_pushnil(L);
982         if(index < 0)
983                 index -= 1;
984         while(lua_next(L, index) != 0){
985                 // key at index -2 and value at index -1
986                 std::string name = luaL_checkstring(L, -2);
987                 int rating = luaL_checkinteger(L, -1);
988                 result[name] = rating;
989                 // removes value, keeps key for next iteration
990                 lua_pop(L, 1);
991         }
992 }
993
994 /******************************************************************************/
995 void push_groups(lua_State *L, const std::map<std::string, int> &groups)
996 {
997         lua_newtable(L);
998         std::map<std::string, int>::const_iterator it;
999         for (it = groups.begin(); it != groups.end(); ++it) {
1000                 lua_pushnumber(L, it->second);
1001                 lua_setfield(L, -2, it->first.c_str());
1002         }
1003 }
1004
1005 /******************************************************************************/
1006 void push_items(lua_State *L, const std::vector<ItemStack> &items)
1007 {
1008         lua_createtable(L, items.size(), 0);
1009         for (u32 i = 0; i != items.size(); i++) {
1010                 LuaItemStack::create(L, items[i]);
1011                 lua_rawseti(L, -2, i + 1);
1012         }
1013 }
1014
1015 /******************************************************************************/
1016 std::vector<ItemStack> read_items(lua_State *L, int index, Server *srv)
1017 {
1018         if(index < 0)
1019                 index = lua_gettop(L) + 1 + index;
1020
1021         std::vector<ItemStack> items;
1022         luaL_checktype(L, index, LUA_TTABLE);
1023         lua_pushnil(L);
1024         while (lua_next(L, index)) {
1025                 s32 key = luaL_checkinteger(L, -2);
1026                 if (key < 1) {
1027                         throw LuaError("Invalid inventory list index");
1028                 }
1029                 if (items.size() < (u32) key) {
1030                         items.resize(key);
1031                 }
1032                 items[key - 1] = read_item(L, -1, srv);
1033                 lua_pop(L, 1);
1034         }
1035         return items;
1036 }
1037
1038 /******************************************************************************/
1039 void luaentity_get(lua_State *L, u16 id)
1040 {
1041         // Get luaentities[i]
1042         lua_getglobal(L, "core");
1043         lua_getfield(L, -1, "luaentities");
1044         luaL_checktype(L, -1, LUA_TTABLE);
1045         lua_pushnumber(L, id);
1046         lua_gettable(L, -2);
1047         lua_remove(L, -2); // Remove luaentities
1048         lua_remove(L, -2); // Remove core
1049 }
1050
1051 /******************************************************************************/
1052 bool read_noiseparams(lua_State *L, int index, NoiseParams *np)
1053 {
1054         if (index < 0)
1055                 index = lua_gettop(L) + 1 + index;
1056
1057         if (!lua_istable(L, index))
1058                 return false;
1059
1060         getfloatfield(L, index, "offset",      np->offset);
1061         getfloatfield(L, index, "scale",       np->scale);
1062         getfloatfield(L, index, "persist",     np->persist);
1063         getfloatfield(L, index, "persistence", np->persist);
1064         getfloatfield(L, index, "lacunarity",  np->lacunarity);
1065         getintfield(L,   index, "seed",        np->seed);
1066         getintfield(L,   index, "octaves",     np->octaves);
1067
1068         u32 flags    = 0;
1069         u32 flagmask = 0;
1070         np->flags = getflagsfield(L, index, "flags", flagdesc_noiseparams,
1071                 &flags, &flagmask) ? flags : NOISE_FLAG_DEFAULTS;
1072
1073         lua_getfield(L, index, "spread");
1074         np->spread  = read_v3f(L, -1);
1075         lua_pop(L, 1);
1076
1077         return true;
1078 }
1079
1080 void push_noiseparams(lua_State *L, NoiseParams *np)
1081 {
1082         lua_newtable(L);
1083         lua_pushnumber(L, np->offset);
1084         lua_setfield(L, -2, "offset");
1085         lua_pushnumber(L, np->scale);
1086         lua_setfield(L, -2, "scale");
1087         lua_pushnumber(L, np->persist);
1088         lua_setfield(L, -2, "persistence");
1089         lua_pushnumber(L, np->lacunarity);
1090         lua_setfield(L, -2, "lacunarity");
1091         lua_pushnumber(L, np->seed);
1092         lua_setfield(L, -2, "seed");
1093         lua_pushnumber(L, np->octaves);
1094         lua_setfield(L, -2, "octaves");
1095
1096         push_flags_string(L, flagdesc_noiseparams, np->flags,
1097                 np->flags);
1098         lua_setfield(L, -2, "flags");
1099
1100         push_v3f(L, np->spread);
1101         lua_setfield(L, -2, "spread");
1102 }
1103
1104 /******************************************************************************/
1105 // Returns depth of json value tree
1106 static int push_json_value_getdepth(const Json::Value &value)
1107 {
1108         if (!value.isArray() && !value.isObject())
1109                 return 1;
1110
1111         int maxdepth = 0;
1112         for (Json::Value::const_iterator it = value.begin();
1113                         it != value.end(); ++it) {
1114                 int elemdepth = push_json_value_getdepth(*it);
1115                 if (elemdepth > maxdepth)
1116                         maxdepth = elemdepth;
1117         }
1118         return maxdepth + 1;
1119 }
1120 // Recursive function to convert JSON --> Lua table
1121 static bool push_json_value_helper(lua_State *L, const Json::Value &value,
1122                 int nullindex)
1123 {
1124         switch(value.type()) {
1125                 case Json::nullValue:
1126                 default:
1127                         lua_pushvalue(L, nullindex);
1128                         break;
1129                 case Json::intValue:
1130                         lua_pushinteger(L, value.asInt());
1131                         break;
1132                 case Json::uintValue:
1133                         lua_pushinteger(L, value.asUInt());
1134                         break;
1135                 case Json::realValue:
1136                         lua_pushnumber(L, value.asDouble());
1137                         break;
1138                 case Json::stringValue:
1139                         {
1140                                 const char *str = value.asCString();
1141                                 lua_pushstring(L, str ? str : "");
1142                         }
1143                         break;
1144                 case Json::booleanValue:
1145                         lua_pushboolean(L, value.asInt());
1146                         break;
1147                 case Json::arrayValue:
1148                         lua_newtable(L);
1149                         for (Json::Value::const_iterator it = value.begin();
1150                                         it != value.end(); ++it) {
1151                                 push_json_value_helper(L, *it, nullindex);
1152                                 lua_rawseti(L, -2, it.index() + 1);
1153                         }
1154                         break;
1155                 case Json::objectValue:
1156                         lua_newtable(L);
1157                         for (Json::Value::const_iterator it = value.begin();
1158                                         it != value.end(); ++it) {
1159                                 const char *str = it.memberName();
1160                                 lua_pushstring(L, str ? str : "");
1161                                 push_json_value_helper(L, *it, nullindex);
1162                                 lua_rawset(L, -3);
1163                         }
1164                         break;
1165         }
1166         return true;
1167 }
1168 // converts JSON --> Lua table; returns false if lua stack limit exceeded
1169 // nullindex: Lua stack index of value to use in place of JSON null
1170 bool push_json_value(lua_State *L, const Json::Value &value, int nullindex)
1171 {
1172         if(nullindex < 0)
1173                 nullindex = lua_gettop(L) + 1 + nullindex;
1174
1175         int depth = push_json_value_getdepth(value);
1176
1177         // The maximum number of Lua stack slots used at each recursion level
1178         // of push_json_value_helper is 2, so make sure there a depth * 2 slots
1179         if (lua_checkstack(L, depth * 2))
1180                 return push_json_value_helper(L, value, nullindex);
1181         else
1182                 return false;
1183 }
1184
1185 // Converts Lua table --> JSON
1186 void read_json_value(lua_State *L, Json::Value &root, int index, u8 recursion)
1187 {
1188         if (recursion > 16) {
1189                 throw SerializationError("Maximum recursion depth exceeded");
1190         }
1191         int type = lua_type(L, index);
1192         if (type == LUA_TBOOLEAN) {
1193                 root = (bool) lua_toboolean(L, index);
1194         } else if (type == LUA_TNUMBER) {
1195                 root = lua_tonumber(L, index);
1196         } else if (type == LUA_TSTRING) {
1197                 size_t len;
1198                 const char *str = lua_tolstring(L, index, &len);
1199                 root = std::string(str, len);
1200         } else if (type == LUA_TTABLE) {
1201                 lua_pushnil(L);
1202                 while (lua_next(L, index)) {
1203                         // Key is at -2 and value is at -1
1204                         Json::Value value;
1205                         read_json_value(L, value, lua_gettop(L), recursion + 1);
1206
1207                         Json::ValueType roottype = root.type();
1208                         int keytype = lua_type(L, -1);
1209                         if (keytype == LUA_TNUMBER) {
1210                                 lua_Number key = lua_tonumber(L, -1);
1211                                 if (roottype != Json::nullValue && roottype != Json::arrayValue) {
1212                                         throw SerializationError("Can't mix array and object values in JSON");
1213                                 } else if (key < 1) {
1214                                         throw SerializationError("Can't use zero-based or negative indexes in JSON");
1215                                 } else if (floor(key) != key) {
1216                                         throw SerializationError("Can't use indexes with a fractional part in JSON");
1217                                 }
1218                                 root[(Json::ArrayIndex) key - 1] = value;
1219                         } else if (keytype == LUA_TSTRING) {
1220                                 if (roottype != Json::nullValue && roottype != Json::objectValue) {
1221                                         throw SerializationError("Can't mix array and object values in JSON");
1222                                 }
1223                                 root[lua_tostring(L, -1)] = value;
1224                         } else {
1225                                 throw SerializationError("Lua key to convert to JSON is not a string or number");
1226                         }
1227                 }
1228         } else if (type == LUA_TNIL) {
1229                 root = Json::nullValue;
1230         } else {
1231                 throw SerializationError("Can only store booleans, numbers, strings, objects, arrays, and null in JSON");
1232         }
1233         lua_pop(L, 1); // Pop value
1234 }
1235