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