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