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