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