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