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