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.
20 #include "scriptapi.h"
25 #include "util/pointedthing.h"
26 #include "scriptapi_item.h"
27 #include "scriptapi_types.h"
28 #include "scriptapi_common.h"
29 #include "scriptapi_object.h"
30 #include "scriptapi_content.h"
33 struct EnumString es_ItemType[] =
37 {ITEM_CRAFT, "craft"},
47 ItemDefinition read_item_definition(lua_State *L, int index,
48 ItemDefinition default_def)
51 index = lua_gettop(L) + 1 + index;
53 // Read the item definition
54 ItemDefinition def = default_def;
56 def.type = (ItemType)getenumfield(L, index, "type",
57 es_ItemType, ITEM_NONE);
58 getstringfield(L, index, "name", def.name);
59 getstringfield(L, index, "description", def.description);
60 getstringfield(L, index, "inventory_image", def.inventory_image);
61 getstringfield(L, index, "wield_image", def.wield_image);
63 lua_getfield(L, index, "wield_scale");
64 if(lua_istable(L, -1)){
65 def.wield_scale = check_v3f(L, -1);
69 def.stack_max = getintfield_default(L, index, "stack_max", def.stack_max);
70 if(def.stack_max == 0)
73 lua_getfield(L, index, "on_use");
74 def.usable = lua_isfunction(L, -1);
77 getboolfield(L, index, "liquids_pointable", def.liquids_pointable);
79 warn_if_field_exists(L, index, "tool_digging_properties",
80 "deprecated: use tool_capabilities");
82 lua_getfield(L, index, "tool_capabilities");
83 if(lua_istable(L, -1)){
84 def.tool_capabilities = new ToolCapabilities(
85 read_tool_capabilities(L, -1));
88 // If name is "" (hand), ensure there are ToolCapabilities
89 // because it will be looked up there whenever any other item has
90 // no ToolCapabilities
91 if(def.name == "" && def.tool_capabilities == NULL){
92 def.tool_capabilities = new ToolCapabilities();
95 lua_getfield(L, index, "groups");
96 read_groups(L, -1, def.groups);
99 lua_getfield(L, index, "sounds");
100 if(lua_istable(L, -1)){
101 lua_getfield(L, -1, "place");
102 read_soundspec(L, -1, def.sound_place);
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);
116 // register_item_raw({lots of stuff})
117 int l_register_item_raw(lua_State *L)
119 luaL_checktype(L, 1, LUA_TTABLE);
122 // Get the writable item and node definition managers from the server
123 IWritableItemDefManager *idef =
124 get_server(L)->getWritableItemDefManager();
125 IWritableNodeDefManager *ndef =
126 get_server(L)->getWritableNodeDefManager();
128 // Check if name is defined
130 lua_getfield(L, table, "name");
131 if(lua_isstring(L, -1)){
132 name = lua_tostring(L, -1);
133 verbosestream<<"register_item_raw: "<<name<<std::endl;
135 throw LuaError(L, "register_item_raw: name is not defined or not a string");
138 // Check if on_use is defined
141 // Set a distinctive default value to check if this is set
142 def.node_placement_prediction = "__default";
144 // Read the item definition
145 def = read_item_definition(L, table, def);
147 // Default to having client-side placement prediction for nodes
148 // ("" in item definition sets it off)
149 if(def.node_placement_prediction == "__default"){
150 if(def.type == ITEM_NODE)
151 def.node_placement_prediction = name;
153 def.node_placement_prediction = "";
156 // Register item definition
157 idef->registerItem(def);
159 // Read the node definition (content features) and register it
160 if(def.type == ITEM_NODE)
162 ContentFeatures f = read_content_features(L, table);
163 ndef->set(f.name, f);
166 return 0; /* number of results */
169 // register_alias_raw(name, convert_to_name)
170 int l_register_alias_raw(lua_State *L)
172 std::string name = luaL_checkstring(L, 1);
173 std::string convert_to = luaL_checkstring(L, 2);
175 // Get the writable item definition manager from the server
176 IWritableItemDefManager *idef =
177 get_server(L)->getWritableItemDefManager();
179 idef->registerAlias(name, convert_to);
181 return 0; /* number of results */
184 // Retrieves minetest.registered_items[name][callbackname]
185 // If that is nil or on error, return false and stack is unchanged
186 // If that is a function, returns true and pushes the
187 // function onto the stack
188 // If minetest.registered_items[name] doesn't exist, minetest.nodedef_default
189 // is tried instead so unknown items can still be manipulated to some degree
190 bool get_item_callback(lua_State *L,
191 const char *name, const char *callbackname)
193 lua_getglobal(L, "minetest");
194 lua_getfield(L, -1, "registered_items");
196 luaL_checktype(L, -1, LUA_TTABLE);
197 lua_getfield(L, -1, name);
200 if(lua_type(L, -1) != LUA_TTABLE)
202 // Report error and clean up
203 errorstream<<"Item \""<<name<<"\" not defined"<<std::endl;
206 // Try minetest.nodedef_default instead
207 lua_getglobal(L, "minetest");
208 lua_getfield(L, -1, "nodedef_default");
210 luaL_checktype(L, -1, LUA_TTABLE);
212 lua_getfield(L, -1, callbackname);
214 // Should be a function or nil
215 if(lua_type(L, -1) == LUA_TFUNCTION)
219 else if(lua_isnil(L, -1))
226 errorstream<<"Item \""<<name<<"\" callback \""
227 <<callbackname<<" is not a function"<<std::endl;
233 bool scriptapi_item_on_drop(lua_State *L, ItemStack &item,
234 ServerActiveObject *dropper, v3f pos)
237 assert(lua_checkstack(L, 20));
238 StackUnroller stack_unroller(L);
240 // Push callback function on stack
241 if(!get_item_callback(L, item.name.c_str(), "on_drop"))
245 LuaItemStack::create(L, item);
246 objectref_get_or_create(L, dropper);
247 pushFloatPos(L, pos);
248 if(lua_pcall(L, 3, 1, 0))
249 script_error(L, "error: %s", lua_tostring(L, -1));
250 if(!lua_isnil(L, -1))
251 item = read_item(L, -1);
255 bool scriptapi_item_on_place(lua_State *L, ItemStack &item,
256 ServerActiveObject *placer, const PointedThing &pointed)
259 assert(lua_checkstack(L, 20));
260 StackUnroller stack_unroller(L);
262 // Push callback function on stack
263 if(!get_item_callback(L, item.name.c_str(), "on_place"))
267 LuaItemStack::create(L, item);
268 objectref_get_or_create(L, placer);
269 push_pointed_thing(L, pointed);
270 if(lua_pcall(L, 3, 1, 0))
271 script_error(L, "error: %s", lua_tostring(L, -1));
272 if(!lua_isnil(L, -1))
273 item = read_item(L, -1);
277 bool scriptapi_item_on_use(lua_State *L, ItemStack &item,
278 ServerActiveObject *user, const PointedThing &pointed)
281 assert(lua_checkstack(L, 20));
282 StackUnroller stack_unroller(L);
284 // Push callback function on stack
285 if(!get_item_callback(L, item.name.c_str(), "on_use"))
289 LuaItemStack::create(L, item);
290 objectref_get_or_create(L, user);
291 push_pointed_thing(L, pointed);
292 if(lua_pcall(L, 3, 1, 0))
293 script_error(L, "error: %s", lua_tostring(L, -1));
294 if(!lua_isnil(L, -1))
295 item = read_item(L, -1);
300 int LuaItemStack::gc_object(lua_State *L)
302 LuaItemStack *o = *(LuaItemStack **)(lua_touserdata(L, 1));
307 // is_empty(self) -> true/false
308 int LuaItemStack::l_is_empty(lua_State *L)
310 LuaItemStack *o = checkobject(L, 1);
311 ItemStack &item = o->m_stack;
312 lua_pushboolean(L, item.empty());
316 // get_name(self) -> string
317 int LuaItemStack::l_get_name(lua_State *L)
319 LuaItemStack *o = checkobject(L, 1);
320 ItemStack &item = o->m_stack;
321 lua_pushstring(L, item.name.c_str());
325 // get_count(self) -> number
326 int LuaItemStack::l_get_count(lua_State *L)
328 LuaItemStack *o = checkobject(L, 1);
329 ItemStack &item = o->m_stack;
330 lua_pushinteger(L, item.count);
334 // get_wear(self) -> number
335 int LuaItemStack::l_get_wear(lua_State *L)
337 LuaItemStack *o = checkobject(L, 1);
338 ItemStack &item = o->m_stack;
339 lua_pushinteger(L, item.wear);
343 // get_metadata(self) -> string
344 int LuaItemStack::l_get_metadata(lua_State *L)
346 LuaItemStack *o = checkobject(L, 1);
347 ItemStack &item = o->m_stack;
348 lua_pushlstring(L, item.metadata.c_str(), item.metadata.size());
352 // clear(self) -> true
353 int LuaItemStack::l_clear(lua_State *L)
355 LuaItemStack *o = checkobject(L, 1);
357 lua_pushboolean(L, true);
361 // replace(self, itemstack or itemstring or table or nil) -> true
362 int LuaItemStack::l_replace(lua_State *L)
364 LuaItemStack *o = checkobject(L, 1);
365 o->m_stack = read_item(L, 2);
366 lua_pushboolean(L, true);
370 // to_string(self) -> string
371 int LuaItemStack::l_to_string(lua_State *L)
373 LuaItemStack *o = checkobject(L, 1);
374 std::string itemstring = o->m_stack.getItemString();
375 lua_pushstring(L, itemstring.c_str());
379 // to_table(self) -> table or nil
380 int LuaItemStack::l_to_table(lua_State *L)
382 LuaItemStack *o = checkobject(L, 1);
383 const ItemStack &item = o->m_stack;
391 lua_pushstring(L, item.name.c_str());
392 lua_setfield(L, -2, "name");
393 lua_pushinteger(L, item.count);
394 lua_setfield(L, -2, "count");
395 lua_pushinteger(L, item.wear);
396 lua_setfield(L, -2, "wear");
397 lua_pushlstring(L, item.metadata.c_str(), item.metadata.size());
398 lua_setfield(L, -2, "metadata");
403 // get_stack_max(self) -> number
404 int LuaItemStack::l_get_stack_max(lua_State *L)
406 LuaItemStack *o = checkobject(L, 1);
407 ItemStack &item = o->m_stack;
408 lua_pushinteger(L, item.getStackMax(get_server(L)->idef()));
412 // get_free_space(self) -> number
413 int LuaItemStack::l_get_free_space(lua_State *L)
415 LuaItemStack *o = checkobject(L, 1);
416 ItemStack &item = o->m_stack;
417 lua_pushinteger(L, item.freeSpace(get_server(L)->idef()));
421 // is_known(self) -> true/false
422 // Checks if the item is defined.
423 int LuaItemStack::l_is_known(lua_State *L)
425 LuaItemStack *o = checkobject(L, 1);
426 ItemStack &item = o->m_stack;
427 bool is_known = item.isKnown(get_server(L)->idef());
428 lua_pushboolean(L, is_known);
432 // get_definition(self) -> table
433 // Returns the item definition table from minetest.registered_items,
434 // or a fallback one (name="unknown")
435 int LuaItemStack::l_get_definition(lua_State *L)
437 LuaItemStack *o = checkobject(L, 1);
438 ItemStack &item = o->m_stack;
440 // Get minetest.registered_items[name]
441 lua_getglobal(L, "minetest");
442 lua_getfield(L, -1, "registered_items");
443 luaL_checktype(L, -1, LUA_TTABLE);
444 lua_getfield(L, -1, item.name.c_str());
448 lua_getfield(L, -1, "unknown");
453 // get_tool_capabilities(self) -> table
454 // Returns the effective tool digging properties.
455 // Returns those of the hand ("") if this item has none associated.
456 int LuaItemStack::l_get_tool_capabilities(lua_State *L)
458 LuaItemStack *o = checkobject(L, 1);
459 ItemStack &item = o->m_stack;
460 const ToolCapabilities &prop =
461 item.getToolCapabilities(get_server(L)->idef());
462 push_tool_capabilities(L, prop);
466 // add_wear(self, amount) -> true/false
467 // The range for "amount" is [0,65535]. Wear is only added if the item
468 // is a tool. Adding wear might destroy the item.
469 // Returns true if the item is (or was) a tool.
470 int LuaItemStack::l_add_wear(lua_State *L)
472 LuaItemStack *o = checkobject(L, 1);
473 ItemStack &item = o->m_stack;
474 int amount = lua_tointeger(L, 2);
475 bool result = item.addWear(amount, get_server(L)->idef());
476 lua_pushboolean(L, result);
480 // add_item(self, itemstack or itemstring or table or nil) -> itemstack
481 // Returns leftover item stack
482 int LuaItemStack::l_add_item(lua_State *L)
484 LuaItemStack *o = checkobject(L, 1);
485 ItemStack &item = o->m_stack;
486 ItemStack newitem = read_item(L, 2);
487 ItemStack leftover = item.addItem(newitem, get_server(L)->idef());
492 // item_fits(self, itemstack or itemstring or table or nil) -> true/false, itemstack
493 // First return value is true iff the new item fits fully into the stack
494 // Second return value is the would-be-left-over item stack
495 int LuaItemStack::l_item_fits(lua_State *L)
497 LuaItemStack *o = checkobject(L, 1);
498 ItemStack &item = o->m_stack;
499 ItemStack newitem = read_item(L, 2);
501 bool fits = item.itemFits(newitem, &restitem, get_server(L)->idef());
502 lua_pushboolean(L, fits); // first return value
503 create(L, restitem); // second return value
507 // take_item(self, takecount=1) -> itemstack
508 int LuaItemStack::l_take_item(lua_State *L)
510 LuaItemStack *o = checkobject(L, 1);
511 ItemStack &item = o->m_stack;
513 if(!lua_isnone(L, 2))
514 takecount = luaL_checkinteger(L, 2);
515 ItemStack taken = item.takeItem(takecount);
520 // peek_item(self, peekcount=1) -> itemstack
521 int LuaItemStack::l_peek_item(lua_State *L)
523 LuaItemStack *o = checkobject(L, 1);
524 ItemStack &item = o->m_stack;
526 if(!lua_isnone(L, 2))
527 peekcount = lua_tointeger(L, 2);
528 ItemStack peekaboo = item.peekItem(peekcount);
533 LuaItemStack::LuaItemStack(const ItemStack &item):
538 LuaItemStack::~LuaItemStack()
542 const ItemStack& LuaItemStack::getItem() const
546 ItemStack& LuaItemStack::getItem()
551 // LuaItemStack(itemstack or itemstring or table or nil)
552 // Creates an LuaItemStack and leaves it on top of stack
553 int LuaItemStack::create_object(lua_State *L)
555 ItemStack item = read_item(L, 1);
556 LuaItemStack *o = new LuaItemStack(item);
557 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
558 luaL_getmetatable(L, className);
559 lua_setmetatable(L, -2);
562 // Not callable from Lua
563 int LuaItemStack::create(lua_State *L, const ItemStack &item)
565 LuaItemStack *o = new LuaItemStack(item);
566 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
567 luaL_getmetatable(L, className);
568 lua_setmetatable(L, -2);
572 LuaItemStack* LuaItemStack::checkobject(lua_State *L, int narg)
574 luaL_checktype(L, narg, LUA_TUSERDATA);
575 void *ud = luaL_checkudata(L, narg, className);
576 if(!ud) luaL_typerror(L, narg, className);
577 return *(LuaItemStack**)ud; // unbox pointer
580 void LuaItemStack::Register(lua_State *L)
583 int methodtable = lua_gettop(L);
584 luaL_newmetatable(L, className);
585 int metatable = lua_gettop(L);
587 lua_pushliteral(L, "__metatable");
588 lua_pushvalue(L, methodtable);
589 lua_settable(L, metatable); // hide metatable from Lua getmetatable()
591 lua_pushliteral(L, "__index");
592 lua_pushvalue(L, methodtable);
593 lua_settable(L, metatable);
595 lua_pushliteral(L, "__gc");
596 lua_pushcfunction(L, gc_object);
597 lua_settable(L, metatable);
599 lua_pop(L, 1); // drop metatable
601 luaL_openlib(L, 0, methods, 0); // fill methodtable
602 lua_pop(L, 1); // drop methodtable
604 // Can be created from Lua (LuaItemStack(itemstack or itemstring or table or nil))
605 lua_register(L, className, create_object);
608 const char LuaItemStack::className[] = "ItemStack";
609 const luaL_reg LuaItemStack::methods[] = {
610 luamethod(LuaItemStack, is_empty),
611 luamethod(LuaItemStack, get_name),
612 luamethod(LuaItemStack, get_count),
613 luamethod(LuaItemStack, get_wear),
614 luamethod(LuaItemStack, get_metadata),
615 luamethod(LuaItemStack, clear),
616 luamethod(LuaItemStack, replace),
617 luamethod(LuaItemStack, to_string),
618 luamethod(LuaItemStack, to_table),
619 luamethod(LuaItemStack, get_stack_max),
620 luamethod(LuaItemStack, get_free_space),
621 luamethod(LuaItemStack, is_known),
622 luamethod(LuaItemStack, get_definition),
623 luamethod(LuaItemStack, get_tool_capabilities),
624 luamethod(LuaItemStack, add_wear),
625 luamethod(LuaItemStack, add_item),
626 luamethod(LuaItemStack, item_fits),
627 luamethod(LuaItemStack, take_item),
628 luamethod(LuaItemStack, peek_item),
632 ItemStack read_item(lua_State *L, int index)
635 index = lua_gettop(L) + 1 + index;
637 if(lua_isnil(L, index))
641 else if(lua_isuserdata(L, index))
643 // Convert from LuaItemStack
644 LuaItemStack *o = LuaItemStack::checkobject(L, index);
647 else if(lua_isstring(L, index))
649 // Convert from itemstring
650 std::string itemstring = lua_tostring(L, index);
651 IItemDefManager *idef = get_server(L)->idef();
655 item.deSerialize(itemstring, idef);
658 catch(SerializationError &e)
660 infostream<<"WARNING: unable to create item from itemstring"
661 <<": "<<itemstring<<std::endl;
665 else if(lua_istable(L, index))
667 // Convert from table
668 IItemDefManager *idef = get_server(L)->idef();
669 std::string name = getstringfield_default(L, index, "name", "");
670 int count = getintfield_default(L, index, "count", 1);
671 int wear = getintfield_default(L, index, "wear", 0);
672 std::string metadata = getstringfield_default(L, index, "metadata", "");
673 return ItemStack(name, count, wear, metadata, idef);
677 throw LuaError(L, "Expecting itemstack, itemstring, table or nil");
681 std::vector<ItemStack> read_items(lua_State *L, int index)
684 index = lua_gettop(L) + 1 + index;
686 std::vector<ItemStack> items;
687 luaL_checktype(L, index, LUA_TTABLE);
689 while(lua_next(L, index) != 0){
690 // key at index -2 and value at index -1
691 items.push_back(read_item(L, -1));
692 // removes value, keeps key for next iteration
698 // creates a table of ItemStacks
699 void push_items(lua_State *L, const std::vector<ItemStack> &items)
701 // Get the table insert function
702 lua_getglobal(L, "table");
703 lua_getfield(L, -1, "insert");
704 int table_insert = lua_gettop(L);
705 // Create and fill table
707 int table = lua_gettop(L);
708 for(u32 i=0; i<items.size(); i++){
709 ItemStack item = items[i];
710 lua_pushvalue(L, table_insert);
711 lua_pushvalue(L, table);
712 LuaItemStack::create(L, item);
713 if(lua_pcall(L, 2, 0, 0))
714 script_error(L, "error: %s", lua_tostring(L, -1));
716 lua_remove(L, -2); // Remove table
717 lua_remove(L, -2); // Remove insert