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