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