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