]> git.lizzy.rs Git - minetest.git/blob - src/itemdef.cpp
Fix multicaller support in RequestQueue
[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 "gamedef.h"
24 #include "nodedef.h"
25 #include "tool.h"
26 #include "inventory.h"
27 #ifndef SERVER
28 #include "mapblock_mesh.h"
29 #include "mesh.h"
30 #include "tile.h"
31 #endif
32 #include "log.h"
33 #include "main.h" // g_settings
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         inventory_image = def.inventory_image;
66         wield_image = def.wield_image;
67         wield_scale = def.wield_scale;
68         stack_max = def.stack_max;
69         usable = def.usable;
70         liquids_pointable = def.liquids_pointable;
71         if(def.tool_capabilities)
72         {
73                 tool_capabilities = new ToolCapabilities(
74                                 *def.tool_capabilities);
75         }
76         groups = def.groups;
77         node_placement_prediction = def.node_placement_prediction;
78         sound_place = def.sound_place;
79         range = def.range;
80         return *this;
81 }
82
83 ItemDefinition::~ItemDefinition()
84 {
85         reset();
86 }
87
88 void ItemDefinition::resetInitial()
89 {
90         // Initialize pointers to NULL so reset() does not delete undefined pointers
91         tool_capabilities = NULL;
92         reset();
93 }
94
95 void ItemDefinition::reset()
96 {
97         type = ITEM_NONE;
98         name = "";
99         description = "";
100         inventory_image = "";
101         wield_image = "";
102         wield_scale = v3f(1.0, 1.0, 1.0);
103         stack_max = 99;
104         usable = false;
105         liquids_pointable = false;
106         if(tool_capabilities)
107         {
108                 delete tool_capabilities;
109                 tool_capabilities = NULL;
110         }
111         groups.clear();
112         sound_place = SimpleSoundSpec();
113         range = -1;
114
115         node_placement_prediction = "";
116 }
117
118 void ItemDefinition::serialize(std::ostream &os, u16 protocol_version) const
119 {
120         if(protocol_version <= 17)
121                 writeU8(os, 1); // version
122         else if(protocol_version <= 20)
123                 writeU8(os, 2); // version
124         else
125                 writeU8(os, 3); // version
126         writeU8(os, type);
127         os<<serializeString(name);
128         os<<serializeString(description);
129         os<<serializeString(inventory_image);
130         os<<serializeString(wield_image);
131         writeV3F1000(os, wield_scale);
132         writeS16(os, stack_max);
133         writeU8(os, usable);
134         writeU8(os, liquids_pointable);
135         std::string tool_capabilities_s = "";
136         if(tool_capabilities){
137                 std::ostringstream tmp_os(std::ios::binary);
138                 tool_capabilities->serialize(tmp_os, protocol_version);
139                 tool_capabilities_s = tmp_os.str();
140         }
141         os<<serializeString(tool_capabilities_s);
142         writeU16(os, groups.size());
143         for(std::map<std::string, int>::const_iterator
144                         i = groups.begin(); i != groups.end(); i++){
145                 os<<serializeString(i->first);
146                 writeS16(os, i->second);
147         }
148         os<<serializeString(node_placement_prediction);
149         if(protocol_version > 17){
150                 //serializeSimpleSoundSpec(sound_place, os);
151                 os<<serializeString(sound_place.name);
152                 writeF1000(os, sound_place.gain);
153         }
154         if(protocol_version > 20){
155                 writeF1000(os, range);
156         }
157 }
158
159 void ItemDefinition::deSerialize(std::istream &is)
160 {
161         // Reset everything
162         reset();
163
164         // Deserialize
165         int version = readU8(is);
166         if(version < 1 || version > 3)
167                 throw SerializationError("unsupported ItemDefinition version");
168         type = (enum ItemType)readU8(is);
169         name = deSerializeString(is);
170         description = deSerializeString(is);
171         inventory_image = deSerializeString(is);
172         wield_image = deSerializeString(is);
173         wield_scale = readV3F1000(is);
174         stack_max = readS16(is);
175         usable = readU8(is);
176         liquids_pointable = readU8(is);
177         std::string tool_capabilities_s = deSerializeString(is);
178         if(!tool_capabilities_s.empty())
179         {
180                 std::istringstream tmp_is(tool_capabilities_s, std::ios::binary);
181                 tool_capabilities = new ToolCapabilities;
182                 tool_capabilities->deSerialize(tmp_is);
183         }
184         groups.clear();
185         u32 groups_size = readU16(is);
186         for(u32 i=0; i<groups_size; i++){
187                 std::string name = deSerializeString(is);
188                 int value = readS16(is);
189                 groups[name] = value;
190         }
191         if(version == 1){
192                 // We cant be sure that node_placement_prediction is send in version 1
193                 try{
194                         node_placement_prediction = deSerializeString(is);
195                 }catch(SerializationError &e) {};
196                 // Set the old default sound
197                 sound_place.name = "default_place_node";
198                 sound_place.gain = 0.5;
199         } else if(version >= 2) {
200                 node_placement_prediction = deSerializeString(is);
201                 //deserializeSimpleSoundSpec(sound_place, is);
202                 sound_place.name = deSerializeString(is);
203                 sound_place.gain = readF1000(is);
204         }
205         if(version == 3) {
206                 range = readF1000(is);
207         }
208         // If you add anything here, insert it primarily inside the try-catch
209         // block to not need to increase the version.
210         try{
211         }catch(SerializationError &e) {};
212 }
213
214 /*
215         CItemDefManager
216 */
217
218 // SUGG: Support chains of aliases?
219
220 class CItemDefManager: public IWritableItemDefManager
221 {
222 #ifndef SERVER
223         struct ClientCached
224         {
225                 video::ITexture *inventory_texture;
226                 scene::IMesh *wield_mesh;
227
228                 ClientCached():
229                         inventory_texture(NULL),
230                         wield_mesh(NULL)
231                 {}
232         };
233 #endif
234
235 public:
236         CItemDefManager()
237         {
238
239 #ifndef SERVER
240                 m_main_thread = get_current_thread_id();
241 #endif
242                 clear();
243         }
244         virtual ~CItemDefManager()
245         {
246 #ifndef SERVER
247                 const std::list<ClientCached*> &values = m_clientcached.getValues();
248                 for(std::list<ClientCached*>::const_iterator
249                                 i = values.begin(); i != values.end(); ++i)
250                 {
251                         ClientCached *cc = *i;
252                         if (cc->wield_mesh)
253                                 cc->wield_mesh->drop();
254                         delete cc;
255                 }
256
257 #endif
258                 for (std::map<std::string, ItemDefinition*>::iterator iter =
259                                 m_item_definitions.begin(); iter != m_item_definitions.end();
260                                 iter ++) {
261                         delete iter->second;
262                 }
263                 m_item_definitions.clear();
264         }
265         virtual const ItemDefinition& get(const std::string &name_) const
266         {
267                 // Convert name according to possible alias
268                 std::string name = getAlias(name_);
269                 // Get the definition
270                 std::map<std::string, ItemDefinition*>::const_iterator i;
271                 i = m_item_definitions.find(name);
272                 if(i == m_item_definitions.end())
273                         i = m_item_definitions.find("unknown");
274                 assert(i != m_item_definitions.end());
275                 return *(i->second);
276         }
277         virtual std::string getAlias(const std::string &name) const
278         {
279                 std::map<std::string, std::string>::const_iterator i;
280                 i = m_aliases.find(name);
281                 if(i != m_aliases.end())
282                         return i->second;
283                 return name;
284         }
285         virtual std::set<std::string> getAll() const
286         {
287                 std::set<std::string> result;
288                 for(std::map<std::string, ItemDefinition*>::const_iterator
289                                 i = m_item_definitions.begin();
290                                 i != m_item_definitions.end(); i++)
291                 {
292                         result.insert(i->first);
293                 }
294                 for(std::map<std::string, std::string>::const_iterator
295                                 i = m_aliases.begin();
296                                 i != m_aliases.end(); i++)
297                 {
298                         result.insert(i->first);
299                 }
300                 return result;
301         }
302         virtual bool isKnown(const std::string &name_) const
303         {
304                 // Convert name according to possible alias
305                 std::string name = getAlias(name_);
306                 // Get the definition
307                 std::map<std::string, ItemDefinition*>::const_iterator i;
308                 return m_item_definitions.find(name) != m_item_definitions.end();
309         }
310 #ifndef SERVER
311 public:
312         ClientCached* createClientCachedDirect(const std::string &name,
313                         IGameDef *gamedef) const
314         {
315                 infostream<<"Lazily creating item texture and mesh for \""
316                                 <<name<<"\""<<std::endl;
317
318                 // This is not thread-safe
319                 assert(get_current_thread_id() == m_main_thread);
320
321                 // Skip if already in cache
322                 ClientCached *cc = NULL;
323                 m_clientcached.get(name, &cc);
324                 if(cc)
325                         return cc;
326
327                 ITextureSource *tsrc = gamedef->getTextureSource();
328                 INodeDefManager *nodedef = gamedef->getNodeDefManager();
329                 IrrlichtDevice *device = tsrc->getDevice();
330                 video::IVideoDriver *driver = device->getVideoDriver();
331                 const ItemDefinition *def = &get(name);
332
333                 // Create new ClientCached
334                 cc = new ClientCached();
335
336                 bool need_node_mesh = false;
337
338                 // Create an inventory texture
339                 cc->inventory_texture = NULL;
340                 if(def->inventory_image != "")
341                 {
342                         cc->inventory_texture = tsrc->getTexture(def->inventory_image);
343                 }
344                 else if(def->type == ITEM_NODE)
345                 {
346                         need_node_mesh = true;
347                 }
348
349                 // Create a wield mesh
350                 assert(cc->wield_mesh == NULL);
351                 if(def->type == ITEM_NODE && def->wield_image == "")
352                 {
353                         need_node_mesh = true;
354                 }
355                 else if(def->wield_image != "" || def->inventory_image != "")
356                 {
357                         // Extrude the wield image into a mesh
358
359                         std::string imagename;
360                         if(def->wield_image != "")
361                                 imagename = def->wield_image;
362                         else
363                                 imagename = def->inventory_image;
364
365                         cc->wield_mesh = createExtrudedMesh(
366                                         tsrc->getTexture(imagename),
367                                         driver,
368                                         def->wield_scale * v3f(40.0, 40.0, 4.0));
369                         if(cc->wield_mesh == NULL)
370                         {
371                                 infostream<<"ItemDefManager: WARNING: "
372                                         <<"updateTexturesAndMeshes(): "
373                                         <<"Unable to create extruded mesh for item "
374                                         <<def->name<<std::endl;
375                         }
376                 }
377
378                 if(need_node_mesh)
379                 {
380                         /*
381                                 Get node properties
382                         */
383                         content_t id = nodedef->getId(def->name);
384                         const ContentFeatures &f = nodedef->get(id);
385
386                         u8 param1 = 0;
387                         if(f.param_type == CPT_LIGHT)
388                                 param1 = 0xee;
389
390                         /*
391                                 Make a mesh from the node
392                         */
393                         MeshMakeData mesh_make_data(gamedef);
394                         MapNode mesh_make_node(id, param1, 0);
395                         mesh_make_data.fillSingleNode(&mesh_make_node);
396                         MapBlockMesh mapblock_mesh(&mesh_make_data);
397
398                         scene::IMesh *node_mesh = mapblock_mesh.getMesh();
399                         assert(node_mesh);
400                         video::SColor c(255, 255, 255, 255);
401                         if(g_settings->getBool("enable_shaders"))
402                                 c = MapBlock_LightColor(255, 0xffff, decode_light(f.light_source));
403                         setMeshColor(node_mesh, c);
404
405                         /*
406                                 Scale and translate the mesh so it's a unit cube
407                                 centered on the origin
408                         */
409                         scaleMesh(node_mesh, v3f(1.0/BS, 1.0/BS, 1.0/BS));
410                         translateMesh(node_mesh, v3f(-1.0, -1.0, -1.0));
411
412                         /*
413                                 Draw node mesh into a render target texture
414                         */
415                         if(cc->inventory_texture == NULL)
416                         {
417                                 TextureFromMeshParams params;
418                                 params.mesh = node_mesh;
419                                 params.dim.set(64, 64);
420                                 params.rtt_texture_name = "INVENTORY_"
421                                         + def->name + "_RTT";
422                                 params.delete_texture_on_shutdown = true;
423                                 params.camera_position.set(0, 1.0, -1.5);
424                                 params.camera_position.rotateXZBy(45);
425                                 params.camera_lookat.set(0, 0, 0);
426                                 // Set orthogonal projection
427                                 params.camera_projection_matrix.buildProjectionMatrixOrthoLH(
428                                                 1.65, 1.65, 0, 100);
429                                 params.ambient_light.set(1.0, 0.2, 0.2, 0.2);
430                                 params.light_position.set(10, 100, -50);
431                                 params.light_color.set(1.0, 0.5, 0.5, 0.5);
432                                 params.light_radius = 1000;
433
434                                 cc->inventory_texture =
435                                         tsrc->generateTextureFromMesh(params);
436
437                                 // render-to-target didn't work
438                                 if(cc->inventory_texture == NULL)
439                                 {
440                                         cc->inventory_texture =
441                                                 tsrc->getTexture(f.tiledef[0].name);
442                                 }
443                         }
444
445                         /*
446                                 Use the node mesh as the wield mesh
447                         */
448
449                         // Scale to proper wield mesh proportions
450                         scaleMesh(node_mesh, v3f(30.0, 30.0, 30.0)
451                                         * def->wield_scale);
452
453                         cc->wield_mesh = node_mesh;
454                         cc->wield_mesh->grab();
455
456                         //no way reference count can be smaller than 2 in this place!
457                         assert(cc->wield_mesh->getReferenceCount() >= 2);
458                 }
459
460                 // Put in cache
461                 m_clientcached.set(name, cc);
462
463                 return cc;
464         }
465         ClientCached* getClientCached(const std::string &name,
466                         IGameDef *gamedef) const
467         {
468                 ClientCached *cc = NULL;
469                 m_clientcached.get(name, &cc);
470                 if(cc)
471                         return cc;
472
473                 if(get_current_thread_id() == m_main_thread)
474                 {
475                         return createClientCachedDirect(name, gamedef);
476                 }
477                 else
478                 {
479                         // We're gonna ask the result to be put into here
480                         ResultQueue<std::string, ClientCached*, u8, u8> result_queue;
481                         // Throw a request in
482                         m_get_clientcached_queue.add(name, 0, 0, &result_queue);
483                         try{
484                                 // Wait result for a second
485                                 GetResult<std::string, ClientCached*, u8, u8>
486                                                 result = result_queue.pop_front(1000);
487                                 // Check that at least something worked OK
488                                 assert(result.key == name);
489                                 // Return it
490                                 return result.item;
491                         }
492                         catch(ItemNotFoundException &e)
493                         {
494                                 errorstream<<"Waiting for clientcached timed out."<<std::endl;
495                                 return &m_dummy_clientcached;
496                         }
497                 }
498         }
499         // Get item inventory texture
500         virtual video::ITexture* getInventoryTexture(const std::string &name,
501                         IGameDef *gamedef) const
502         {
503                 ClientCached *cc = getClientCached(name, gamedef);
504                 if(!cc)
505                         return NULL;
506                 return cc->inventory_texture;
507         }
508         // Get item wield mesh
509         virtual scene::IMesh* getWieldMesh(const std::string &name,
510                         IGameDef *gamedef) const
511         {
512                 ClientCached *cc = getClientCached(name, gamedef);
513                 if(!cc)
514                         return NULL;
515                 return cc->wield_mesh;
516         }
517 #endif
518         void clear()
519         {
520                 for(std::map<std::string, ItemDefinition*>::const_iterator
521                                 i = m_item_definitions.begin();
522                                 i != m_item_definitions.end(); i++)
523                 {
524                         delete i->second;
525                 }
526                 m_item_definitions.clear();
527                 m_aliases.clear();
528
529                 // Add the four builtin items:
530                 //   "" is the hand
531                 //   "unknown" is returned whenever an undefined item
532                 //     is accessed (is also the unknown node)
533                 //   "air" is the air node
534                 //   "ignore" is the ignore node
535
536                 ItemDefinition* hand_def = new ItemDefinition;
537                 hand_def->name = "";
538                 hand_def->wield_image = "wieldhand.png";
539                 hand_def->tool_capabilities = new ToolCapabilities;
540                 m_item_definitions.insert(std::make_pair("", hand_def));
541
542                 ItemDefinition* unknown_def = new ItemDefinition;
543                 unknown_def->type = ITEM_NODE;
544                 unknown_def->name = "unknown";
545                 m_item_definitions.insert(std::make_pair("unknown", unknown_def));
546
547                 ItemDefinition* air_def = new ItemDefinition;
548                 air_def->type = ITEM_NODE;
549                 air_def->name = "air";
550                 m_item_definitions.insert(std::make_pair("air", air_def));
551
552                 ItemDefinition* ignore_def = new ItemDefinition;
553                 ignore_def->type = ITEM_NODE;
554                 ignore_def->name = "ignore";
555                 m_item_definitions.insert(std::make_pair("ignore", ignore_def));
556         }
557         virtual void registerItem(const ItemDefinition &def)
558         {
559                 verbosestream<<"ItemDefManager: registering \""<<def.name<<"\""<<std::endl;
560                 // Ensure that the "" item (the hand) always has ToolCapabilities
561                 if(def.name == "")
562                         assert(def.tool_capabilities != NULL);
563                 
564                 if(m_item_definitions.count(def.name) == 0)
565                         m_item_definitions[def.name] = new ItemDefinition(def);
566                 else
567                         *(m_item_definitions[def.name]) = def;
568
569                 // Remove conflicting alias if it exists
570                 bool alias_removed = (m_aliases.erase(def.name) != 0);
571                 if(alias_removed)
572                         infostream<<"ItemDefManager: erased alias "<<def.name
573                                         <<" because item was defined"<<std::endl;
574         }
575         virtual void registerAlias(const std::string &name,
576                         const std::string &convert_to)
577         {
578                 if(m_item_definitions.find(name) == m_item_definitions.end())
579                 {
580                         verbosestream<<"ItemDefManager: setting alias "<<name
581                                 <<" -> "<<convert_to<<std::endl;
582                         m_aliases[name] = convert_to;
583                 }
584         }
585         void serialize(std::ostream &os, u16 protocol_version)
586         {
587                 writeU8(os, 0); // version
588                 u16 count = m_item_definitions.size();
589                 writeU16(os, count);
590                 for(std::map<std::string, ItemDefinition*>::const_iterator
591                                 i = m_item_definitions.begin();
592                                 i != m_item_definitions.end(); i++)
593                 {
594                         ItemDefinition *def = i->second;
595                         // Serialize ItemDefinition and write wrapped in a string
596                         std::ostringstream tmp_os(std::ios::binary);
597                         def->serialize(tmp_os, protocol_version);
598                         os<<serializeString(tmp_os.str());
599                 }
600                 writeU16(os, m_aliases.size());
601                 for(std::map<std::string, std::string>::const_iterator
602                         i = m_aliases.begin(); i != m_aliases.end(); i++)
603                 {
604                         os<<serializeString(i->first);
605                         os<<serializeString(i->second);
606                 }
607         }
608         void deSerialize(std::istream &is)
609         {
610                 // Clear everything
611                 clear();
612                 // Deserialize
613                 int version = readU8(is);
614                 if(version != 0)
615                         throw SerializationError("unsupported ItemDefManager version");
616                 u16 count = readU16(is);
617                 for(u16 i=0; i<count; i++)
618                 {
619                         // Deserialize a string and grab an ItemDefinition from it
620                         std::istringstream tmp_is(deSerializeString(is), std::ios::binary);
621                         ItemDefinition def;
622                         def.deSerialize(tmp_is);
623                         // Register
624                         registerItem(def);
625                 }
626                 u16 num_aliases = readU16(is);
627                 for(u16 i=0; i<num_aliases; i++)
628                 {
629                         std::string name = deSerializeString(is);
630                         std::string convert_to = deSerializeString(is);
631                         registerAlias(name, convert_to);
632                 }
633         }
634         void processQueue(IGameDef *gamedef)
635         {
636 #ifndef SERVER
637                 while(!m_get_clientcached_queue.empty())
638                 {
639                         GetRequest<std::string, ClientCached*, u8, u8>
640                                         request = m_get_clientcached_queue.pop();
641
642                         m_get_clientcached_queue.pushResult(request,
643                                         createClientCachedDirect(request.key, gamedef));
644                 }
645 #endif
646         }
647 private:
648         // Key is name
649         std::map<std::string, ItemDefinition*> m_item_definitions;
650         // Aliases
651         std::map<std::string, std::string> m_aliases;
652 #ifndef SERVER
653         // The id of the thread that is allowed to use irrlicht directly
654         threadid_t m_main_thread;
655         // A reference to this can be returned when nothing is found, to avoid NULLs
656         mutable ClientCached m_dummy_clientcached;
657         // Cached textures and meshes
658         mutable MutexedMap<std::string, ClientCached*> m_clientcached;
659         // Queued clientcached fetches (to be processed by the main thread)
660         mutable RequestQueue<std::string, ClientCached*, u8, u8> m_get_clientcached_queue;
661 #endif
662 };
663
664 IWritableItemDefManager* createItemDefManager()
665 {
666         return new CItemDefManager();
667 }