Tooltips: Unify the tooltip[] and list[] description tooltip display functions (...
[oweals/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         palette_image = def.palette_image;
86         color = def.color;
87         return *this;
88 }
89
90 ItemDefinition::~ItemDefinition()
91 {
92         reset();
93 }
94
95 void ItemDefinition::resetInitial()
96 {
97         // Initialize pointers to NULL so reset() does not delete undefined pointers
98         tool_capabilities = NULL;
99         reset();
100 }
101
102 void ItemDefinition::reset()
103 {
104         type = ITEM_NONE;
105         name = "";
106         description = "";
107         inventory_image = "";
108         wield_image = "";
109         palette_image = "";
110         color = video::SColor(0xFFFFFFFF);
111         wield_scale = v3f(1.0, 1.0, 1.0);
112         stack_max = 99;
113         usable = false;
114         liquids_pointable = false;
115         if(tool_capabilities)
116         {
117                 delete tool_capabilities;
118                 tool_capabilities = NULL;
119         }
120         groups.clear();
121         sound_place = SimpleSoundSpec();
122         sound_place_failed = SimpleSoundSpec();
123         range = -1;
124
125         node_placement_prediction = "";
126 }
127
128 void ItemDefinition::serialize(std::ostream &os, u16 protocol_version) const
129 {
130
131         writeU8(os, 3); // version (proto > 20)
132         writeU8(os, type);
133         os << serializeString(name);
134         os << serializeString(description);
135         os << serializeString(inventory_image);
136         os << serializeString(wield_image);
137         writeV3F1000(os, wield_scale);
138         writeS16(os, stack_max);
139         writeU8(os, usable);
140         writeU8(os, liquids_pointable);
141         std::string tool_capabilities_s = "";
142         if(tool_capabilities){
143                 std::ostringstream tmp_os(std::ios::binary);
144                 tool_capabilities->serialize(tmp_os, protocol_version);
145                 tool_capabilities_s = tmp_os.str();
146         }
147         os << serializeString(tool_capabilities_s);
148         writeU16(os, groups.size());
149         for (ItemGroupList::const_iterator
150                         i = groups.begin(); i != groups.end(); ++i){
151                 os << serializeString(i->first);
152                 writeS16(os, i->second);
153         }
154         os << serializeString(node_placement_prediction);
155         os << serializeString(sound_place.name);
156         writeF1000(os, sound_place.gain);
157         writeF1000(os, range);
158         os << serializeString(sound_place_failed.name);
159         writeF1000(os, sound_place_failed.gain);
160         os << serializeString(palette_image);
161         writeU32(os, color.color);
162 }
163
164 void ItemDefinition::deSerialize(std::istream &is)
165 {
166         // Reset everything
167         reset();
168
169         // Deserialize
170         int version = readU8(is);
171         if(version < 1 || version > 3)
172                 throw SerializationError("unsupported ItemDefinition version");
173         type = (enum ItemType)readU8(is);
174         name = deSerializeString(is);
175         description = deSerializeString(is);
176         inventory_image = deSerializeString(is);
177         wield_image = deSerializeString(is);
178         wield_scale = readV3F1000(is);
179         stack_max = readS16(is);
180         usable = readU8(is);
181         liquids_pointable = readU8(is);
182         std::string tool_capabilities_s = deSerializeString(is);
183         if(!tool_capabilities_s.empty())
184         {
185                 std::istringstream tmp_is(tool_capabilities_s, std::ios::binary);
186                 tool_capabilities = new ToolCapabilities;
187                 tool_capabilities->deSerialize(tmp_is);
188         }
189         groups.clear();
190         u32 groups_size = readU16(is);
191         for(u32 i=0; i<groups_size; i++){
192                 std::string name = deSerializeString(is);
193                 int value = readS16(is);
194                 groups[name] = value;
195         }
196         if(version == 1){
197                 // We cant be sure that node_placement_prediction is send in version 1
198                 try{
199                         node_placement_prediction = deSerializeString(is);
200                 }catch(SerializationError &e) {};
201                 // Set the old default sound
202                 sound_place.name = "default_place_node";
203                 sound_place.gain = 0.5;
204         } else if(version >= 2) {
205                 node_placement_prediction = deSerializeString(is);
206                 //deserializeSimpleSoundSpec(sound_place, is);
207                 sound_place.name = deSerializeString(is);
208                 sound_place.gain = readF1000(is);
209         }
210         if(version == 3) {
211                 range = readF1000(is);
212         }
213         // If you add anything here, insert it primarily inside the try-catch
214         // block to not need to increase the version.
215         try {
216                 sound_place_failed.name = deSerializeString(is);
217                 sound_place_failed.gain = readF1000(is);
218                 palette_image = deSerializeString(is);
219                 color.set(readU32(is));
220         } catch(SerializationError &e) {};
221 }
222
223 /*
224         CItemDefManager
225 */
226
227 // SUGG: Support chains of aliases?
228
229 class CItemDefManager: public IWritableItemDefManager
230 {
231 #ifndef SERVER
232         struct ClientCached
233         {
234                 video::ITexture *inventory_texture;
235                 ItemMesh wield_mesh;
236                 Palette *palette;
237
238                 ClientCached():
239                         inventory_texture(NULL),
240                         wield_mesh(),
241                         palette(NULL)
242                 {}
243         };
244 #endif
245
246 public:
247         CItemDefManager()
248         {
249
250 #ifndef SERVER
251                 m_main_thread = thr_get_current_thread_id();
252 #endif
253                 clear();
254         }
255         virtual ~CItemDefManager()
256         {
257 #ifndef SERVER
258                 const std::vector<ClientCached*> &values = m_clientcached.getValues();
259                 for(std::vector<ClientCached*>::const_iterator
260                                 i = values.begin(); i != values.end(); ++i)
261                 {
262                         ClientCached *cc = *i;
263                         if (cc->wield_mesh.mesh)
264                                 cc->wield_mesh.mesh->drop();
265                         delete cc;
266                 }
267
268 #endif
269                 for (std::map<std::string, ItemDefinition*>::iterator iter =
270                                 m_item_definitions.begin(); iter != m_item_definitions.end();
271                                 ++iter) {
272                         delete iter->second;
273                 }
274                 m_item_definitions.clear();
275         }
276         virtual const ItemDefinition& get(const std::string &name_) const
277         {
278                 // Convert name according to possible alias
279                 std::string name = getAlias(name_);
280                 // Get the definition
281                 std::map<std::string, ItemDefinition*>::const_iterator i;
282                 i = m_item_definitions.find(name);
283                 if(i == m_item_definitions.end())
284                         i = m_item_definitions.find("unknown");
285                 assert(i != m_item_definitions.end());
286                 return *(i->second);
287         }
288         virtual const std::string &getAlias(const std::string &name) const
289         {
290                 StringMap::const_iterator it = m_aliases.find(name);
291                 if (it != m_aliases.end())
292                         return it->second;
293                 return name;
294         }
295         virtual void getAll(std::set<std::string> &result) const
296         {
297                 result.clear();
298                 for(std::map<std::string, ItemDefinition *>::const_iterator
299                                 it = m_item_definitions.begin();
300                                 it != m_item_definitions.end(); ++it) {
301                         result.insert(it->first);
302                 }
303                 for (StringMap::const_iterator
304                                 it = m_aliases.begin();
305                                 it != m_aliases.end(); ++it) {
306                         result.insert(it->first);
307                 }
308         }
309         virtual bool isKnown(const std::string &name_) const
310         {
311                 // Convert name according to possible alias
312                 std::string name = getAlias(name_);
313                 // Get the definition
314                 std::map<std::string, ItemDefinition*>::const_iterator i;
315                 return m_item_definitions.find(name) != m_item_definitions.end();
316         }
317 #ifndef SERVER
318 public:
319         ClientCached* createClientCachedDirect(const std::string &name,
320                         Client *client) const
321         {
322                 infostream<<"Lazily creating item texture and mesh for \""
323                                 <<name<<"\""<<std::endl;
324
325                 // This is not thread-safe
326                 sanity_check(thr_is_current_thread(m_main_thread));
327
328                 // Skip if already in cache
329                 ClientCached *cc = NULL;
330                 m_clientcached.get(name, &cc);
331                 if(cc)
332                         return cc;
333
334                 ITextureSource *tsrc = client->getTextureSource();
335                 const ItemDefinition &def = get(name);
336
337                 // Create new ClientCached
338                 cc = new ClientCached();
339
340                 // Create an inventory texture
341                 cc->inventory_texture = NULL;
342                 if(def.inventory_image != "")
343                         cc->inventory_texture = tsrc->getTexture(def.inventory_image);
344
345                 ItemStack item = ItemStack();
346                 item.name = def.name;
347
348                 getItemMesh(client, item, &(cc->wield_mesh));
349
350                 cc->palette = tsrc->getPalette(def.palette_image);
351
352                 // Put in cache
353                 m_clientcached.set(name, cc);
354
355                 return cc;
356         }
357         ClientCached* getClientCached(const std::string &name,
358                         Client *client) const
359         {
360                 ClientCached *cc = NULL;
361                 m_clientcached.get(name, &cc);
362                 if(cc)
363                         return cc;
364
365                 if(thr_is_current_thread(m_main_thread))
366                 {
367                         return createClientCachedDirect(name, client);
368                 }
369                 else
370                 {
371                         // We're gonna ask the result to be put into here
372                         static ResultQueue<std::string, ClientCached*, u8, u8> result_queue;
373
374                         // Throw a request in
375                         m_get_clientcached_queue.add(name, 0, 0, &result_queue);
376                         try{
377                                 while(true) {
378                                         // Wait result for a second
379                                         GetResult<std::string, ClientCached*, u8, u8>
380                                                 result = result_queue.pop_front(1000);
381
382                                         if (result.key == name) {
383                                                 return result.item;
384                                         }
385                                 }
386                         }
387                         catch(ItemNotFoundException &e)
388                         {
389                                 errorstream<<"Waiting for clientcached " << name << " timed out."<<std::endl;
390                                 return &m_dummy_clientcached;
391                         }
392                 }
393         }
394         // Get item inventory texture
395         virtual video::ITexture* getInventoryTexture(const std::string &name,
396                         Client *client) const
397         {
398                 ClientCached *cc = getClientCached(name, client);
399                 if(!cc)
400                         return NULL;
401                 return cc->inventory_texture;
402         }
403         // Get item wield mesh
404         virtual ItemMesh* getWieldMesh(const std::string &name,
405                         Client *client) const
406         {
407                 ClientCached *cc = getClientCached(name, client);
408                 if(!cc)
409                         return NULL;
410                 return &(cc->wield_mesh);
411         }
412
413         // Get item palette
414         virtual Palette* getPalette(const std::string &name,
415                         Client *client) const
416         {
417                 ClientCached *cc = getClientCached(name, client);
418                 if(!cc)
419                         return NULL;
420                 return cc->palette;
421         }
422
423         virtual video::SColor getItemstackColor(const ItemStack &stack,
424                 Client *client) const
425         {
426                 // Look for direct color definition
427                 const std::string &colorstring = stack.metadata.getString("color", 0);
428                 video::SColor directcolor;
429                 if ((colorstring != "")
430                                 && parseColorString(colorstring, directcolor, true))
431                         return directcolor;
432                 // See if there is a palette
433                 Palette *palette = getPalette(stack.name, client);
434                 const std::string &index = stack.metadata.getString("palette_index", 0);
435                 if ((palette != NULL) && (index != ""))
436                         return (*palette)[mystoi(index, 0, 255)];
437                 // Fallback color
438                 return get(stack.name).color;
439         }
440 #endif
441         void clear()
442         {
443                 for(std::map<std::string, ItemDefinition*>::const_iterator
444                                 i = m_item_definitions.begin();
445                                 i != m_item_definitions.end(); ++i)
446                 {
447                         delete i->second;
448                 }
449                 m_item_definitions.clear();
450                 m_aliases.clear();
451
452                 // Add the four builtin items:
453                 //   "" is the hand
454                 //   "unknown" is returned whenever an undefined item
455                 //     is accessed (is also the unknown node)
456                 //   "air" is the air node
457                 //   "ignore" is the ignore node
458
459                 ItemDefinition* hand_def = new ItemDefinition;
460                 hand_def->name = "";
461                 hand_def->wield_image = "wieldhand.png";
462                 hand_def->tool_capabilities = new ToolCapabilities;
463                 m_item_definitions.insert(std::make_pair("", hand_def));
464
465                 ItemDefinition* unknown_def = new ItemDefinition;
466                 unknown_def->type = ITEM_NODE;
467                 unknown_def->name = "unknown";
468                 m_item_definitions.insert(std::make_pair("unknown", unknown_def));
469
470                 ItemDefinition* air_def = new ItemDefinition;
471                 air_def->type = ITEM_NODE;
472                 air_def->name = "air";
473                 m_item_definitions.insert(std::make_pair("air", air_def));
474
475                 ItemDefinition* ignore_def = new ItemDefinition;
476                 ignore_def->type = ITEM_NODE;
477                 ignore_def->name = "ignore";
478                 m_item_definitions.insert(std::make_pair("ignore", ignore_def));
479         }
480         virtual void registerItem(const ItemDefinition &def)
481         {
482                 verbosestream<<"ItemDefManager: registering \""<<def.name<<"\""<<std::endl;
483                 // Ensure that the "" item (the hand) always has ToolCapabilities
484                 if(def.name == "")
485                         FATAL_ERROR_IF(!def.tool_capabilities, "Hand does not have ToolCapabilities");
486
487                 if(m_item_definitions.count(def.name) == 0)
488                         m_item_definitions[def.name] = new ItemDefinition(def);
489                 else
490                         *(m_item_definitions[def.name]) = def;
491
492                 // Remove conflicting alias if it exists
493                 bool alias_removed = (m_aliases.erase(def.name) != 0);
494                 if(alias_removed)
495                         infostream<<"ItemDefManager: erased alias "<<def.name
496                                         <<" because item was defined"<<std::endl;
497         }
498         virtual void unregisterItem(const std::string &name)
499         {
500                 verbosestream<<"ItemDefManager: unregistering \""<<name<<"\""<<std::endl;
501
502                 delete m_item_definitions[name];
503                 m_item_definitions.erase(name);
504         }
505         virtual void registerAlias(const std::string &name,
506                         const std::string &convert_to)
507         {
508                 if (m_item_definitions.find(name) == m_item_definitions.end()) {
509                         verbosestream<<"ItemDefManager: setting alias "<<name
510                                 <<" -> "<<convert_to<<std::endl;
511                         m_aliases[name] = convert_to;
512                 }
513         }
514         void serialize(std::ostream &os, u16 protocol_version)
515         {
516                 writeU8(os, 0); // version
517                 u16 count = m_item_definitions.size();
518                 writeU16(os, count);
519
520                 for (std::map<std::string, ItemDefinition *>::const_iterator
521                                 it = m_item_definitions.begin();
522                                 it != m_item_definitions.end(); ++it) {
523                         ItemDefinition *def = it->second;
524                         // Serialize ItemDefinition and write wrapped in a string
525                         std::ostringstream tmp_os(std::ios::binary);
526                         def->serialize(tmp_os, protocol_version);
527                         os << serializeString(tmp_os.str());
528                 }
529
530                 writeU16(os, m_aliases.size());
531
532                 for (StringMap::const_iterator
533                                 it = m_aliases.begin();
534                                 it != m_aliases.end(); ++it) {
535                         os << serializeString(it->first);
536                         os << serializeString(it->second);
537                 }
538         }
539         void deSerialize(std::istream &is)
540         {
541                 // Clear everything
542                 clear();
543                 // Deserialize
544                 int version = readU8(is);
545                 if(version != 0)
546                         throw SerializationError("unsupported ItemDefManager version");
547                 u16 count = readU16(is);
548                 for(u16 i=0; i<count; i++)
549                 {
550                         // Deserialize a string and grab an ItemDefinition from it
551                         std::istringstream tmp_is(deSerializeString(is), std::ios::binary);
552                         ItemDefinition def;
553                         def.deSerialize(tmp_is);
554                         // Register
555                         registerItem(def);
556                 }
557                 u16 num_aliases = readU16(is);
558                 for(u16 i=0; i<num_aliases; i++)
559                 {
560                         std::string name = deSerializeString(is);
561                         std::string convert_to = deSerializeString(is);
562                         registerAlias(name, convert_to);
563                 }
564         }
565         void processQueue(IGameDef *gamedef)
566         {
567 #ifndef SERVER
568                 //NOTE this is only thread safe for ONE consumer thread!
569                 while(!m_get_clientcached_queue.empty())
570                 {
571                         GetRequest<std::string, ClientCached*, u8, u8>
572                                         request = m_get_clientcached_queue.pop();
573
574                         m_get_clientcached_queue.pushResult(request,
575                                         createClientCachedDirect(request.key, (Client *)gamedef));
576                 }
577 #endif
578         }
579 private:
580         // Key is name
581         std::map<std::string, ItemDefinition*> m_item_definitions;
582         // Aliases
583         StringMap m_aliases;
584 #ifndef SERVER
585         // The id of the thread that is allowed to use irrlicht directly
586         threadid_t m_main_thread;
587         // A reference to this can be returned when nothing is found, to avoid NULLs
588         mutable ClientCached m_dummy_clientcached;
589         // Cached textures and meshes
590         mutable MutexedMap<std::string, ClientCached*> m_clientcached;
591         // Queued clientcached fetches (to be processed by the main thread)
592         mutable RequestQueue<std::string, ClientCached*, u8, u8> m_get_clientcached_queue;
593 #endif
594 };
595
596 IWritableItemDefManager* createItemDefManager()
597 {
598         return new CItemDefManager();
599 }