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