e41d23fd148fdd11f21ee6a526a526dc61023195
[oweals/minetest.git] / src / script / lua_api / l_item.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
20 #include "lua_api/l_item.h"
21 #include "lua_api/l_itemstackmeta.h"
22 #include "lua_api/l_internal.h"
23 #include "common/c_converter.h"
24 #include "common/c_content.h"
25 #include "itemdef.h"
26 #include "nodedef.h"
27 #include "server.h"
28 #include "content_sao.h"
29 #include "inventory.h"
30 #include "log.h"
31
32
33 // garbage collector
34 int LuaItemStack::gc_object(lua_State *L)
35 {
36         LuaItemStack *o = *(LuaItemStack **)(lua_touserdata(L, 1));
37         delete o;
38         return 0;
39 }
40
41 // is_empty(self) -> true/false
42 int LuaItemStack::l_is_empty(lua_State *L)
43 {
44         NO_MAP_LOCK_REQUIRED;
45         LuaItemStack *o = checkobject(L, 1);
46         ItemStack &item = o->m_stack;
47         lua_pushboolean(L, item.empty());
48         return 1;
49 }
50
51 // get_name(self) -> string
52 int LuaItemStack::l_get_name(lua_State *L)
53 {
54         NO_MAP_LOCK_REQUIRED;
55         LuaItemStack *o = checkobject(L, 1);
56         ItemStack &item = o->m_stack;
57         lua_pushstring(L, item.name.c_str());
58         return 1;
59 }
60
61 // set_name(self, name)
62 int LuaItemStack::l_set_name(lua_State *L)
63 {
64         NO_MAP_LOCK_REQUIRED;
65         LuaItemStack *o = checkobject(L, 1);
66         ItemStack &item = o->m_stack;
67
68         bool status = true;
69         item.name = luaL_checkstring(L, 2);
70         if (item.name.empty() || item.empty()) {
71                 item.clear();
72                 status = false;
73         }
74
75         lua_pushboolean(L, status);
76         return 1;
77 }
78
79 // get_count(self) -> number
80 int LuaItemStack::l_get_count(lua_State *L)
81 {
82         NO_MAP_LOCK_REQUIRED;
83         LuaItemStack *o = checkobject(L, 1);
84         ItemStack &item = o->m_stack;
85         lua_pushinteger(L, item.count);
86         return 1;
87 }
88
89 // set_count(self, number)
90 int LuaItemStack::l_set_count(lua_State *L)
91 {
92         NO_MAP_LOCK_REQUIRED;
93         LuaItemStack *o = checkobject(L, 1);
94         ItemStack &item = o->m_stack;
95
96         bool status;
97         lua_Integer count = luaL_checkinteger(L, 2);
98         if (count > 0 && count <= 65535) {
99                 item.count = count;
100                 status = true;
101         } else {
102                 item.clear();
103                 status = false;
104         }
105
106         lua_pushboolean(L, status);
107         return 1;
108 }
109
110 // get_wear(self) -> number
111 int LuaItemStack::l_get_wear(lua_State *L)
112 {
113         NO_MAP_LOCK_REQUIRED;
114         LuaItemStack *o = checkobject(L, 1);
115         ItemStack &item = o->m_stack;
116         lua_pushinteger(L, item.wear);
117         return 1;
118 }
119
120 // set_wear(self, number)
121 int LuaItemStack::l_set_wear(lua_State *L)
122 {
123         NO_MAP_LOCK_REQUIRED;
124         LuaItemStack *o = checkobject(L, 1);
125         ItemStack &item = o->m_stack;
126
127         bool status;
128         lua_Integer wear = luaL_checkinteger(L, 2);
129         if (wear <= 65535) {
130                 item.wear = wear;
131                 status = true;
132         } else {
133                 item.clear();
134                 status = false;
135         }
136
137         lua_pushboolean(L, status);
138         return 1;
139 }
140
141 // get_meta(self) -> string
142 int LuaItemStack::l_get_meta(lua_State *L)
143 {
144         NO_MAP_LOCK_REQUIRED;
145         LuaItemStack *o = checkobject(L, 1);
146         ItemStackMetaRef::create(L, &o->m_stack);
147         return 1;
148 }
149
150 // DEPRECATED
151 // get_metadata(self) -> string
152 int LuaItemStack::l_get_metadata(lua_State *L)
153 {
154         NO_MAP_LOCK_REQUIRED;
155         LuaItemStack *o = checkobject(L, 1);
156         ItemStack &item = o->m_stack;
157         const std::string &value = item.metadata.getString("");
158         lua_pushlstring(L, value.c_str(), value.size());
159         return 1;
160 }
161
162 // DEPRECATED
163 // set_metadata(self, string)
164 int LuaItemStack::l_set_metadata(lua_State *L)
165 {
166         NO_MAP_LOCK_REQUIRED;
167         LuaItemStack *o = checkobject(L, 1);
168         ItemStack &item = o->m_stack;
169
170         size_t len = 0;
171         const char *ptr = luaL_checklstring(L, 2, &len);
172         item.metadata.setString("", std::string(ptr, len));
173
174         lua_pushboolean(L, true);
175         return 1;
176 }
177
178 // clear(self) -> true
179 int LuaItemStack::l_clear(lua_State *L)
180 {
181         NO_MAP_LOCK_REQUIRED;
182         LuaItemStack *o = checkobject(L, 1);
183         o->m_stack.clear();
184         lua_pushboolean(L, true);
185         return 1;
186 }
187
188 // replace(self, itemstack or itemstring or table or nil) -> true
189 int LuaItemStack::l_replace(lua_State *L)
190 {
191         NO_MAP_LOCK_REQUIRED;
192         LuaItemStack *o = checkobject(L, 1);
193         o->m_stack = read_item(L, 2, getGameDef(L)->idef());
194         lua_pushboolean(L, true);
195         return 1;
196 }
197
198 // to_string(self) -> string
199 int LuaItemStack::l_to_string(lua_State *L)
200 {
201         NO_MAP_LOCK_REQUIRED;
202         LuaItemStack *o = checkobject(L, 1);
203         std::string itemstring = o->m_stack.getItemString();
204         lua_pushstring(L, itemstring.c_str());
205         return 1;
206 }
207
208 // to_table(self) -> table or nil
209 int LuaItemStack::l_to_table(lua_State *L)
210 {
211         NO_MAP_LOCK_REQUIRED;
212         LuaItemStack *o = checkobject(L, 1);
213         const ItemStack &item = o->m_stack;
214         if(item.empty())
215         {
216                 lua_pushnil(L);
217         }
218         else
219         {
220                 lua_newtable(L);
221                 lua_pushstring(L, item.name.c_str());
222                 lua_setfield(L, -2, "name");
223                 lua_pushinteger(L, item.count);
224                 lua_setfield(L, -2, "count");
225                 lua_pushinteger(L, item.wear);
226                 lua_setfield(L, -2, "wear");
227
228                 const std::string &metadata_str = item.metadata.getString("");
229                 lua_pushlstring(L, metadata_str.c_str(), metadata_str.size());
230                 lua_setfield(L, -2, "metadata");
231
232                 lua_newtable(L);
233                 const StringMap &fields = item.metadata.getStrings();
234                 for (const auto &field : fields) {
235                         const std::string &name = field.first;
236                         if (name.empty())
237                                 continue;
238                         const std::string &value = field.second;
239                         lua_pushlstring(L, name.c_str(), name.size());
240                         lua_pushlstring(L, value.c_str(), value.size());
241                         lua_settable(L, -3);
242                 }
243                 lua_setfield(L, -2, "meta");
244         }
245         return 1;
246 }
247
248 // get_stack_max(self) -> number
249 int LuaItemStack::l_get_stack_max(lua_State *L)
250 {
251         NO_MAP_LOCK_REQUIRED;
252         LuaItemStack *o = checkobject(L, 1);
253         ItemStack &item = o->m_stack;
254         lua_pushinteger(L, item.getStackMax(getGameDef(L)->idef()));
255         return 1;
256 }
257
258 // get_free_space(self) -> number
259 int LuaItemStack::l_get_free_space(lua_State *L)
260 {
261         NO_MAP_LOCK_REQUIRED;
262         LuaItemStack *o = checkobject(L, 1);
263         ItemStack &item = o->m_stack;
264         lua_pushinteger(L, item.freeSpace(getGameDef(L)->idef()));
265         return 1;
266 }
267
268 // is_known(self) -> true/false
269 // Checks if the item is defined.
270 int LuaItemStack::l_is_known(lua_State *L)
271 {
272         NO_MAP_LOCK_REQUIRED;
273         LuaItemStack *o = checkobject(L, 1);
274         ItemStack &item = o->m_stack;
275         bool is_known = item.isKnown(getGameDef(L)->idef());
276         lua_pushboolean(L, is_known);
277         return 1;
278 }
279
280 // get_definition(self) -> table
281 // Returns the item definition table from registered_items,
282 // or a fallback one (name="unknown")
283 int LuaItemStack::l_get_definition(lua_State *L)
284 {
285         NO_MAP_LOCK_REQUIRED;
286         LuaItemStack *o = checkobject(L, 1);
287         ItemStack &item = o->m_stack;
288
289         // Get registered_items[name]
290         lua_getglobal(L, "core");
291         lua_getfield(L, -1, "registered_items");
292         luaL_checktype(L, -1, LUA_TTABLE);
293         lua_getfield(L, -1, item.name.c_str());
294         if(lua_isnil(L, -1))
295         {
296                 lua_pop(L, 1);
297                 lua_getfield(L, -1, "unknown");
298         }
299         return 1;
300 }
301
302 // get_tool_capabilities(self) -> table
303 // Returns the effective tool digging properties.
304 // Returns those of the hand ("") if this item has none associated.
305 int LuaItemStack::l_get_tool_capabilities(lua_State *L)
306 {
307         NO_MAP_LOCK_REQUIRED;
308         LuaItemStack *o = checkobject(L, 1);
309         ItemStack &item = o->m_stack;
310         const ToolCapabilities &prop =
311                 item.getToolCapabilities(getGameDef(L)->idef());
312         push_tool_capabilities(L, prop);
313         return 1;
314 }
315
316 // add_wear(self, amount) -> true/false
317 // The range for "amount" is [0,65535]. Wear is only added if the item
318 // is a tool. Adding wear might destroy the item.
319 // Returns true if the item is (or was) a tool.
320 int LuaItemStack::l_add_wear(lua_State *L)
321 {
322         NO_MAP_LOCK_REQUIRED;
323         LuaItemStack *o = checkobject(L, 1);
324         ItemStack &item = o->m_stack;
325         int amount = lua_tointeger(L, 2);
326         bool result = item.addWear(amount, getGameDef(L)->idef());
327         lua_pushboolean(L, result);
328         return 1;
329 }
330
331 // add_item(self, itemstack or itemstring or table or nil) -> itemstack
332 // Returns leftover item stack
333 int LuaItemStack::l_add_item(lua_State *L)
334 {
335         NO_MAP_LOCK_REQUIRED;
336         LuaItemStack *o = checkobject(L, 1);
337         ItemStack &item = o->m_stack;
338         ItemStack newitem = read_item(L, -1, getGameDef(L)->idef());
339         ItemStack leftover = item.addItem(newitem, getGameDef(L)->idef());
340         create(L, leftover);
341         return 1;
342 }
343
344 // item_fits(self, itemstack or itemstring or table or nil) -> true/false, itemstack
345 // First return value is true iff the new item fits fully into the stack
346 // Second return value is the would-be-left-over item stack
347 int LuaItemStack::l_item_fits(lua_State *L)
348 {
349         NO_MAP_LOCK_REQUIRED;
350         LuaItemStack *o = checkobject(L, 1);
351         ItemStack &item = o->m_stack;
352         ItemStack newitem = read_item(L, 2, getGameDef(L)->idef());
353         ItemStack restitem;
354         bool fits = item.itemFits(newitem, &restitem, getGameDef(L)->idef());
355         lua_pushboolean(L, fits);  // first return value
356         create(L, restitem);       // second return value
357         return 2;
358 }
359
360 // take_item(self, takecount=1) -> itemstack
361 int LuaItemStack::l_take_item(lua_State *L)
362 {
363         NO_MAP_LOCK_REQUIRED;
364         LuaItemStack *o = checkobject(L, 1);
365         ItemStack &item = o->m_stack;
366         u32 takecount = 1;
367         if(!lua_isnone(L, 2))
368                 takecount = luaL_checkinteger(L, 2);
369         ItemStack taken = item.takeItem(takecount);
370         create(L, taken);
371         return 1;
372 }
373
374 // peek_item(self, peekcount=1) -> itemstack
375 int LuaItemStack::l_peek_item(lua_State *L)
376 {
377         NO_MAP_LOCK_REQUIRED;
378         LuaItemStack *o = checkobject(L, 1);
379         ItemStack &item = o->m_stack;
380         u32 peekcount = 1;
381         if(!lua_isnone(L, 2))
382                 peekcount = lua_tointeger(L, 2);
383         ItemStack peekaboo = item.peekItem(peekcount);
384         create(L, peekaboo);
385         return 1;
386 }
387
388 LuaItemStack::LuaItemStack(const ItemStack &item):
389         m_stack(item)
390 {
391 }
392
393 const ItemStack& LuaItemStack::getItem() const
394 {
395         return m_stack;
396 }
397 ItemStack& LuaItemStack::getItem()
398 {
399         return m_stack;
400 }
401
402 // LuaItemStack(itemstack or itemstring or table or nil)
403 // Creates an LuaItemStack and leaves it on top of stack
404 int LuaItemStack::create_object(lua_State *L)
405 {
406         NO_MAP_LOCK_REQUIRED;
407         ItemStack item = read_item(L, 1, getGameDef(L)->idef());
408         LuaItemStack *o = new LuaItemStack(item);
409         *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
410         luaL_getmetatable(L, className);
411         lua_setmetatable(L, -2);
412         return 1;
413 }
414 // Not callable from Lua
415 int LuaItemStack::create(lua_State *L, const ItemStack &item)
416 {
417         NO_MAP_LOCK_REQUIRED;
418         LuaItemStack *o = new LuaItemStack(item);
419         *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
420         luaL_getmetatable(L, className);
421         lua_setmetatable(L, -2);
422         return 1;
423 }
424
425 LuaItemStack* LuaItemStack::checkobject(lua_State *L, int narg)
426 {
427         luaL_checktype(L, narg, LUA_TUSERDATA);
428         void *ud = luaL_checkudata(L, narg, className);
429         if(!ud) luaL_typerror(L, narg, className);
430         return *(LuaItemStack**)ud;  // unbox pointer
431 }
432
433 void LuaItemStack::Register(lua_State *L)
434 {
435         lua_newtable(L);
436         int methodtable = lua_gettop(L);
437         luaL_newmetatable(L, className);
438         int metatable = lua_gettop(L);
439
440         lua_pushliteral(L, "__metatable");
441         lua_pushvalue(L, methodtable);
442         lua_settable(L, metatable);  // hide metatable from Lua getmetatable()
443
444         lua_pushliteral(L, "__index");
445         lua_pushvalue(L, methodtable);
446         lua_settable(L, metatable);
447
448         lua_pushliteral(L, "__gc");
449         lua_pushcfunction(L, gc_object);
450         lua_settable(L, metatable);
451
452         lua_pop(L, 1);  // drop metatable
453
454         luaL_openlib(L, 0, methods, 0);  // fill methodtable
455         lua_pop(L, 1);  // drop methodtable
456
457         // Can be created from Lua (LuaItemStack(itemstack or itemstring or table or nil))
458         lua_register(L, className, create_object);
459 }
460
461 const char LuaItemStack::className[] = "ItemStack";
462 const luaL_Reg LuaItemStack::methods[] = {
463         luamethod(LuaItemStack, is_empty),
464         luamethod(LuaItemStack, get_name),
465         luamethod(LuaItemStack, set_name),
466         luamethod(LuaItemStack, get_count),
467         luamethod(LuaItemStack, set_count),
468         luamethod(LuaItemStack, get_wear),
469         luamethod(LuaItemStack, set_wear),
470         luamethod(LuaItemStack, get_meta),
471         luamethod(LuaItemStack, get_metadata),
472         luamethod(LuaItemStack, set_metadata),
473         luamethod(LuaItemStack, clear),
474         luamethod(LuaItemStack, replace),
475         luamethod(LuaItemStack, to_string),
476         luamethod(LuaItemStack, to_table),
477         luamethod(LuaItemStack, get_stack_max),
478         luamethod(LuaItemStack, get_free_space),
479         luamethod(LuaItemStack, is_known),
480         luamethod(LuaItemStack, get_definition),
481         luamethod(LuaItemStack, get_tool_capabilities),
482         luamethod(LuaItemStack, add_wear),
483         luamethod(LuaItemStack, add_item),
484         luamethod(LuaItemStack, item_fits),
485         luamethod(LuaItemStack, take_item),
486         luamethod(LuaItemStack, peek_item),
487         {0,0}
488 };
489
490 /*
491         ItemDefinition
492 */
493
494 // register_item_raw({lots of stuff})
495 int ModApiItemMod::l_register_item_raw(lua_State *L)
496 {
497         NO_MAP_LOCK_REQUIRED;
498         luaL_checktype(L, 1, LUA_TTABLE);
499         int table = 1;
500
501         // Get the writable item and node definition managers from the server
502         IWritableItemDefManager *idef =
503                         getServer(L)->getWritableItemDefManager();
504         NodeDefManager *ndef =
505                         getServer(L)->getWritableNodeDefManager();
506
507         // Check if name is defined
508         std::string name;
509         lua_getfield(L, table, "name");
510         if(lua_isstring(L, -1)){
511                 name = readParam<std::string>(L, -1);
512                 verbosestream<<"register_item_raw: "<<name<<std::endl;
513         } else {
514                 throw LuaError("register_item_raw: name is not defined or not a string");
515         }
516
517         // Check if on_use is defined
518
519         ItemDefinition def;
520         // Set a distinctive default value to check if this is set
521         def.node_placement_prediction = "__default";
522
523         // Read the item definition
524         read_item_definition(L, table, def, def);
525
526         // Default to having client-side placement prediction for nodes
527         // ("" in item definition sets it off)
528         if(def.node_placement_prediction == "__default"){
529                 if(def.type == ITEM_NODE)
530                         def.node_placement_prediction = name;
531                 else
532                         def.node_placement_prediction = "";
533         }
534
535         // Register item definition
536         idef->registerItem(def);
537
538         // Read the node definition (content features) and register it
539         if (def.type == ITEM_NODE) {
540                 ContentFeatures f = read_content_features(L, table);
541                 // when a mod reregisters ignore, only texture changes and such should
542                 // be done
543                 if (f.name == "ignore")
544                         return 0;
545
546                 content_t id = ndef->set(f.name, f);
547
548                 if (id > MAX_REGISTERED_CONTENT) {
549                         throw LuaError("Number of registerable nodes ("
550                                         + itos(MAX_REGISTERED_CONTENT+1)
551                                         + ") exceeded (" + name + ")");
552                 }
553         }
554
555         return 0; /* number of results */
556 }
557
558 // unregister_item(name)
559 int ModApiItemMod::l_unregister_item_raw(lua_State *L)
560 {
561         NO_MAP_LOCK_REQUIRED;
562         std::string name = luaL_checkstring(L, 1);
563
564         IWritableItemDefManager *idef =
565                         getServer(L)->getWritableItemDefManager();
566
567         // Unregister the node
568         if (idef->get(name).type == ITEM_NODE) {
569                 NodeDefManager *ndef =
570                         getServer(L)->getWritableNodeDefManager();
571                 ndef->removeNode(name);
572         }
573
574         idef->unregisterItem(name);
575
576         return 0; /* number of results */
577 }
578
579 // register_alias_raw(name, convert_to_name)
580 int ModApiItemMod::l_register_alias_raw(lua_State *L)
581 {
582         NO_MAP_LOCK_REQUIRED;
583         std::string name = luaL_checkstring(L, 1);
584         std::string convert_to = luaL_checkstring(L, 2);
585
586         // Get the writable item definition manager from the server
587         IWritableItemDefManager *idef =
588                         getServer(L)->getWritableItemDefManager();
589
590         idef->registerAlias(name, convert_to);
591
592         return 0; /* number of results */
593 }
594
595 // get_content_id(name)
596 int ModApiItemMod::l_get_content_id(lua_State *L)
597 {
598         NO_MAP_LOCK_REQUIRED;
599         std::string name = luaL_checkstring(L, 1);
600
601         const NodeDefManager *ndef = getGameDef(L)->getNodeDefManager();
602         content_t c = ndef->getId(name);
603
604         lua_pushinteger(L, c);
605         return 1; /* number of results */
606 }
607
608 // get_name_from_content_id(name)
609 int ModApiItemMod::l_get_name_from_content_id(lua_State *L)
610 {
611         NO_MAP_LOCK_REQUIRED;
612         content_t c = luaL_checkint(L, 1);
613
614         const NodeDefManager *ndef = getGameDef(L)->getNodeDefManager();
615         const char *name = ndef->get(c).name.c_str();
616
617         lua_pushstring(L, name);
618         return 1; /* number of results */
619 }
620
621 void ModApiItemMod::Initialize(lua_State *L, int top)
622 {
623         API_FCT(register_item_raw);
624         API_FCT(unregister_item_raw);
625         API_FCT(register_alias_raw);
626         API_FCT(get_content_id);
627         API_FCT(get_name_from_content_id);
628 }