3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
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.
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.
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.
19 #include "common/c_content.h"
20 #include "common/c_converter.h"
21 #include "common/c_types.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"
32 #include "serverobject.h"
34 #include "mg_schematic.h"
36 #include "json/json.h"
38 struct EnumString es_TileAnimationType[] =
41 {TAT_VERTICAL_FRAMES, "vertical_frames"},
45 /******************************************************************************/
46 ItemDefinition read_item_definition(lua_State* L,int index,
47 ItemDefinition default_def)
50 index = lua_gettop(L) + 1 + index;
52 // Read the item definition
53 ItemDefinition def = default_def;
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);
62 lua_getfield(L, index, "wield_scale");
63 if(lua_istable(L, -1)){
64 def.wield_scale = check_v3f(L, -1);
68 def.stack_max = getintfield_default(L, index, "stack_max", def.stack_max);
69 if(def.stack_max == 0)
72 lua_getfield(L, index, "on_use");
73 def.usable = lua_isfunction(L, -1);
76 getboolfield(L, index, "liquids_pointable", def.liquids_pointable);
78 warn_if_field_exists(L, index, "tool_digging_properties",
79 "deprecated: use tool_capabilities");
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));
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();
94 lua_getfield(L, index, "groups");
95 read_groups(L, -1, def.groups);
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);
106 def.range = getfloatfield_default(L, index, "range", def.range);
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);
117 /******************************************************************************/
118 void read_object_properties(lua_State *L, int index,
119 ObjectProperties *prop)
122 index = lua_gettop(L) + 1 + index;
123 if(!lua_istable(L, index))
126 prop->hp_max = getintfield_default(L, -1, "hp_max", 10);
128 getboolfield(L, -1, "physical", prop->physical);
129 getboolfield(L, -1, "collide_with_objects", prop->collideWithObjects);
131 getfloatfield(L, -1, "weight", prop->weight);
133 lua_getfield(L, -1, "collisionbox");
134 if(lua_istable(L, -1))
135 prop->collisionbox = read_aabb3f(L, -1, 1.0);
138 getstringfield(L, -1, "visual", prop->visual);
140 getstringfield(L, -1, "mesh", prop->mesh);
142 lua_getfield(L, -1, "visual_size");
143 if(lua_istable(L, -1))
144 prop->visual_size = read_v2f(L, -1);
147 lua_getfield(L, -1, "textures");
148 if(lua_istable(L, -1)){
149 prop->textures.clear();
150 int table = lua_gettop(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));
157 prop->textures.push_back("");
158 // removes value, keeps key for next iteration
164 lua_getfield(L, -1, "colors");
165 if(lua_istable(L, -1)){
166 prop->colors.clear();
167 int table = lua_gettop(L);
169 while(lua_next(L, table) != 0){
170 // key at index -2 and value at index -1
171 if(lua_isstring(L, -1))
172 prop->colors.push_back(readARGB8(L, -1));
174 prop->colors.push_back(video::SColor(255, 255, 255, 255));
175 // removes value, keeps key for next iteration
181 lua_getfield(L, -1, "spritediv");
182 if(lua_istable(L, -1))
183 prop->spritediv = read_v2s16(L, -1);
186 lua_getfield(L, -1, "initial_sprite_basepos");
187 if(lua_istable(L, -1))
188 prop->initial_sprite_basepos = read_v2s16(L, -1);
191 getboolfield(L, -1, "is_visible", prop->is_visible);
192 getboolfield(L, -1, "makes_footstep_sound", prop->makes_footstep_sound);
193 getfloatfield(L, -1, "automatic_rotate", prop->automatic_rotate);
194 if (getfloatfield(L, -1, "stepheight", prop->stepheight))
195 prop->stepheight *= BS;
196 lua_getfield(L, -1, "automatic_face_movement_dir");
197 if (lua_isnumber(L, -1)) {
198 prop->automatic_face_movement_dir = true;
199 prop->automatic_face_movement_dir_offset = luaL_checknumber(L, -1);
200 } else if (lua_isboolean(L, -1)) {
201 prop->automatic_face_movement_dir = lua_toboolean(L, -1);
202 prop->automatic_face_movement_dir_offset = 0.0;
207 /******************************************************************************/
208 TileDef read_tiledef(lua_State *L, int index)
211 index = lua_gettop(L) + 1 + index;
215 // key at index -2 and value at index
216 if(lua_isstring(L, index)){
217 // "default_lava.png"
218 tiledef.name = lua_tostring(L, index);
220 else if(lua_istable(L, index))
222 // {name="default_lava.png", animation={}}
224 getstringfield(L, index, "name", tiledef.name);
225 getstringfield(L, index, "image", tiledef.name); // MaterialSpec compat.
226 tiledef.backface_culling = getboolfield_default(
227 L, index, "backface_culling", true);
229 lua_getfield(L, index, "animation");
230 if(lua_istable(L, -1)){
231 // {type="vertical_frames", aspect_w=16, aspect_h=16, length=2.0}
232 tiledef.animation.type = (TileAnimationType)
233 getenumfield(L, -1, "type", es_TileAnimationType,
235 tiledef.animation.aspect_w =
236 getintfield_default(L, -1, "aspect_w", 16);
237 tiledef.animation.aspect_h =
238 getintfield_default(L, -1, "aspect_h", 16);
239 tiledef.animation.length =
240 getfloatfield_default(L, -1, "length", 1.0);
248 /******************************************************************************/
249 ContentFeatures read_content_features(lua_State *L, int index)
252 index = lua_gettop(L) + 1 + index;
256 /* Cache existence of some callbacks */
257 lua_getfield(L, index, "on_construct");
258 if(!lua_isnil(L, -1)) f.has_on_construct = true;
260 lua_getfield(L, index, "on_destruct");
261 if(!lua_isnil(L, -1)) f.has_on_destruct = true;
263 lua_getfield(L, index, "after_destruct");
264 if(!lua_isnil(L, -1)) f.has_after_destruct = true;
267 lua_getfield(L, index, "on_rightclick");
268 f.rightclickable = lua_isfunction(L, -1);
272 getstringfield(L, index, "name", f.name);
275 lua_getfield(L, index, "groups");
276 read_groups(L, -1, f.groups);
279 /* Visual definition */
281 f.drawtype = (NodeDrawType)getenumfield(L, index, "drawtype",
282 ScriptApiNode::es_DrawType,NDT_NORMAL);
283 getfloatfield(L, index, "visual_scale", f.visual_scale);
285 /* Meshnode model filename */
286 getstringfield(L, index, "mesh", f.mesh);
289 lua_getfield(L, index, "tiles");
290 // If nil, try the deprecated name "tile_images" instead
291 if(lua_isnil(L, -1)){
293 warn_if_field_exists(L, index, "tile_images",
294 "Deprecated; new name is \"tiles\".");
295 lua_getfield(L, index, "tile_images");
297 if(lua_istable(L, -1)){
298 int table = lua_gettop(L);
301 while(lua_next(L, table) != 0){
302 // Read tiledef from value
303 f.tiledef[i] = read_tiledef(L, -1);
304 // removes value, keeps key for next iteration
312 // Copy last value to all remaining textures
314 TileDef lasttile = f.tiledef[i-1];
316 f.tiledef[i] = lasttile;
323 // special_tiles = {}
324 lua_getfield(L, index, "special_tiles");
325 // If nil, try the deprecated name "special_materials" instead
326 if(lua_isnil(L, -1)){
328 warn_if_field_exists(L, index, "special_materials",
329 "Deprecated; new name is \"special_tiles\".");
330 lua_getfield(L, index, "special_materials");
332 if(lua_istable(L, -1)){
333 int table = lua_gettop(L);
336 while(lua_next(L, table) != 0){
337 // Read tiledef from value
338 f.tiledef_special[i] = read_tiledef(L, -1);
339 // removes value, keeps key for next iteration
342 if(i==CF_SPECIAL_COUNT){
350 f.alpha = getintfield_default(L, index, "alpha", 255);
352 bool usealpha = getboolfield_default(L, index,
353 "use_texture_alpha", false);
359 lua_getfield(L, index, "post_effect_color");
360 if(!lua_isnil(L, -1))
361 f.post_effect_color = readARGB8(L, -1);
364 f.param_type = (ContentParamType)getenumfield(L, index, "paramtype",
365 ScriptApiNode::es_ContentParamType, CPT_NONE);
366 f.param_type_2 = (ContentParamType2)getenumfield(L, index, "paramtype2",
367 ScriptApiNode::es_ContentParamType2, CPT2_NONE);
369 // Warn about some deprecated fields
370 warn_if_field_exists(L, index, "wall_mounted",
371 "deprecated: use paramtype2 = 'wallmounted'");
372 warn_if_field_exists(L, index, "light_propagates",
373 "deprecated: determined from paramtype");
374 warn_if_field_exists(L, index, "dug_item",
375 "deprecated: use 'drop' field");
376 warn_if_field_exists(L, index, "extra_dug_item",
377 "deprecated: use 'drop' field");
378 warn_if_field_exists(L, index, "extra_dug_item_rarity",
379 "deprecated: use 'drop' field");
380 warn_if_field_exists(L, index, "metadata_name",
381 "deprecated: use on_add and metadata callbacks");
383 // True for all ground-like things like stone and mud, false for eg. trees
384 getboolfield(L, index, "is_ground_content", f.is_ground_content);
385 f.light_propagates = (f.param_type == CPT_LIGHT);
386 getboolfield(L, index, "sunlight_propagates", f.sunlight_propagates);
387 // This is used for collision detection.
388 // Also for general solidness queries.
389 getboolfield(L, index, "walkable", f.walkable);
390 // Player can point to these
391 getboolfield(L, index, "pointable", f.pointable);
392 // Player can dig these
393 getboolfield(L, index, "diggable", f.diggable);
394 // Player can climb these
395 getboolfield(L, index, "climbable", f.climbable);
396 // Player can build on these
397 getboolfield(L, index, "buildable_to", f.buildable_to);
398 // Whether the node is non-liquid, source liquid or flowing liquid
399 f.liquid_type = (LiquidType)getenumfield(L, index, "liquidtype",
400 ScriptApiNode::es_LiquidType, LIQUID_NONE);
401 // If the content is liquid, this is the flowing version of the liquid.
402 getstringfield(L, index, "liquid_alternative_flowing",
403 f.liquid_alternative_flowing);
404 // If the content is liquid, this is the source version of the liquid.
405 getstringfield(L, index, "liquid_alternative_source",
406 f.liquid_alternative_source);
407 // Viscosity for fluid flow, ranging from 1 to 7, with
408 // 1 giving almost instantaneous propagation and 7 being
409 // the slowest possible
410 f.liquid_viscosity = getintfield_default(L, index,
411 "liquid_viscosity", f.liquid_viscosity);
412 f.liquid_range = getintfield_default(L, index,
413 "liquid_range", f.liquid_range);
414 f.leveled = getintfield_default(L, index, "leveled", f.leveled);
416 getboolfield(L, index, "liquid_renewable", f.liquid_renewable);
417 f.drowning = getintfield_default(L, index,
418 "drowning", f.drowning);
419 // Amount of light the node emits
420 f.light_source = getintfield_default(L, index,
421 "light_source", f.light_source);
422 f.damage_per_second = getintfield_default(L, index,
423 "damage_per_second", f.damage_per_second);
425 lua_getfield(L, index, "node_box");
426 if(lua_istable(L, -1))
427 f.node_box = read_nodebox(L, -1);
430 lua_getfield(L, index, "selection_box");
431 if(lua_istable(L, -1))
432 f.selection_box = read_nodebox(L, -1);
435 lua_getfield(L, index, "collision_box");
436 if(lua_istable(L, -1))
437 f.collision_box = read_nodebox(L, -1);
440 f.waving = getintfield_default(L, index,
443 // Set to true if paramtype used to be 'facedir_simple'
444 getboolfield(L, index, "legacy_facedir_simple", f.legacy_facedir_simple);
445 // Set to true if wall_mounted used to be set to true
446 getboolfield(L, index, "legacy_wallmounted", f.legacy_wallmounted);
449 lua_getfield(L, index, "sounds");
450 if(lua_istable(L, -1)){
451 lua_getfield(L, -1, "footstep");
452 read_soundspec(L, -1, f.sound_footstep);
454 lua_getfield(L, -1, "dig");
455 read_soundspec(L, -1, f.sound_dig);
457 lua_getfield(L, -1, "dug");
458 read_soundspec(L, -1, f.sound_dug);
466 /******************************************************************************/
467 void read_server_sound_params(lua_State *L, int index,
468 ServerSoundParams ¶ms)
471 index = lua_gettop(L) + 1 + index;
473 params = ServerSoundParams();
474 if(lua_istable(L, index)){
475 getfloatfield(L, index, "gain", params.gain);
476 getstringfield(L, index, "to_player", params.to_player);
477 lua_getfield(L, index, "pos");
478 if(!lua_isnil(L, -1)){
479 v3f p = read_v3f(L, -1)*BS;
481 params.type = ServerSoundParams::SSP_POSITIONAL;
484 lua_getfield(L, index, "object");
485 if(!lua_isnil(L, -1)){
486 ObjectRef *ref = ObjectRef::checkobject(L, -1);
487 ServerActiveObject *sao = ObjectRef::getobject(ref);
489 params.object = sao->getId();
490 params.type = ServerSoundParams::SSP_OBJECT;
494 params.max_hear_distance = BS*getfloatfield_default(L, index,
495 "max_hear_distance", params.max_hear_distance/BS);
496 getboolfield(L, index, "loop", params.loop);
500 /******************************************************************************/
501 void read_soundspec(lua_State *L, int index, SimpleSoundSpec &spec)
504 index = lua_gettop(L) + 1 + index;
505 if(lua_isnil(L, index)){
506 } else if(lua_istable(L, index)){
507 getstringfield(L, index, "name", spec.name);
508 getfloatfield(L, index, "gain", spec.gain);
509 } else if(lua_isstring(L, index)){
510 spec.name = lua_tostring(L, index);
514 /******************************************************************************/
515 NodeBox read_nodebox(lua_State *L, int index)
518 if(lua_istable(L, -1)){
519 nodebox.type = (NodeBoxType)getenumfield(L, index, "type",
520 ScriptApiNode::es_NodeBoxType, NODEBOX_REGULAR);
522 lua_getfield(L, index, "fixed");
523 if(lua_istable(L, -1))
524 nodebox.fixed = read_aabb3f_vector(L, -1, BS);
527 lua_getfield(L, index, "wall_top");
528 if(lua_istable(L, -1))
529 nodebox.wall_top = read_aabb3f(L, -1, BS);
532 lua_getfield(L, index, "wall_bottom");
533 if(lua_istable(L, -1))
534 nodebox.wall_bottom = read_aabb3f(L, -1, BS);
537 lua_getfield(L, index, "wall_side");
538 if(lua_istable(L, -1))
539 nodebox.wall_side = read_aabb3f(L, -1, BS);
545 /******************************************************************************/
546 MapNode readnode(lua_State *L, int index, INodeDefManager *ndef)
548 lua_getfield(L, index, "name");
549 if (!lua_isstring(L, -1))
550 throw LuaError("Node name is not set or is not a string!");
551 const char *name = lua_tostring(L, -1);
555 lua_getfield(L, index, "param1");
556 if (!lua_isnil(L, -1))
557 param1 = lua_tonumber(L, -1);
561 lua_getfield(L, index, "param2");
562 if (!lua_isnil(L, -1))
563 param2 = lua_tonumber(L, -1);
566 return MapNode(ndef, name, param1, param2);
569 /******************************************************************************/
570 void pushnode(lua_State *L, const MapNode &n, INodeDefManager *ndef)
573 lua_pushstring(L, ndef->get(n).name.c_str());
574 lua_setfield(L, -2, "name");
575 lua_pushnumber(L, n.getParam1());
576 lua_setfield(L, -2, "param1");
577 lua_pushnumber(L, n.getParam2());
578 lua_setfield(L, -2, "param2");
581 /******************************************************************************/
582 void warn_if_field_exists(lua_State *L, int table,
583 const char *fieldname, const std::string &message)
585 lua_getfield(L, table, fieldname);
586 if(!lua_isnil(L, -1)){
587 //TODO find way to access backtrace fct from here
588 // infostream<<script_get_backtrace(L)<<std::endl;
589 infostream<<"WARNING: field \""<<fieldname<<"\": "
590 <<message<<std::endl;
595 /******************************************************************************/
596 int getenumfield(lua_State *L, int table,
597 const char *fieldname, const EnumString *spec, int default_)
599 int result = default_;
600 string_to_enum(spec, result,
601 getstringfield_default(L, table, fieldname, ""));
605 /******************************************************************************/
606 bool string_to_enum(const EnumString *spec, int &result,
607 const std::string &str)
609 const EnumString *esp = spec;
611 if(str == std::string(esp->str)){
620 /******************************************************************************/
621 ItemStack read_item(lua_State* L, int index,Server* srv)
624 index = lua_gettop(L) + 1 + index;
626 if(lua_isnil(L, index))
630 else if(lua_isuserdata(L, index))
632 // Convert from LuaItemStack
633 LuaItemStack *o = LuaItemStack::checkobject(L, index);
636 else if(lua_isstring(L, index))
638 // Convert from itemstring
639 std::string itemstring = lua_tostring(L, index);
640 IItemDefManager *idef = srv->idef();
644 item.deSerialize(itemstring, idef);
647 catch(SerializationError &e)
649 infostream<<"WARNING: unable to create item from itemstring"
650 <<": "<<itemstring<<std::endl;
654 else if(lua_istable(L, index))
656 // Convert from table
657 IItemDefManager *idef = srv->idef();
658 std::string name = getstringfield_default(L, index, "name", "");
659 int count = getintfield_default(L, index, "count", 1);
660 int wear = getintfield_default(L, index, "wear", 0);
661 std::string metadata = getstringfield_default(L, index, "metadata", "");
662 return ItemStack(name, count, wear, metadata, idef);
666 throw LuaError("Expecting itemstack, itemstring, table or nil");
670 /******************************************************************************/
671 void push_tool_capabilities(lua_State *L,
672 const ToolCapabilities &toolcap)
675 setfloatfield(L, -1, "full_punch_interval", toolcap.full_punch_interval);
676 setintfield(L, -1, "max_drop_level", toolcap.max_drop_level);
677 // Create groupcaps table
680 for(std::map<std::string, ToolGroupCap>::const_iterator
681 i = toolcap.groupcaps.begin(); i != toolcap.groupcaps.end(); i++){
682 // Create groupcap table
684 const std::string &name = i->first;
685 const ToolGroupCap &groupcap = i->second;
686 // Create subtable "times"
688 for(std::map<int, float>::const_iterator
689 i = groupcap.times.begin(); i != groupcap.times.end(); i++){
690 int rating = i->first;
691 float time = i->second;
692 lua_pushinteger(L, rating);
693 lua_pushnumber(L, time);
696 // Set subtable "times"
697 lua_setfield(L, -2, "times");
698 // Set simple parameters
699 setintfield(L, -1, "maxlevel", groupcap.maxlevel);
700 setintfield(L, -1, "uses", groupcap.uses);
701 // Insert groupcap table into groupcaps table
702 lua_setfield(L, -2, name.c_str());
704 // Set groupcaps table
705 lua_setfield(L, -2, "groupcaps");
706 //Create damage_groups table
708 // For each damage group
709 for(std::map<std::string, s16>::const_iterator
710 i = toolcap.damageGroups.begin(); i != toolcap.damageGroups.end(); i++){
711 // Create damage group table
712 lua_pushinteger(L, i->second);
713 lua_setfield(L, -2, i->first.c_str());
715 lua_setfield(L, -2, "damage_groups");
718 /******************************************************************************/
719 void push_inventory_list(lua_State *L, Inventory *inv, const char *name)
721 InventoryList *invlist = inv->getList(name);
726 std::vector<ItemStack> items;
727 for(u32 i=0; i<invlist->getSize(); i++)
728 items.push_back(invlist->getItem(i));
729 push_items(L, items);
732 /******************************************************************************/
733 void read_inventory_list(lua_State *L, int tableindex,
734 Inventory *inv, const char *name, Server* srv, int forcesize)
737 tableindex = lua_gettop(L) + 1 + tableindex;
738 // If nil, delete list
739 if(lua_isnil(L, tableindex)){
740 inv->deleteList(name);
743 // Otherwise set list
744 std::vector<ItemStack> items = read_items(L, tableindex,srv);
745 int listsize = (forcesize != -1) ? forcesize : items.size();
746 InventoryList *invlist = inv->addList(name, listsize);
748 for(std::vector<ItemStack>::const_iterator
749 i = items.begin(); i != items.end(); i++){
750 if(forcesize != -1 && index == forcesize)
752 invlist->changeItem(index, *i);
755 while(forcesize != -1 && index < forcesize){
756 invlist->deleteItem(index);
761 /******************************************************************************/
762 ToolCapabilities read_tool_capabilities(
763 lua_State *L, int table)
765 ToolCapabilities toolcap;
766 getfloatfield(L, table, "full_punch_interval", toolcap.full_punch_interval);
767 getintfield(L, table, "max_drop_level", toolcap.max_drop_level);
768 lua_getfield(L, table, "groupcaps");
769 if(lua_istable(L, -1)){
770 int table_groupcaps = lua_gettop(L);
772 while(lua_next(L, table_groupcaps) != 0){
773 // key at index -2 and value at index -1
774 std::string groupname = luaL_checkstring(L, -2);
775 if(lua_istable(L, -1)){
776 int table_groupcap = lua_gettop(L);
777 // This will be created
778 ToolGroupCap groupcap;
779 // Read simple parameters
780 getintfield(L, table_groupcap, "maxlevel", groupcap.maxlevel);
781 getintfield(L, table_groupcap, "uses", groupcap.uses);
782 // DEPRECATED: maxwear
784 if(getfloatfield(L, table_groupcap, "maxwear", maxwear)){
786 groupcap.uses = 1.0/maxwear;
789 infostream<<script_get_backtrace(L)<<std::endl;
790 infostream<<"WARNING: field \"maxwear\" is deprecated; "
791 <<"should replace with uses=1/maxwear"<<std::endl;
793 // Read "times" table
794 lua_getfield(L, table_groupcap, "times");
795 if(lua_istable(L, -1)){
796 int table_times = lua_gettop(L);
798 while(lua_next(L, table_times) != 0){
799 // key at index -2 and value at index -1
800 int rating = luaL_checkinteger(L, -2);
801 float time = luaL_checknumber(L, -1);
802 groupcap.times[rating] = time;
803 // removes value, keeps key for next iteration
808 // Insert groupcap into toolcap
809 toolcap.groupcaps[groupname] = groupcap;
811 // removes value, keeps key for next iteration
817 lua_getfield(L, table, "damage_groups");
818 if(lua_istable(L, -1)){
819 int table_damage_groups = lua_gettop(L);
821 while(lua_next(L, table_damage_groups) != 0){
822 // key at index -2 and value at index -1
823 std::string groupname = luaL_checkstring(L, -2);
824 u16 value = luaL_checkinteger(L, -1);
825 toolcap.damageGroups[groupname] = value;
826 // removes value, keeps key for next iteration
834 /******************************************************************************/
835 void push_dig_params(lua_State *L,const DigParams ¶ms)
838 setboolfield(L, -1, "diggable", params.diggable);
839 setfloatfield(L, -1, "time", params.time);
840 setintfield(L, -1, "wear", params.wear);
843 /******************************************************************************/
844 void push_hit_params(lua_State *L,const HitParams ¶ms)
847 setintfield(L, -1, "hp", params.hp);
848 setintfield(L, -1, "wear", params.wear);
851 /******************************************************************************/
853 bool getflagsfield(lua_State *L, int table, const char *fieldname,
854 FlagDesc *flagdesc, u32 *flags, u32 *flagmask)
856 lua_getfield(L, table, fieldname);
858 bool success = read_flags(L, -1, flagdesc, flags, flagmask);
865 bool read_flags(lua_State *L, int index, FlagDesc *flagdesc,
866 u32 *flags, u32 *flagmask)
868 if (lua_isstring(L, index)) {
869 std::string flagstr = lua_tostring(L, index);
870 *flags = readFlagString(flagstr, flagdesc, flagmask);
871 } else if (lua_istable(L, index)) {
872 *flags = read_flags_table(L, index, flagdesc, flagmask);
880 u32 read_flags_table(lua_State *L, int table, FlagDesc *flagdesc, u32 *flagmask)
882 u32 flags = 0, mask = 0;
883 char fnamebuf[64] = "no";
885 for (int i = 0; flagdesc[i].name; i++) {
888 if (getboolfield(L, table, flagdesc[i].name, result)) {
889 mask |= flagdesc[i].flag;
891 flags |= flagdesc[i].flag;
894 strlcpy(fnamebuf + 2, flagdesc[i].name, sizeof(fnamebuf) - 2);
895 if (getboolfield(L, table, fnamebuf, result))
896 mask |= flagdesc[i].flag;
905 /******************************************************************************/
906 /* Lua Stored data! */
907 /******************************************************************************/
909 /******************************************************************************/
910 void read_groups(lua_State *L, int index,
911 std::map<std::string, int> &result)
913 if (!lua_istable(L,index))
919 while(lua_next(L, index) != 0){
920 // key at index -2 and value at index -1
921 std::string name = luaL_checkstring(L, -2);
922 int rating = luaL_checkinteger(L, -1);
923 result[name] = rating;
924 // removes value, keeps key for next iteration
929 /******************************************************************************/
930 void push_items(lua_State *L, const std::vector<ItemStack> &items)
932 // Create and fill table
933 lua_createtable(L, items.size(), 0);
934 std::vector<ItemStack>::const_iterator iter = items.begin();
935 for (u32 i = 0; iter != items.end(); iter++) {
936 LuaItemStack::create(L, *iter);
937 lua_rawseti(L, -2, ++i);
941 /******************************************************************************/
942 std::vector<ItemStack> read_items(lua_State *L, int index, Server *srv)
945 index = lua_gettop(L) + 1 + index;
947 std::vector<ItemStack> items;
948 luaL_checktype(L, index, LUA_TTABLE);
950 while (lua_next(L, index)) {
951 s32 key = luaL_checkinteger(L, -2);
953 throw LuaError("Invalid inventory list index");
955 if (items.size() < (u32) key) {
958 items[key - 1] = read_item(L, -1, srv);
964 /******************************************************************************/
965 void luaentity_get(lua_State *L, u16 id)
967 // Get luaentities[i]
968 lua_getglobal(L, "core");
969 lua_getfield(L, -1, "luaentities");
970 luaL_checktype(L, -1, LUA_TTABLE);
971 lua_pushnumber(L, id);
973 lua_remove(L, -2); // Remove luaentities
974 lua_remove(L, -2); // Remove core
977 /******************************************************************************/
978 bool read_noiseparams(lua_State *L, int index, NoiseParams *np)
981 index = lua_gettop(L) + 1 + index;
983 if (!lua_istable(L, index))
986 np->offset = getfloatfield_default(L, index, "offset", 0.0);
987 np->scale = getfloatfield_default(L, index, "scale", 0.0);
988 np->persist = getfloatfield_default(L, index, "persist", 0.0);
989 np->lacunarity = getfloatfield_default(L, index, "lacunarity", 2.0);
990 np->seed = getintfield_default(L, index, "seed", 0);
991 np->octaves = getintfield_default(L, index, "octaves", 0);
993 u32 flags = 0, flagmask = 0;
994 np->flags = getflagsfield(L, index, "flags", flagdesc_noiseparams,
995 &flags, &flagmask) ? flags : NOISE_FLAG_DEFAULTS;
997 lua_getfield(L, index, "spread");
998 np->spread = read_v3f(L, -1);
1004 /******************************************************************************/
1005 // Returns depth of json value tree
1006 static int push_json_value_getdepth(const Json::Value &value)
1008 if (!value.isArray() && !value.isObject())
1012 for (Json::Value::const_iterator it = value.begin();
1013 it != value.end(); ++it) {
1014 int elemdepth = push_json_value_getdepth(*it);
1015 if (elemdepth > maxdepth)
1016 maxdepth = elemdepth;
1018 return maxdepth + 1;
1020 // Recursive function to convert JSON --> Lua table
1021 static bool push_json_value_helper(lua_State *L, const Json::Value &value,
1024 switch(value.type()) {
1025 case Json::nullValue:
1027 lua_pushvalue(L, nullindex);
1029 case Json::intValue:
1030 lua_pushinteger(L, value.asInt());
1032 case Json::uintValue:
1033 lua_pushinteger(L, value.asUInt());
1035 case Json::realValue:
1036 lua_pushnumber(L, value.asDouble());
1038 case Json::stringValue:
1040 const char *str = value.asCString();
1041 lua_pushstring(L, str ? str : "");
1044 case Json::booleanValue:
1045 lua_pushboolean(L, value.asInt());
1047 case Json::arrayValue:
1049 for (Json::Value::const_iterator it = value.begin();
1050 it != value.end(); ++it) {
1051 push_json_value_helper(L, *it, nullindex);
1052 lua_rawseti(L, -2, it.index() + 1);
1055 case Json::objectValue:
1057 for (Json::Value::const_iterator it = value.begin();
1058 it != value.end(); ++it) {
1059 const char *str = it.memberName();
1060 lua_pushstring(L, str ? str : "");
1061 push_json_value_helper(L, *it, nullindex);
1068 // converts JSON --> Lua table; returns false if lua stack limit exceeded
1069 // nullindex: Lua stack index of value to use in place of JSON null
1070 bool push_json_value(lua_State *L, const Json::Value &value, int nullindex)
1073 nullindex = lua_gettop(L) + 1 + nullindex;
1075 int depth = push_json_value_getdepth(value);
1077 // The maximum number of Lua stack slots used at each recursion level
1078 // of push_json_value_helper is 2, so make sure there a depth * 2 slots
1079 if (lua_checkstack(L, depth * 2))
1080 return push_json_value_helper(L, value, nullindex);
1085 // Converts Lua table --> JSON
1086 void read_json_value(lua_State *L, Json::Value &root, int index, u8 recursion)
1088 if (recursion > 16) {
1089 throw SerializationError("Maximum recursion depth exceeded");
1091 int type = lua_type(L, index);
1092 if (type == LUA_TBOOLEAN) {
1093 root = (bool) lua_toboolean(L, index);
1094 } else if (type == LUA_TNUMBER) {
1095 root = lua_tonumber(L, index);
1096 } else if (type == LUA_TSTRING) {
1098 const char *str = lua_tolstring(L, index, &len);
1099 root = std::string(str, len);
1100 } else if (type == LUA_TTABLE) {
1102 while (lua_next(L, index)) {
1103 // Key is at -2 and value is at -1
1105 read_json_value(L, value, lua_gettop(L), recursion + 1);
1107 Json::ValueType roottype = root.type();
1108 int keytype = lua_type(L, -1);
1109 if (keytype == LUA_TNUMBER) {
1110 lua_Number key = lua_tonumber(L, -1);
1111 if (roottype != Json::nullValue && roottype != Json::arrayValue) {
1112 throw SerializationError("Can't mix array and object values in JSON");
1113 } else if (key < 1) {
1114 throw SerializationError("Can't use zero-based or negative indexes in JSON");
1115 } else if (floor(key) != key) {
1116 throw SerializationError("Can't use indexes with a fractional part in JSON");
1118 root[(Json::ArrayIndex) key - 1] = value;
1119 } else if (keytype == LUA_TSTRING) {
1120 if (roottype != Json::nullValue && roottype != Json::objectValue) {
1121 throw SerializationError("Can't mix array and object values in JSON");
1123 root[lua_tostring(L, -1)] = value;
1125 throw SerializationError("Lua key to convert to JSON is not a string or number");
1128 } else if (type == LUA_TNIL) {
1129 root = Json::nullValue;
1131 throw SerializationError("Can only store booleans, numbers, strings, objects, arrays, and null in JSON");
1133 lua_pop(L, 1); // Pop value