]> git.lizzy.rs Git - minetest.git/blob - src/itemdef.cpp
f43e5c970cb3d4212335a6b5e8dac11d4a1de7b4
[minetest.git] / src / itemdef.cpp
1 /*
2 Minetest
3 Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4 Copyright (C) 2013 Kahrl <kahrl@gmx.net>
5
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU Lesser General Public License as published by
8 the Free Software Foundation; either version 2.1 of the License, or
9 (at your option) any later version.
10
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 GNU Lesser General Public License for more details.
15
16 You should have received a copy of the GNU Lesser General Public License along
17 with this program; if not, write to the Free Software Foundation, Inc.,
18 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 */
20
21 #include "itemdef.h"
22
23 #include "nodedef.h"
24 #include "tool.h"
25 #include "inventory.h"
26 #ifndef SERVER
27 #include "mapblock_mesh.h"
28 #include "mesh.h"
29 #include "wieldmesh.h"
30 #include "client/tile.h"
31 #include "client.h"
32 #endif
33 #include "log.h"
34 #include "settings.h"
35 #include "util/serialize.h"
36 #include "util/container.h"
37 #include "util/thread.h"
38 #include <map>
39 #include <set>
40
41 #ifdef __ANDROID__
42 #include <GLES/gl.h>
43 #endif
44
45 /*
46         ItemDefinition
47 */
48 ItemDefinition::ItemDefinition()
49 {
50         resetInitial();
51 }
52
53 ItemDefinition::ItemDefinition(const ItemDefinition &def)
54 {
55         resetInitial();
56         *this = def;
57 }
58
59 ItemDefinition& ItemDefinition::operator=(const ItemDefinition &def)
60 {
61         if(this == &def)
62                 return *this;
63
64         reset();
65
66         type = def.type;
67         name = def.name;
68         description = def.description;
69         inventory_image = def.inventory_image;
70         wield_image = def.wield_image;
71         wield_scale = def.wield_scale;
72         stack_max = def.stack_max;
73         usable = def.usable;
74         liquids_pointable = def.liquids_pointable;
75         if(def.tool_capabilities)
76         {
77                 tool_capabilities = new ToolCapabilities(
78                                 *def.tool_capabilities);
79         }
80         groups = def.groups;
81         node_placement_prediction = def.node_placement_prediction;
82         sound_place = def.sound_place;
83         sound_place_failed = def.sound_place_failed;
84         range = def.range;
85         return *this;
86 }
87
88 ItemDefinition::~ItemDefinition()
89 {
90         reset();
91 }
92
93 void ItemDefinition::resetInitial()
94 {
95         // Initialize pointers to NULL so reset() does not delete undefined pointers
96         tool_capabilities = NULL;
97         reset();
98 }
99
100 void ItemDefinition::reset()
101 {
102         type = ITEM_NONE;
103         name = "";
104         description = "";
105         inventory_image = "";
106         wield_image = "";
107         wield_scale = v3f(1.0, 1.0, 1.0);
108         stack_max = 99;
109         usable = false;
110         liquids_pointable = false;
111         if(tool_capabilities)
112         {
113                 delete tool_capabilities;
114                 tool_capabilities = NULL;
115         }
116         groups.clear();
117         sound_place = SimpleSoundSpec();
118         sound_place_failed = SimpleSoundSpec();
119         range = -1;
120
121         node_placement_prediction = "";
122 }
123
124 void ItemDefinition::serialize(std::ostream &os, u16 protocol_version) const
125 {
126
127         writeU8(os, 3); // version (proto > 20)
128         writeU8(os, type);
129         os << serializeString(name);
130         os << serializeString(description);
131         os << serializeString(inventory_image);
132         os << serializeString(wield_image);
133         writeV3F1000(os, wield_scale);
134         writeS16(os, stack_max);
135         writeU8(os, usable);
136         writeU8(os, liquids_pointable);
137         std::string tool_capabilities_s = "";
138         if(tool_capabilities){
139                 std::ostringstream tmp_os(std::ios::binary);
140                 tool_capabilities->serialize(tmp_os, protocol_version);
141                 tool_capabilities_s = tmp_os.str();
142         }
143         os << serializeString(tool_capabilities_s);
144         writeU16(os, groups.size());
145         for (ItemGroupList::const_iterator
146                         i = groups.begin(); i != groups.end(); ++i){
147                 os << serializeString(i->first);
148                 writeS16(os, i->second);
149         }
150         os << serializeString(node_placement_prediction);
151         os << serializeString(sound_place.name);
152         writeF1000(os, sound_place.gain);
153         writeF1000(os, range);
154         os << serializeString(sound_place_failed.name);
155         writeF1000(os, sound_place_failed.gain);
156 }
157
158 void ItemDefinition::deSerialize(std::istream &is)
159 {
160         // Reset everything
161         reset();
162
163         // Deserialize
164         int version = readU8(is);
165         if(version < 1 || version > 3)
166                 throw SerializationError("unsupported ItemDefinition version");
167         type = (enum ItemType)readU8(is);
168         name = deSerializeString(is);
169         description = deSerializeString(is);
170         inventory_image = deSerializeString(is);
171         wield_image = deSerializeString(is);
172         wield_scale = readV3F1000(is);
173         stack_max = readS16(is);
174         usable = readU8(is);
175         liquids_pointable = readU8(is);
176         std::string tool_capabilities_s = deSerializeString(is);
177         if(!tool_capabilities_s.empty())
178         {
179                 std::istringstream tmp_is(tool_capabilities_s, std::ios::binary);
180                 tool_capabilities = new ToolCapabilities;
181                 tool_capabilities->deSerialize(tmp_is);
182         }
183         groups.clear();
184         u32 groups_size = readU16(is);
185         for(u32 i=0; i<groups_size; i++){
186                 std::string name = deSerializeString(is);
187                 int value = readS16(is);
188                 groups[name] = value;
189         }
190         if(version == 1){
191                 // We cant be sure that node_placement_prediction is send in version 1
192                 try{
193                         node_placement_prediction = deSerializeString(is);
194                 }catch(SerializationError &e) {};
195                 // Set the old default sound
196                 sound_place.name = "default_place_node";
197                 sound_place.gain = 0.5;
198         } else if(version >= 2) {
199                 node_placement_prediction = deSerializeString(is);
200                 //deserializeSimpleSoundSpec(sound_place, is);
201                 sound_place.name = deSerializeString(is);
202                 sound_place.gain = readF1000(is);
203         }
204         if(version == 3) {
205                 range = readF1000(is);
206         }
207         // If you add anything here, insert it primarily inside the try-catch
208         // block to not need to increase the version.
209         try {
210                 sound_place_failed.name = deSerializeString(is);
211                 sound_place_failed.gain = readF1000(is);
212         } catch(SerializationError &e) {};
213 }
214
215 /*
216         CItemDefManager
217 */
218
219 // SUGG: Support chains of aliases?
220
221 class CItemDefManager: public IWritableItemDefManager
222 {
223 #ifndef SERVER
224         struct ClientCached
225         {
226                 video::ITexture *inventory_texture;
227                 scene::IMesh *wield_mesh;
228
229                 ClientCached():
230                         inventory_texture(NULL),
231                         wield_mesh(NULL)
232                 {}
233         };
234 #endif
235
236 public:
237         CItemDefManager()
238         {
239
240 #ifndef SERVER
241                 m_main_thread = thr_get_current_thread_id();
242 #endif
243                 clear();
244         }
245         virtual ~CItemDefManager()
246         {
247 #ifndef SERVER
248                 const std::vector<ClientCached*> &values = m_clientcached.getValues();
249                 for(std::vector<ClientCached*>::const_iterator
250                                 i = values.begin(); i != values.end(); ++i)
251                 {
252                         ClientCached *cc = *i;
253                         if (cc->wield_mesh)
254                                 cc->wield_mesh->drop();
255                         delete cc;
256                 }
257
258 #endif
259                 for (std::map<std::string, ItemDefinition*>::iterator iter =
260                                 m_item_definitions.begin(); iter != m_item_definitions.end();
261                                 ++iter) {
262                         delete iter->second;
263                 }
264                 m_item_definitions.clear();
265         }
266         virtual const ItemDefinition& get(const std::string &name_) const
267         {
268                 // Convert name according to possible alias
269                 std::string name = getAlias(name_);
270                 // Get the definition
271                 std::map<std::string, ItemDefinition*>::const_iterator i;
272                 i = m_item_definitions.find(name);
273                 if(i == m_item_definitions.end())
274                         i = m_item_definitions.find("unknown");
275                 assert(i != m_item_definitions.end());
276                 return *(i->second);
277         }
278         virtual std::string getAlias(const std::string &name) const
279         {
280                 StringMap::const_iterator it = m_aliases.find(name);
281                 if (it != m_aliases.end())
282                         return it->second;
283                 return name;
284         }
285         virtual std::set<std::string> getAll() const
286         {
287                 std::set<std::string> result;
288                 for(std::map<std::string, ItemDefinition *>::const_iterator
289                                 it = m_item_definitions.begin();
290                                 it != m_item_definitions.end(); ++it) {
291                         result.insert(it->first);
292                 }
293                 for (StringMap::const_iterator
294                                 it = m_aliases.begin();
295                                 it != m_aliases.end(); ++it) {
296                         result.insert(it->first);
297                 }
298                 return result;
299         }
300         virtual bool isKnown(const std::string &name_) const
301         {
302                 // Convert name according to possible alias
303                 std::string name = getAlias(name_);
304                 // Get the definition
305                 std::map<std::string, ItemDefinition*>::const_iterator i;
306                 return m_item_definitions.find(name) != m_item_definitions.end();
307         }
308 #ifndef SERVER
309 public:
310         ClientCached* createClientCachedDirect(const std::string &name,
311                         Client *client) const
312         {
313                 infostream<<"Lazily creating item texture and mesh for \""
314                                 <<name<<"\""<<std::endl;
315
316                 // This is not thread-safe
317                 sanity_check(thr_is_current_thread(m_main_thread));
318
319                 // Skip if already in cache
320                 ClientCached *cc = NULL;
321                 m_clientcached.get(name, &cc);
322                 if(cc)
323                         return cc;
324
325                 ITextureSource *tsrc = client->getTextureSource();
326                 const ItemDefinition &def = get(name);
327
328                 // Create new ClientCached
329                 cc = new ClientCached();
330
331                 // Create an inventory texture
332                 cc->inventory_texture = NULL;
333                 if(def.inventory_image != "")
334                         cc->inventory_texture = tsrc->getTexture(def.inventory_image);
335
336                 ItemStack item = ItemStack();
337                 item.name = def.name;
338
339                 scene::IMesh *mesh = getItemMesh(client, item);
340                 cc->wield_mesh = mesh;
341
342                 // Put in cache
343                 m_clientcached.set(name, cc);
344
345                 return cc;
346         }
347         ClientCached* getClientCached(const std::string &name,
348                         Client *client) const
349         {
350                 ClientCached *cc = NULL;
351                 m_clientcached.get(name, &cc);
352                 if(cc)
353                         return cc;
354
355                 if(thr_is_current_thread(m_main_thread))
356                 {
357                         return createClientCachedDirect(name, client);
358                 }
359                 else
360                 {
361                         // We're gonna ask the result to be put into here
362                         static ResultQueue<std::string, ClientCached*, u8, u8> result_queue;
363
364                         // Throw a request in
365                         m_get_clientcached_queue.add(name, 0, 0, &result_queue);
366                         try{
367                                 while(true) {
368                                         // Wait result for a second
369                                         GetResult<std::string, ClientCached*, u8, u8>
370                                                 result = result_queue.pop_front(1000);
371
372                                         if (result.key == name) {
373                                                 return result.item;
374                                         }
375                                 }
376                         }
377                         catch(ItemNotFoundException &e)
378                         {
379                                 errorstream<<"Waiting for clientcached " << name << " timed out."<<std::endl;
380                                 return &m_dummy_clientcached;
381                         }
382                 }
383         }
384         // Get item inventory texture
385         virtual video::ITexture* getInventoryTexture(const std::string &name,
386                         Client *client) const
387         {
388                 ClientCached *cc = getClientCached(name, client);
389                 if(!cc)
390                         return NULL;
391                 return cc->inventory_texture;
392         }
393         // Get item wield mesh
394         virtual scene::IMesh* getWieldMesh(const std::string &name,
395                         Client *client) const
396         {
397                 ClientCached *cc = getClientCached(name, client);
398                 if(!cc)
399                         return NULL;
400                 return cc->wield_mesh;
401         }
402 #endif
403         void clear()
404         {
405                 for(std::map<std::string, ItemDefinition*>::const_iterator
406                                 i = m_item_definitions.begin();
407                                 i != m_item_definitions.end(); ++i)
408                 {
409                         delete i->second;
410                 }
411                 m_item_definitions.clear();
412                 m_aliases.clear();
413
414                 // Add the four builtin items:
415                 //   "" is the hand
416                 //   "unknown" is returned whenever an undefined item
417                 //     is accessed (is also the unknown node)
418                 //   "air" is the air node
419                 //   "ignore" is the ignore node
420
421                 ItemDefinition* hand_def = new ItemDefinition;
422                 hand_def->name = "";
423                 hand_def->wield_image = "wieldhand.png";
424                 hand_def->tool_capabilities = new ToolCapabilities;
425                 m_item_definitions.insert(std::make_pair("", hand_def));
426
427                 ItemDefinition* unknown_def = new ItemDefinition;
428                 unknown_def->type = ITEM_NODE;
429                 unknown_def->name = "unknown";
430                 m_item_definitions.insert(std::make_pair("unknown", unknown_def));
431
432                 ItemDefinition* air_def = new ItemDefinition;
433                 air_def->type = ITEM_NODE;
434                 air_def->name = "air";
435                 m_item_definitions.insert(std::make_pair("air", air_def));
436
437                 ItemDefinition* ignore_def = new ItemDefinition;
438                 ignore_def->type = ITEM_NODE;
439                 ignore_def->name = "ignore";
440                 m_item_definitions.insert(std::make_pair("ignore", ignore_def));
441         }
442         virtual void registerItem(const ItemDefinition &def)
443         {
444                 verbosestream<<"ItemDefManager: registering \""<<def.name<<"\""<<std::endl;
445                 // Ensure that the "" item (the hand) always has ToolCapabilities
446                 if(def.name == "")
447                         FATAL_ERROR_IF(!def.tool_capabilities, "Hand does not have ToolCapabilities");
448
449                 if(m_item_definitions.count(def.name) == 0)
450                         m_item_definitions[def.name] = new ItemDefinition(def);
451                 else
452                         *(m_item_definitions[def.name]) = def;
453
454                 // Remove conflicting alias if it exists
455                 bool alias_removed = (m_aliases.erase(def.name) != 0);
456                 if(alias_removed)
457                         infostream<<"ItemDefManager: erased alias "<<def.name
458                                         <<" because item was defined"<<std::endl;
459         }
460         virtual void unregisterItem(const std::string &name)
461         {
462                 verbosestream<<"ItemDefManager: unregistering \""<<name<<"\""<<std::endl;
463
464                 delete m_item_definitions[name];
465                 m_item_definitions.erase(name);
466         }
467         virtual void registerAlias(const std::string &name,
468                         const std::string &convert_to)
469         {
470                 if (m_item_definitions.find(name) == m_item_definitions.end()) {
471                         verbosestream<<"ItemDefManager: setting alias "<<name
472                                 <<" -> "<<convert_to<<std::endl;
473                         m_aliases[name] = convert_to;
474                 }
475         }
476         void serialize(std::ostream &os, u16 protocol_version)
477         {
478                 writeU8(os, 0); // version
479                 u16 count = m_item_definitions.size();
480                 writeU16(os, count);
481
482                 for (std::map<std::string, ItemDefinition *>::const_iterator
483                                 it = m_item_definitions.begin();
484                                 it != m_item_definitions.end(); ++it) {
485                         ItemDefinition *def = it->second;
486                         // Serialize ItemDefinition and write wrapped in a string
487                         std::ostringstream tmp_os(std::ios::binary);
488                         def->serialize(tmp_os, protocol_version);
489                         os << serializeString(tmp_os.str());
490                 }
491
492                 writeU16(os, m_aliases.size());
493
494                 for (StringMap::const_iterator
495                                 it = m_aliases.begin();
496                                 it != m_aliases.end(); ++it) {
497                         os << serializeString(it->first);
498                         os << serializeString(it->second);
499                 }
500         }
501         void deSerialize(std::istream &is)
502         {
503                 // Clear everything
504                 clear();
505                 // Deserialize
506                 int version = readU8(is);
507                 if(version != 0)
508                         throw SerializationError("unsupported ItemDefManager version");
509                 u16 count = readU16(is);
510                 for(u16 i=0; i<count; i++)
511                 {
512                         // Deserialize a string and grab an ItemDefinition from it
513                         std::istringstream tmp_is(deSerializeString(is), std::ios::binary);
514                         ItemDefinition def;
515                         def.deSerialize(tmp_is);
516                         // Register
517                         registerItem(def);
518                 }
519                 u16 num_aliases = readU16(is);
520                 for(u16 i=0; i<num_aliases; i++)
521                 {
522                         std::string name = deSerializeString(is);
523                         std::string convert_to = deSerializeString(is);
524                         registerAlias(name, convert_to);
525                 }
526         }
527         void processQueue(IGameDef *gamedef)
528         {
529 #ifndef SERVER
530                 //NOTE this is only thread safe for ONE consumer thread!
531                 while(!m_get_clientcached_queue.empty())
532                 {
533                         GetRequest<std::string, ClientCached*, u8, u8>
534                                         request = m_get_clientcached_queue.pop();
535
536                         m_get_clientcached_queue.pushResult(request,
537                                         createClientCachedDirect(request.key, (Client *)gamedef));
538                 }
539 #endif
540         }
541 private:
542         // Key is name
543         std::map<std::string, ItemDefinition*> m_item_definitions;
544         // Aliases
545         StringMap m_aliases;
546 #ifndef SERVER
547         // The id of the thread that is allowed to use irrlicht directly
548         threadid_t m_main_thread;
549         // A reference to this can be returned when nothing is found, to avoid NULLs
550         mutable ClientCached m_dummy_clientcached;
551         // Cached textures and meshes
552         mutable MutexedMap<std::string, ClientCached*> m_clientcached;
553         // Queued clientcached fetches (to be processed by the main thread)
554         mutable RequestQueue<std::string, ClientCached*, u8, u8> m_get_clientcached_queue;
555 #endif
556 };
557
558 IWritableItemDefManager* createItemDefManager()
559 {
560         return new CItemDefManager();
561 }