]> git.lizzy.rs Git - minetest.git/blob - src/script/common/c_content.cpp
Fix relief mapping issues
[minetest.git] / src / script / common / c_content.cpp
1 /*
2 Minetest
3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19 #include "common/c_content.h"
20 #include "common/c_converter.h"
21 #include "common/c_types.h"
22 #include "nodedef.h"
23 #include "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)
262 {
263         if(index < 0)
264                 index = lua_gettop(L) + 1 + index;
265
266         TileDef tiledef;
267
268         // key at index -2 and value at index
269         if(lua_isstring(L, index)){
270                 // "default_lava.png"
271                 tiledef.name = lua_tostring(L, index);
272         }
273         else if(lua_istable(L, index))
274         {
275                 // {name="default_lava.png", animation={}}
276                 tiledef.name = "";
277                 getstringfield(L, index, "name", tiledef.name);
278                 getstringfield(L, index, "image", tiledef.name); // MaterialSpec compat.
279                 tiledef.backface_culling = getboolfield_default(
280                         L, index, "backface_culling", true);
281                 tiledef.tileable_horizontal = getboolfield_default(
282                         L, index, "tileable_horizontal", true);
283                 tiledef.tileable_vertical = getboolfield_default(
284                         L, index, "tileable_vertical", true);
285                 // animation = {}
286                 lua_getfield(L, index, "animation");
287                 if(lua_istable(L, -1)){
288                         // {type="vertical_frames", aspect_w=16, aspect_h=16, length=2.0}
289                         tiledef.animation.type = (TileAnimationType)
290                                 getenumfield(L, -1, "type", es_TileAnimationType,
291                                 TAT_NONE);
292                         tiledef.animation.aspect_w =
293                                 getintfield_default(L, -1, "aspect_w", 16);
294                         tiledef.animation.aspect_h =
295                                 getintfield_default(L, -1, "aspect_h", 16);
296                         tiledef.animation.length =
297                                 getfloatfield_default(L, -1, "length", 1.0);
298                 }
299                 lua_pop(L, 1);
300         }
301
302         return tiledef;
303 }
304
305 /******************************************************************************/
306 ContentFeatures read_content_features(lua_State *L, int index)
307 {
308         if(index < 0)
309                 index = lua_gettop(L) + 1 + index;
310
311         ContentFeatures f;
312
313         /* Cache existence of some callbacks */
314         lua_getfield(L, index, "on_construct");
315         if(!lua_isnil(L, -1)) f.has_on_construct = true;
316         lua_pop(L, 1);
317         lua_getfield(L, index, "on_destruct");
318         if(!lua_isnil(L, -1)) f.has_on_destruct = true;
319         lua_pop(L, 1);
320         lua_getfield(L, index, "after_destruct");
321         if(!lua_isnil(L, -1)) f.has_after_destruct = true;
322         lua_pop(L, 1);
323
324         lua_getfield(L, index, "on_rightclick");
325         f.rightclickable = lua_isfunction(L, -1);
326         lua_pop(L, 1);
327
328         /* Name */
329         getstringfield(L, index, "name", f.name);
330
331         /* Groups */
332         lua_getfield(L, index, "groups");
333         read_groups(L, -1, f.groups);
334         lua_pop(L, 1);
335
336         /* Visual definition */
337
338         f.drawtype = (NodeDrawType)getenumfield(L, index, "drawtype",
339                         ScriptApiNode::es_DrawType,NDT_NORMAL);
340         getfloatfield(L, index, "visual_scale", f.visual_scale);
341
342         /* Meshnode model filename */
343         getstringfield(L, index, "mesh", f.mesh);
344
345         // tiles = {}
346         lua_getfield(L, index, "tiles");
347         // If nil, try the deprecated name "tile_images" instead
348         if(lua_isnil(L, -1)){
349                 lua_pop(L, 1);
350                 warn_if_field_exists(L, index, "tile_images",
351                                 "Deprecated; new name is \"tiles\".");
352                 lua_getfield(L, index, "tile_images");
353         }
354         if(lua_istable(L, -1)){
355                 int table = lua_gettop(L);
356                 lua_pushnil(L);
357                 int i = 0;
358                 while(lua_next(L, table) != 0){
359                         // Read tiledef from value
360                         f.tiledef[i] = read_tiledef(L, -1);
361                         // removes value, keeps key for next iteration
362                         lua_pop(L, 1);
363                         i++;
364                         if(i==6){
365                                 lua_pop(L, 1);
366                                 break;
367                         }
368                 }
369                 // Copy last value to all remaining textures
370                 if(i >= 1){
371                         TileDef lasttile = f.tiledef[i-1];
372                         while(i < 6){
373                                 f.tiledef[i] = lasttile;
374                                 i++;
375                         }
376                 }
377         }
378         lua_pop(L, 1);
379
380         // special_tiles = {}
381         lua_getfield(L, index, "special_tiles");
382         // If nil, try the deprecated name "special_materials" instead
383         if(lua_isnil(L, -1)){
384                 lua_pop(L, 1);
385                 warn_if_field_exists(L, index, "special_materials",
386                                 "Deprecated; new name is \"special_tiles\".");
387                 lua_getfield(L, index, "special_materials");
388         }
389         if(lua_istable(L, -1)){
390                 int table = lua_gettop(L);
391                 lua_pushnil(L);
392                 int i = 0;
393                 while(lua_next(L, table) != 0){
394                         // Read tiledef from value
395                         f.tiledef_special[i] = read_tiledef(L, -1);
396                         // removes value, keeps key for next iteration
397                         lua_pop(L, 1);
398                         i++;
399                         if(i==CF_SPECIAL_COUNT){
400                                 lua_pop(L, 1);
401                                 break;
402                         }
403                 }
404         }
405         lua_pop(L, 1);
406
407         f.alpha = getintfield_default(L, index, "alpha", 255);
408
409         bool usealpha = getboolfield_default(L, index,
410                         "use_texture_alpha", false);
411         if (usealpha)
412                 f.alpha = 0;
413
414         /* Other stuff */
415
416         lua_getfield(L, index, "post_effect_color");
417         read_color(L, -1, &f.post_effect_color);
418         lua_pop(L, 1);
419
420         f.param_type = (ContentParamType)getenumfield(L, index, "paramtype",
421                         ScriptApiNode::es_ContentParamType, CPT_NONE);
422         f.param_type_2 = (ContentParamType2)getenumfield(L, index, "paramtype2",
423                         ScriptApiNode::es_ContentParamType2, CPT2_NONE);
424
425         // Warn about some deprecated fields
426         warn_if_field_exists(L, index, "wall_mounted",
427                         "deprecated: use paramtype2 = 'wallmounted'");
428         warn_if_field_exists(L, index, "light_propagates",
429                         "deprecated: determined from paramtype");
430         warn_if_field_exists(L, index, "dug_item",
431                         "deprecated: use 'drop' field");
432         warn_if_field_exists(L, index, "extra_dug_item",
433                         "deprecated: use 'drop' field");
434         warn_if_field_exists(L, index, "extra_dug_item_rarity",
435                         "deprecated: use 'drop' field");
436         warn_if_field_exists(L, index, "metadata_name",
437                         "deprecated: use on_add and metadata callbacks");
438
439         // True for all ground-like things like stone and mud, false for eg. trees
440         getboolfield(L, index, "is_ground_content", f.is_ground_content);
441         f.light_propagates = (f.param_type == CPT_LIGHT);
442         getboolfield(L, index, "sunlight_propagates", f.sunlight_propagates);
443         // This is used for collision detection.
444         // Also for general solidness queries.
445         getboolfield(L, index, "walkable", f.walkable);
446         // Player can point to these
447         getboolfield(L, index, "pointable", f.pointable);
448         // Player can dig these
449         getboolfield(L, index, "diggable", f.diggable);
450         // Player can climb these
451         getboolfield(L, index, "climbable", f.climbable);
452         // Player can build on these
453         getboolfield(L, index, "buildable_to", f.buildable_to);
454         // Whether the node is non-liquid, source liquid or flowing liquid
455         f.liquid_type = (LiquidType)getenumfield(L, index, "liquidtype",
456                         ScriptApiNode::es_LiquidType, LIQUID_NONE);
457         // If the content is liquid, this is the flowing version of the liquid.
458         getstringfield(L, index, "liquid_alternative_flowing",
459                         f.liquid_alternative_flowing);
460         // If the content is liquid, this is the source version of the liquid.
461         getstringfield(L, index, "liquid_alternative_source",
462                         f.liquid_alternative_source);
463         // Viscosity for fluid flow, ranging from 1 to 7, with
464         // 1 giving almost instantaneous propagation and 7 being
465         // the slowest possible
466         f.liquid_viscosity = getintfield_default(L, index,
467                         "liquid_viscosity", f.liquid_viscosity);
468         f.liquid_range = getintfield_default(L, index,
469                         "liquid_range", f.liquid_range);
470         f.leveled = getintfield_default(L, index, "leveled", f.leveled);
471
472         getboolfield(L, index, "liquid_renewable", f.liquid_renewable);
473         f.drowning = getintfield_default(L, index,
474                         "drowning", f.drowning);
475         // Amount of light the node emits
476         f.light_source = getintfield_default(L, index,
477                         "light_source", f.light_source);
478         f.damage_per_second = getintfield_default(L, index,
479                         "damage_per_second", f.damage_per_second);
480
481         lua_getfield(L, index, "node_box");
482         if(lua_istable(L, -1))
483                 f.node_box = read_nodebox(L, -1);
484         lua_pop(L, 1);
485
486         lua_getfield(L, index, "selection_box");
487         if(lua_istable(L, -1))
488                 f.selection_box = read_nodebox(L, -1);
489         lua_pop(L, 1);
490
491         lua_getfield(L, index, "collision_box");
492         if(lua_istable(L, -1))
493                 f.collision_box = read_nodebox(L, -1);
494         lua_pop(L, 1);
495
496         f.waving = getintfield_default(L, index,
497                         "waving", f.waving);
498
499         // Set to true if paramtype used to be 'facedir_simple'
500         getboolfield(L, index, "legacy_facedir_simple", f.legacy_facedir_simple);
501         // Set to true if wall_mounted used to be set to true
502         getboolfield(L, index, "legacy_wallmounted", f.legacy_wallmounted);
503
504         // Sound table
505         lua_getfield(L, index, "sounds");
506         if(lua_istable(L, -1)){
507                 lua_getfield(L, -1, "footstep");
508                 read_soundspec(L, -1, f.sound_footstep);
509                 lua_pop(L, 1);
510                 lua_getfield(L, -1, "dig");
511                 read_soundspec(L, -1, f.sound_dig);
512                 lua_pop(L, 1);
513                 lua_getfield(L, -1, "dug");
514                 read_soundspec(L, -1, f.sound_dug);
515                 lua_pop(L, 1);
516         }
517         lua_pop(L, 1);
518
519         return f;
520 }
521
522 /******************************************************************************/
523 void read_server_sound_params(lua_State *L, int index,
524                 ServerSoundParams &params)
525 {
526         if(index < 0)
527                 index = lua_gettop(L) + 1 + index;
528         // Clear
529         params = ServerSoundParams();
530         if(lua_istable(L, index)){
531                 getfloatfield(L, index, "gain", params.gain);
532                 getstringfield(L, index, "to_player", params.to_player);
533                 lua_getfield(L, index, "pos");
534                 if(!lua_isnil(L, -1)){
535                         v3f p = read_v3f(L, -1)*BS;
536                         params.pos = p;
537                         params.type = ServerSoundParams::SSP_POSITIONAL;
538                 }
539                 lua_pop(L, 1);
540                 lua_getfield(L, index, "object");
541                 if(!lua_isnil(L, -1)){
542                         ObjectRef *ref = ObjectRef::checkobject(L, -1);
543                         ServerActiveObject *sao = ObjectRef::getobject(ref);
544                         if(sao){
545                                 params.object = sao->getId();
546                                 params.type = ServerSoundParams::SSP_OBJECT;
547                         }
548                 }
549                 lua_pop(L, 1);
550                 params.max_hear_distance = BS*getfloatfield_default(L, index,
551                                 "max_hear_distance", params.max_hear_distance/BS);
552                 getboolfield(L, index, "loop", params.loop);
553         }
554 }
555
556 /******************************************************************************/
557 void read_soundspec(lua_State *L, int index, SimpleSoundSpec &spec)
558 {
559         if(index < 0)
560                 index = lua_gettop(L) + 1 + index;
561         if(lua_isnil(L, index)){
562         } else if(lua_istable(L, index)){
563                 getstringfield(L, index, "name", spec.name);
564                 getfloatfield(L, index, "gain", spec.gain);
565         } else if(lua_isstring(L, index)){
566                 spec.name = lua_tostring(L, index);
567         }
568 }
569
570 /******************************************************************************/
571 NodeBox read_nodebox(lua_State *L, int index)
572 {
573         NodeBox nodebox;
574         if(lua_istable(L, -1)){
575                 nodebox.type = (NodeBoxType)getenumfield(L, index, "type",
576                                 ScriptApiNode::es_NodeBoxType, NODEBOX_REGULAR);
577
578                 lua_getfield(L, index, "fixed");
579                 if(lua_istable(L, -1))
580                         nodebox.fixed = read_aabb3f_vector(L, -1, BS);
581                 lua_pop(L, 1);
582
583                 lua_getfield(L, index, "wall_top");
584                 if(lua_istable(L, -1))
585                         nodebox.wall_top = read_aabb3f(L, -1, BS);
586                 lua_pop(L, 1);
587
588                 lua_getfield(L, index, "wall_bottom");
589                 if(lua_istable(L, -1))
590                         nodebox.wall_bottom = read_aabb3f(L, -1, BS);
591                 lua_pop(L, 1);
592
593                 lua_getfield(L, index, "wall_side");
594                 if(lua_istable(L, -1))
595                         nodebox.wall_side = read_aabb3f(L, -1, BS);
596                 lua_pop(L, 1);
597         }
598         return nodebox;
599 }
600
601 /******************************************************************************/
602 MapNode readnode(lua_State *L, int index, INodeDefManager *ndef)
603 {
604         lua_getfield(L, index, "name");
605         if (!lua_isstring(L, -1))
606                 throw LuaError("Node name is not set or is not a string!");
607         const char *name = lua_tostring(L, -1);
608         lua_pop(L, 1);
609
610         u8 param1 = 0;
611         lua_getfield(L, index, "param1");
612         if (!lua_isnil(L, -1))
613                 param1 = lua_tonumber(L, -1);
614         lua_pop(L, 1);
615
616         u8 param2 = 0;
617         lua_getfield(L, index, "param2");
618         if (!lua_isnil(L, -1))
619                 param2 = lua_tonumber(L, -1);
620         lua_pop(L, 1);
621
622         return MapNode(ndef, name, param1, param2);
623 }
624
625 /******************************************************************************/
626 void pushnode(lua_State *L, const MapNode &n, INodeDefManager *ndef)
627 {
628         lua_newtable(L);
629         lua_pushstring(L, ndef->get(n).name.c_str());
630         lua_setfield(L, -2, "name");
631         lua_pushnumber(L, n.getParam1());
632         lua_setfield(L, -2, "param1");
633         lua_pushnumber(L, n.getParam2());
634         lua_setfield(L, -2, "param2");
635 }
636
637 /******************************************************************************/
638 void warn_if_field_exists(lua_State *L, int table,
639                 const char *fieldname, const std::string &message)
640 {
641         lua_getfield(L, table, fieldname);
642         if(!lua_isnil(L, -1)){
643 //TODO find way to access backtrace fct from here
644                 //              infostream<<script_get_backtrace(L)<<std::endl;
645                 infostream<<"WARNING: field \""<<fieldname<<"\": "
646                                 <<message<<std::endl;
647         }
648         lua_pop(L, 1);
649 }
650
651 /******************************************************************************/
652 int getenumfield(lua_State *L, int table,
653                 const char *fieldname, const EnumString *spec, int default_)
654 {
655         int result = default_;
656         string_to_enum(spec, result,
657                         getstringfield_default(L, table, fieldname, ""));
658         return result;
659 }
660
661 /******************************************************************************/
662 bool string_to_enum(const EnumString *spec, int &result,
663                 const std::string &str)
664 {
665         const EnumString *esp = spec;
666         while(esp->str){
667                 if(str == std::string(esp->str)){
668                         result = esp->num;
669                         return true;
670                 }
671                 esp++;
672         }
673         return false;
674 }
675
676 /******************************************************************************/
677 ItemStack read_item(lua_State* L, int index,Server* srv)
678 {
679         if(index < 0)
680                 index = lua_gettop(L) + 1 + index;
681
682         if(lua_isnil(L, index))
683         {
684                 return ItemStack();
685         }
686         else if(lua_isuserdata(L, index))
687         {
688                 // Convert from LuaItemStack
689                 LuaItemStack *o = LuaItemStack::checkobject(L, index);
690                 return o->getItem();
691         }
692         else if(lua_isstring(L, index))
693         {
694                 // Convert from itemstring
695                 std::string itemstring = lua_tostring(L, index);
696                 IItemDefManager *idef = srv->idef();
697                 try
698                 {
699                         ItemStack item;
700                         item.deSerialize(itemstring, idef);
701                         return item;
702                 }
703                 catch(SerializationError &e)
704                 {
705                         infostream<<"WARNING: unable to create item from itemstring"
706                                         <<": "<<itemstring<<std::endl;
707                         return ItemStack();
708                 }
709         }
710         else if(lua_istable(L, index))
711         {
712                 // Convert from table
713                 IItemDefManager *idef = srv->idef();
714                 std::string name = getstringfield_default(L, index, "name", "");
715                 int count = getintfield_default(L, index, "count", 1);
716                 int wear = getintfield_default(L, index, "wear", 0);
717                 std::string metadata = getstringfield_default(L, index, "metadata", "");
718                 return ItemStack(name, count, wear, metadata, idef);
719         }
720         else
721         {
722                 throw LuaError("Expecting itemstack, itemstring, table or nil");
723         }
724 }
725
726 /******************************************************************************/
727 void push_tool_capabilities(lua_State *L,
728                 const ToolCapabilities &toolcap)
729 {
730         lua_newtable(L);
731         setfloatfield(L, -1, "full_punch_interval", toolcap.full_punch_interval);
732                 setintfield(L, -1, "max_drop_level", toolcap.max_drop_level);
733                 // Create groupcaps table
734                 lua_newtable(L);
735                 // For each groupcap
736                 for(std::map<std::string, ToolGroupCap>::const_iterator
737                                 i = toolcap.groupcaps.begin(); i != toolcap.groupcaps.end(); i++){
738                         // Create groupcap table
739                         lua_newtable(L);
740                         const std::string &name = i->first;
741                         const ToolGroupCap &groupcap = i->second;
742                         // Create subtable "times"
743                         lua_newtable(L);
744                         for(std::map<int, float>::const_iterator
745                                         i = groupcap.times.begin(); i != groupcap.times.end(); i++){
746                                 int rating = i->first;
747                                 float time = i->second;
748                                 lua_pushinteger(L, rating);
749                                 lua_pushnumber(L, time);
750                                 lua_settable(L, -3);
751                         }
752                         // Set subtable "times"
753                         lua_setfield(L, -2, "times");
754                         // Set simple parameters
755                         setintfield(L, -1, "maxlevel", groupcap.maxlevel);
756                         setintfield(L, -1, "uses", groupcap.uses);
757                         // Insert groupcap table into groupcaps table
758                         lua_setfield(L, -2, name.c_str());
759                 }
760                 // Set groupcaps table
761                 lua_setfield(L, -2, "groupcaps");
762                 //Create damage_groups table
763                 lua_newtable(L);
764                 // For each damage group
765                 for(std::map<std::string, s16>::const_iterator
766                                 i = toolcap.damageGroups.begin(); i != toolcap.damageGroups.end(); i++){
767                         // Create damage group table
768                         lua_pushinteger(L, i->second);
769                         lua_setfield(L, -2, i->first.c_str());
770                 }
771                 lua_setfield(L, -2, "damage_groups");
772 }
773
774 /******************************************************************************/
775 void push_inventory_list(lua_State *L, Inventory *inv, const char *name)
776 {
777         InventoryList *invlist = inv->getList(name);
778         if(invlist == NULL){
779                 lua_pushnil(L);
780                 return;
781         }
782         std::vector<ItemStack> items;
783         for(u32 i=0; i<invlist->getSize(); i++)
784                 items.push_back(invlist->getItem(i));
785         push_items(L, items);
786 }
787
788 /******************************************************************************/
789 void read_inventory_list(lua_State *L, int tableindex,
790                 Inventory *inv, const char *name, Server* srv, int forcesize)
791 {
792         if(tableindex < 0)
793                 tableindex = lua_gettop(L) + 1 + tableindex;
794         // If nil, delete list
795         if(lua_isnil(L, tableindex)){
796                 inv->deleteList(name);
797                 return;
798         }
799         // Otherwise set list
800         std::vector<ItemStack> items = read_items(L, tableindex,srv);
801         int listsize = (forcesize != -1) ? forcesize : items.size();
802         InventoryList *invlist = inv->addList(name, listsize);
803         int index = 0;
804         for(std::vector<ItemStack>::const_iterator
805                         i = items.begin(); i != items.end(); i++){
806                 if(forcesize != -1 && index == forcesize)
807                         break;
808                 invlist->changeItem(index, *i);
809                 index++;
810         }
811         while(forcesize != -1 && index < forcesize){
812                 invlist->deleteItem(index);
813                 index++;
814         }
815 }
816
817 /******************************************************************************/
818 ToolCapabilities read_tool_capabilities(
819                 lua_State *L, int table)
820 {
821         ToolCapabilities toolcap;
822         getfloatfield(L, table, "full_punch_interval", toolcap.full_punch_interval);
823         getintfield(L, table, "max_drop_level", toolcap.max_drop_level);
824         lua_getfield(L, table, "groupcaps");
825         if(lua_istable(L, -1)){
826                 int table_groupcaps = lua_gettop(L);
827                 lua_pushnil(L);
828                 while(lua_next(L, table_groupcaps) != 0){
829                         // key at index -2 and value at index -1
830                         std::string groupname = luaL_checkstring(L, -2);
831                         if(lua_istable(L, -1)){
832                                 int table_groupcap = lua_gettop(L);
833                                 // This will be created
834                                 ToolGroupCap groupcap;
835                                 // Read simple parameters
836                                 getintfield(L, table_groupcap, "maxlevel", groupcap.maxlevel);
837                                 getintfield(L, table_groupcap, "uses", groupcap.uses);
838                                 // DEPRECATED: maxwear
839                                 float maxwear = 0;
840                                 if(getfloatfield(L, table_groupcap, "maxwear", maxwear)){
841                                         if(maxwear != 0)
842                                                 groupcap.uses = 1.0/maxwear;
843                                         else
844                                                 groupcap.uses = 0;
845                                         infostream<<script_get_backtrace(L)<<std::endl;
846                                         infostream<<"WARNING: field \"maxwear\" is deprecated; "
847                                                         <<"should replace with uses=1/maxwear"<<std::endl;
848                                 }
849                                 // Read "times" table
850                                 lua_getfield(L, table_groupcap, "times");
851                                 if(lua_istable(L, -1)){
852                                         int table_times = lua_gettop(L);
853                                         lua_pushnil(L);
854                                         while(lua_next(L, table_times) != 0){
855                                                 // key at index -2 and value at index -1
856                                                 int rating = luaL_checkinteger(L, -2);
857                                                 float time = luaL_checknumber(L, -1);
858                                                 groupcap.times[rating] = time;
859                                                 // removes value, keeps key for next iteration
860                                                 lua_pop(L, 1);
861                                         }
862                                 }
863                                 lua_pop(L, 1);
864                                 // Insert groupcap into toolcap
865                                 toolcap.groupcaps[groupname] = groupcap;
866                         }
867                         // removes value, keeps key for next iteration
868                         lua_pop(L, 1);
869                 }
870         }
871         lua_pop(L, 1);
872
873         lua_getfield(L, table, "damage_groups");
874         if(lua_istable(L, -1)){
875                 int table_damage_groups = lua_gettop(L);
876                 lua_pushnil(L);
877                 while(lua_next(L, table_damage_groups) != 0){
878                         // key at index -2 and value at index -1
879                         std::string groupname = luaL_checkstring(L, -2);
880                         u16 value = luaL_checkinteger(L, -1);
881                         toolcap.damageGroups[groupname] = value;
882                         // removes value, keeps key for next iteration
883                         lua_pop(L, 1);
884                 }
885         }
886         lua_pop(L, 1);
887         return toolcap;
888 }
889
890 /******************************************************************************/
891 void push_dig_params(lua_State *L,const DigParams &params)
892 {
893         lua_newtable(L);
894         setboolfield(L, -1, "diggable", params.diggable);
895         setfloatfield(L, -1, "time", params.time);
896         setintfield(L, -1, "wear", params.wear);
897 }
898
899 /******************************************************************************/
900 void push_hit_params(lua_State *L,const HitParams &params)
901 {
902         lua_newtable(L);
903         setintfield(L, -1, "hp", params.hp);
904         setintfield(L, -1, "wear", params.wear);
905 }
906
907 /******************************************************************************/
908
909 bool getflagsfield(lua_State *L, int table, const char *fieldname,
910         FlagDesc *flagdesc, u32 *flags, u32 *flagmask)
911 {
912         lua_getfield(L, table, fieldname);
913
914         bool success = read_flags(L, -1, flagdesc, flags, flagmask);
915
916         lua_pop(L, 1);
917
918         return success;
919 }
920
921 bool read_flags(lua_State *L, int index, FlagDesc *flagdesc,
922         u32 *flags, u32 *flagmask)
923 {
924         if (lua_isstring(L, index)) {
925                 std::string flagstr = lua_tostring(L, index);
926                 *flags = readFlagString(flagstr, flagdesc, flagmask);
927         } else if (lua_istable(L, index)) {
928                 *flags = read_flags_table(L, index, flagdesc, flagmask);
929         } else {
930                 return false;
931         }
932
933         return true;
934 }
935
936 u32 read_flags_table(lua_State *L, int table, FlagDesc *flagdesc, u32 *flagmask)
937 {
938         u32 flags = 0, mask = 0;
939         char fnamebuf[64] = "no";
940
941         for (int i = 0; flagdesc[i].name; i++) {
942                 bool result;
943
944                 if (getboolfield(L, table, flagdesc[i].name, result)) {
945                         mask |= flagdesc[i].flag;
946                         if (result)
947                                 flags |= flagdesc[i].flag;
948                 }
949
950                 strlcpy(fnamebuf + 2, flagdesc[i].name, sizeof(fnamebuf) - 2);
951                 if (getboolfield(L, table, fnamebuf, result))
952                         mask |= flagdesc[i].flag;
953         }
954
955         if (flagmask)
956                 *flagmask = mask;
957
958         return flags;
959 }
960
961 void push_flags_string(lua_State *L, FlagDesc *flagdesc, u32 flags, u32 flagmask)
962 {
963         std::string flagstring = writeFlagString(flags, flagdesc, flagmask);
964         lua_pushlstring(L, flagstring.c_str(), flagstring.size());
965 }
966
967 /******************************************************************************/
968 /* Lua Stored data!                                                           */
969 /******************************************************************************/
970
971 /******************************************************************************/
972 void read_groups(lua_State *L, int index,
973                 std::map<std::string, int> &result)
974 {
975         if (!lua_istable(L,index))
976                 return;
977         result.clear();
978         lua_pushnil(L);
979         if(index < 0)
980                 index -= 1;
981         while(lua_next(L, index) != 0){
982                 // key at index -2 and value at index -1
983                 std::string name = luaL_checkstring(L, -2);
984                 int rating = luaL_checkinteger(L, -1);
985                 result[name] = rating;
986                 // removes value, keeps key for next iteration
987                 lua_pop(L, 1);
988         }
989 }
990
991 /******************************************************************************/
992 void push_groups(lua_State *L, const std::map<std::string, int> &groups)
993 {
994         lua_newtable(L);
995         std::map<std::string, int>::const_iterator it;
996         for (it = groups.begin(); it != groups.end(); ++it) {
997                 lua_pushnumber(L, it->second);
998                 lua_setfield(L, -2, it->first.c_str());
999         }
1000 }
1001
1002 /******************************************************************************/
1003 void push_items(lua_State *L, const std::vector<ItemStack> &items)
1004 {
1005         lua_createtable(L, items.size(), 0);
1006         for (u32 i = 0; i != items.size(); i++) {
1007                 LuaItemStack::create(L, items[i]);
1008                 lua_rawseti(L, -2, i + 1);
1009         }
1010 }
1011
1012 /******************************************************************************/
1013 std::vector<ItemStack> read_items(lua_State *L, int index, Server *srv)
1014 {
1015         if(index < 0)
1016                 index = lua_gettop(L) + 1 + index;
1017
1018         std::vector<ItemStack> items;
1019         luaL_checktype(L, index, LUA_TTABLE);
1020         lua_pushnil(L);
1021         while (lua_next(L, index)) {
1022                 s32 key = luaL_checkinteger(L, -2);
1023                 if (key < 1) {
1024                         throw LuaError("Invalid inventory list index");
1025                 }
1026                 if (items.size() < (u32) key) {
1027                         items.resize(key);
1028                 }
1029                 items[key - 1] = read_item(L, -1, srv);
1030                 lua_pop(L, 1);
1031         }
1032         return items;
1033 }
1034
1035 /******************************************************************************/
1036 void luaentity_get(lua_State *L, u16 id)
1037 {
1038         // Get luaentities[i]
1039         lua_getglobal(L, "core");
1040         lua_getfield(L, -1, "luaentities");
1041         luaL_checktype(L, -1, LUA_TTABLE);
1042         lua_pushnumber(L, id);
1043         lua_gettable(L, -2);
1044         lua_remove(L, -2); // Remove luaentities
1045         lua_remove(L, -2); // Remove core
1046 }
1047
1048 /******************************************************************************/
1049 bool read_noiseparams(lua_State *L, int index, NoiseParams *np)
1050 {
1051         if (index < 0)
1052                 index = lua_gettop(L) + 1 + index;
1053
1054         if (!lua_istable(L, index))
1055                 return false;
1056
1057         getfloatfield(L, index, "offset",      np->offset);
1058         getfloatfield(L, index, "scale",       np->scale);
1059         getfloatfield(L, index, "persist",     np->persist);
1060         getfloatfield(L, index, "persistence", np->persist);
1061         getfloatfield(L, index, "lacunarity",  np->lacunarity);
1062         getintfield(L,   index, "seed",        np->seed);
1063         getintfield(L,   index, "octaves",     np->octaves);
1064
1065         u32 flags    = 0;
1066         u32 flagmask = 0;
1067         np->flags = getflagsfield(L, index, "flags", flagdesc_noiseparams,
1068                 &flags, &flagmask) ? flags : NOISE_FLAG_DEFAULTS;
1069
1070         lua_getfield(L, index, "spread");
1071         np->spread  = read_v3f(L, -1);
1072         lua_pop(L, 1);
1073
1074         return true;
1075 }
1076
1077 void push_noiseparams(lua_State *L, NoiseParams *np)
1078 {
1079         lua_newtable(L);
1080         lua_pushnumber(L, np->offset);
1081         lua_setfield(L, -2, "offset");
1082         lua_pushnumber(L, np->scale);
1083         lua_setfield(L, -2, "scale");
1084         lua_pushnumber(L, np->persist);
1085         lua_setfield(L, -2, "persistence");
1086         lua_pushnumber(L, np->lacunarity);
1087         lua_setfield(L, -2, "lacunarity");
1088         lua_pushnumber(L, np->seed);
1089         lua_setfield(L, -2, "seed");
1090         lua_pushnumber(L, np->octaves);
1091         lua_setfield(L, -2, "octaves");
1092
1093         push_flags_string(L, flagdesc_noiseparams, np->flags,
1094                 np->flags);
1095         lua_setfield(L, -2, "flags");
1096
1097         push_v3f(L, np->spread);
1098         lua_setfield(L, -2, "spread");
1099 }
1100
1101 /******************************************************************************/
1102 // Returns depth of json value tree
1103 static int push_json_value_getdepth(const Json::Value &value)
1104 {
1105         if (!value.isArray() && !value.isObject())
1106                 return 1;
1107
1108         int maxdepth = 0;
1109         for (Json::Value::const_iterator it = value.begin();
1110                         it != value.end(); ++it) {
1111                 int elemdepth = push_json_value_getdepth(*it);
1112                 if (elemdepth > maxdepth)
1113                         maxdepth = elemdepth;
1114         }
1115         return maxdepth + 1;
1116 }
1117 // Recursive function to convert JSON --> Lua table
1118 static bool push_json_value_helper(lua_State *L, const Json::Value &value,
1119                 int nullindex)
1120 {
1121         switch(value.type()) {
1122                 case Json::nullValue:
1123                 default:
1124                         lua_pushvalue(L, nullindex);
1125                         break;
1126                 case Json::intValue:
1127                         lua_pushinteger(L, value.asInt());
1128                         break;
1129                 case Json::uintValue:
1130                         lua_pushinteger(L, value.asUInt());
1131                         break;
1132                 case Json::realValue:
1133                         lua_pushnumber(L, value.asDouble());
1134                         break;
1135                 case Json::stringValue:
1136                         {
1137                                 const char *str = value.asCString();
1138                                 lua_pushstring(L, str ? str : "");
1139                         }
1140                         break;
1141                 case Json::booleanValue:
1142                         lua_pushboolean(L, value.asInt());
1143                         break;
1144                 case Json::arrayValue:
1145                         lua_newtable(L);
1146                         for (Json::Value::const_iterator it = value.begin();
1147                                         it != value.end(); ++it) {
1148                                 push_json_value_helper(L, *it, nullindex);
1149                                 lua_rawseti(L, -2, it.index() + 1);
1150                         }
1151                         break;
1152                 case Json::objectValue:
1153                         lua_newtable(L);
1154                         for (Json::Value::const_iterator it = value.begin();
1155                                         it != value.end(); ++it) {
1156                                 const char *str = it.memberName();
1157                                 lua_pushstring(L, str ? str : "");
1158                                 push_json_value_helper(L, *it, nullindex);
1159                                 lua_rawset(L, -3);
1160                         }
1161                         break;
1162         }
1163         return true;
1164 }
1165 // converts JSON --> Lua table; returns false if lua stack limit exceeded
1166 // nullindex: Lua stack index of value to use in place of JSON null
1167 bool push_json_value(lua_State *L, const Json::Value &value, int nullindex)
1168 {
1169         if(nullindex < 0)
1170                 nullindex = lua_gettop(L) + 1 + nullindex;
1171
1172         int depth = push_json_value_getdepth(value);
1173
1174         // The maximum number of Lua stack slots used at each recursion level
1175         // of push_json_value_helper is 2, so make sure there a depth * 2 slots
1176         if (lua_checkstack(L, depth * 2))
1177                 return push_json_value_helper(L, value, nullindex);
1178         else
1179                 return false;
1180 }
1181
1182 // Converts Lua table --> JSON
1183 void read_json_value(lua_State *L, Json::Value &root, int index, u8 recursion)
1184 {
1185         if (recursion > 16) {
1186                 throw SerializationError("Maximum recursion depth exceeded");
1187         }
1188         int type = lua_type(L, index);
1189         if (type == LUA_TBOOLEAN) {
1190                 root = (bool) lua_toboolean(L, index);
1191         } else if (type == LUA_TNUMBER) {
1192                 root = lua_tonumber(L, index);
1193         } else if (type == LUA_TSTRING) {
1194                 size_t len;
1195                 const char *str = lua_tolstring(L, index, &len);
1196                 root = std::string(str, len);
1197         } else if (type == LUA_TTABLE) {
1198                 lua_pushnil(L);
1199                 while (lua_next(L, index)) {
1200                         // Key is at -2 and value is at -1
1201                         Json::Value value;
1202                         read_json_value(L, value, lua_gettop(L), recursion + 1);
1203
1204                         Json::ValueType roottype = root.type();
1205                         int keytype = lua_type(L, -1);
1206                         if (keytype == LUA_TNUMBER) {
1207                                 lua_Number key = lua_tonumber(L, -1);
1208                                 if (roottype != Json::nullValue && roottype != Json::arrayValue) {
1209                                         throw SerializationError("Can't mix array and object values in JSON");
1210                                 } else if (key < 1) {
1211                                         throw SerializationError("Can't use zero-based or negative indexes in JSON");
1212                                 } else if (floor(key) != key) {
1213                                         throw SerializationError("Can't use indexes with a fractional part in JSON");
1214                                 }
1215                                 root[(Json::ArrayIndex) key - 1] = value;
1216                         } else if (keytype == LUA_TSTRING) {
1217                                 if (roottype != Json::nullValue && roottype != Json::objectValue) {
1218                                         throw SerializationError("Can't mix array and object values in JSON");
1219                                 }
1220                                 root[lua_tostring(L, -1)] = value;
1221                         } else {
1222                                 throw SerializationError("Lua key to convert to JSON is not a string or number");
1223                         }
1224                 }
1225         } else if (type == LUA_TNIL) {
1226                 root = Json::nullValue;
1227         } else {
1228                 throw SerializationError("Can only store booleans, numbers, strings, objects, arrays, and null in JSON");
1229         }
1230         lua_pop(L, 1); // Pop value
1231 }
1232