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