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