3 Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4 Copyright (C) 2013 Kahrl <kahrl@gmx.net>
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.
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.
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.
26 #include "inventory.h"
28 #include "mapblock_mesh.h"
33 #include "main.h" // g_settings
35 #include "util/serialize.h"
36 #include "util/container.h"
37 #include "util/thread.h"
44 ItemDefinition::ItemDefinition()
49 ItemDefinition::ItemDefinition(const ItemDefinition &def)
55 ItemDefinition& ItemDefinition::operator=(const ItemDefinition &def)
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;
70 liquids_pointable = def.liquids_pointable;
71 if(def.tool_capabilities)
73 tool_capabilities = new ToolCapabilities(
74 *def.tool_capabilities);
77 node_placement_prediction = def.node_placement_prediction;
78 sound_place = def.sound_place;
83 ItemDefinition::~ItemDefinition()
88 void ItemDefinition::resetInitial()
90 // Initialize pointers to NULL so reset() does not delete undefined pointers
91 tool_capabilities = NULL;
95 void ItemDefinition::reset()
100 inventory_image = "";
102 wield_scale = v3f(1.0, 1.0, 1.0);
105 liquids_pointable = false;
106 if(tool_capabilities)
108 delete tool_capabilities;
109 tool_capabilities = NULL;
112 sound_place = SimpleSoundSpec();
115 node_placement_prediction = "";
118 void ItemDefinition::serialize(std::ostream &os, u16 protocol_version) const
120 if(protocol_version <= 17)
121 writeU8(os, 1); // version
123 writeU8(os, 2); // version
125 os<<serializeString(name);
126 os<<serializeString(description);
127 os<<serializeString(inventory_image);
128 os<<serializeString(wield_image);
129 writeV3F1000(os, wield_scale);
130 writeS16(os, stack_max);
132 writeU8(os, liquids_pointable);
133 std::string tool_capabilities_s = "";
134 if(tool_capabilities){
135 std::ostringstream tmp_os(std::ios::binary);
136 tool_capabilities->serialize(tmp_os, protocol_version);
137 tool_capabilities_s = tmp_os.str();
139 os<<serializeString(tool_capabilities_s);
140 writeU16(os, groups.size());
141 for(std::map<std::string, int>::const_iterator
142 i = groups.begin(); i != groups.end(); i++){
143 os<<serializeString(i->first);
144 writeS16(os, i->second);
146 os<<serializeString(node_placement_prediction);
147 if(protocol_version > 17){
148 //serializeSimpleSoundSpec(sound_place, os);
149 os<<serializeString(sound_place.name);
150 writeF1000(os, sound_place.gain);
151 writeF1000(os, range);
155 void ItemDefinition::deSerialize(std::istream &is)
161 int version = readU8(is);
162 if(version != 1 && version != 2)
163 throw SerializationError("unsupported ItemDefinition version");
164 type = (enum ItemType)readU8(is);
165 name = deSerializeString(is);
166 description = deSerializeString(is);
167 inventory_image = deSerializeString(is);
168 wield_image = deSerializeString(is);
169 wield_scale = readV3F1000(is);
170 stack_max = readS16(is);
172 liquids_pointable = readU8(is);
173 std::string tool_capabilities_s = deSerializeString(is);
174 if(!tool_capabilities_s.empty())
176 std::istringstream tmp_is(tool_capabilities_s, std::ios::binary);
177 tool_capabilities = new ToolCapabilities;
178 tool_capabilities->deSerialize(tmp_is);
181 u32 groups_size = readU16(is);
182 for(u32 i=0; i<groups_size; i++){
183 std::string name = deSerializeString(is);
184 int value = readS16(is);
185 groups[name] = value;
188 // We cant be sure that node_placement_prediction is send in version 1
190 node_placement_prediction = deSerializeString(is);
191 }catch(SerializationError &e) {};
192 // Set the old default sound
193 sound_place.name = "default_place_node";
194 sound_place.gain = 0.5;
195 } else if(version == 2) {
196 node_placement_prediction = deSerializeString(is);
197 //deserializeSimpleSoundSpec(sound_place, is);
198 sound_place.name = deSerializeString(is);
199 sound_place.gain = readF1000(is);
201 // If you add anything here, insert it primarily inside the try-catch
202 // block to not need to increase the version.
204 range = readF1000(is);
205 }catch(SerializationError &e) {};
212 // SUGG: Support chains of aliases?
214 class CItemDefManager: public IWritableItemDefManager
219 video::ITexture *inventory_texture;
220 scene::IMesh *wield_mesh;
223 inventory_texture(NULL),
234 m_main_thread = get_current_thread_id();
238 virtual ~CItemDefManager()
241 const std::list<ClientCached*> &values = m_clientcached.getValues();
242 for(std::list<ClientCached*>::const_iterator
243 i = values.begin(); i != values.end(); ++i)
245 ClientCached *cc = *i;
247 cc->wield_mesh->drop();
252 for (std::map<std::string, ItemDefinition*>::iterator iter =
253 m_item_definitions.begin(); iter != m_item_definitions.end();
257 m_item_definitions.clear();
259 virtual const ItemDefinition& get(const std::string &name_) const
261 // Convert name according to possible alias
262 std::string name = getAlias(name_);
263 // Get the definition
264 std::map<std::string, ItemDefinition*>::const_iterator i;
265 i = m_item_definitions.find(name);
266 if(i == m_item_definitions.end())
267 i = m_item_definitions.find("unknown");
268 assert(i != m_item_definitions.end());
271 virtual std::string getAlias(const std::string &name) const
273 std::map<std::string, std::string>::const_iterator i;
274 i = m_aliases.find(name);
275 if(i != m_aliases.end())
279 virtual std::set<std::string> getAll() const
281 std::set<std::string> result;
282 for(std::map<std::string, ItemDefinition*>::const_iterator
283 i = m_item_definitions.begin();
284 i != m_item_definitions.end(); i++)
286 result.insert(i->first);
288 for(std::map<std::string, std::string>::const_iterator
289 i = m_aliases.begin();
290 i != m_aliases.end(); i++)
292 result.insert(i->first);
296 virtual bool isKnown(const std::string &name_) const
298 // Convert name according to possible alias
299 std::string name = getAlias(name_);
300 // Get the definition
301 std::map<std::string, ItemDefinition*>::const_iterator i;
302 return m_item_definitions.find(name) != m_item_definitions.end();
306 ClientCached* createClientCachedDirect(const std::string &name,
307 IGameDef *gamedef) const
309 infostream<<"Lazily creating item texture and mesh for \""
310 <<name<<"\""<<std::endl;
312 // This is not thread-safe
313 assert(get_current_thread_id() == m_main_thread);
315 // Skip if already in cache
316 ClientCached *cc = NULL;
317 m_clientcached.get(name, &cc);
321 ITextureSource *tsrc = gamedef->getTextureSource();
322 INodeDefManager *nodedef = gamedef->getNodeDefManager();
323 IrrlichtDevice *device = tsrc->getDevice();
324 video::IVideoDriver *driver = device->getVideoDriver();
325 const ItemDefinition *def = &get(name);
327 // Create new ClientCached
328 cc = new ClientCached();
330 bool need_node_mesh = false;
332 // Create an inventory texture
333 cc->inventory_texture = NULL;
334 if(def->inventory_image != "")
336 cc->inventory_texture = tsrc->getTexture(def->inventory_image);
338 else if(def->type == ITEM_NODE)
340 need_node_mesh = true;
343 // Create a wield mesh
344 assert(cc->wield_mesh == NULL);
345 if(def->type == ITEM_NODE && def->wield_image == "")
347 need_node_mesh = true;
349 else if(def->wield_image != "" || def->inventory_image != "")
351 // Extrude the wield image into a mesh
353 std::string imagename;
354 if(def->wield_image != "")
355 imagename = def->wield_image;
357 imagename = def->inventory_image;
359 cc->wield_mesh = createExtrudedMesh(
360 tsrc->getTexture(imagename),
362 def->wield_scale * v3f(40.0, 40.0, 4.0));
363 if(cc->wield_mesh == NULL)
365 infostream<<"ItemDefManager: WARNING: "
366 <<"updateTexturesAndMeshes(): "
367 <<"Unable to create extruded mesh for item "
368 <<def->name<<std::endl;
377 content_t id = nodedef->getId(def->name);
378 const ContentFeatures &f = nodedef->get(id);
381 if(f.param_type == CPT_LIGHT)
385 Make a mesh from the node
387 MeshMakeData mesh_make_data(gamedef);
388 MapNode mesh_make_node(id, param1, 0);
389 mesh_make_data.fillSingleNode(&mesh_make_node);
390 MapBlockMesh mapblock_mesh(&mesh_make_data);
392 scene::IMesh *node_mesh = mapblock_mesh.getMesh();
394 video::SColor c(255, 255, 255, 255);
395 if(g_settings->getBool("enable_shaders"))
396 c = MapBlock_LightColor(255, 0xffff, decode_light(f.light_source));
397 setMeshColor(node_mesh, c);
400 Scale and translate the mesh so it's a unit cube
401 centered on the origin
403 scaleMesh(node_mesh, v3f(1.0/BS, 1.0/BS, 1.0/BS));
404 translateMesh(node_mesh, v3f(-1.0, -1.0, -1.0));
407 Draw node mesh into a render target texture
409 if(cc->inventory_texture == NULL)
411 TextureFromMeshParams params;
412 params.mesh = node_mesh;
413 params.dim.set(64, 64);
414 params.rtt_texture_name = "INVENTORY_"
415 + def->name + "_RTT";
416 params.delete_texture_on_shutdown = true;
417 params.camera_position.set(0, 1.0, -1.5);
418 params.camera_position.rotateXZBy(45);
419 params.camera_lookat.set(0, 0, 0);
420 // Set orthogonal projection
421 params.camera_projection_matrix.buildProjectionMatrixOrthoLH(
423 params.ambient_light.set(1.0, 0.2, 0.2, 0.2);
424 params.light_position.set(10, 100, -50);
425 params.light_color.set(1.0, 0.5, 0.5, 0.5);
426 params.light_radius = 1000;
428 cc->inventory_texture =
429 tsrc->generateTextureFromMesh(params);
431 // render-to-target didn't work
432 if(cc->inventory_texture == NULL)
434 cc->inventory_texture =
435 tsrc->getTexture(f.tiledef[0].name);
440 Use the node mesh as the wield mesh
443 // Scale to proper wield mesh proportions
444 scaleMesh(node_mesh, v3f(30.0, 30.0, 30.0)
447 cc->wield_mesh = node_mesh;
448 cc->wield_mesh->grab();
450 //no way reference count can be smaller than 2 in this place!
451 assert(cc->wield_mesh->getReferenceCount() >= 2);
455 m_clientcached.set(name, cc);
459 ClientCached* getClientCached(const std::string &name,
460 IGameDef *gamedef) const
462 ClientCached *cc = NULL;
463 m_clientcached.get(name, &cc);
467 if(get_current_thread_id() == m_main_thread)
469 return createClientCachedDirect(name, gamedef);
473 // We're gonna ask the result to be put into here
474 ResultQueue<std::string, ClientCached*, u8, u8> result_queue;
475 // Throw a request in
476 m_get_clientcached_queue.add(name, 0, 0, &result_queue);
478 // Wait result for a second
479 GetResult<std::string, ClientCached*, u8, u8>
480 result = result_queue.pop_front(1000);
481 // Check that at least something worked OK
482 assert(result.key == name);
486 catch(ItemNotFoundException &e)
488 errorstream<<"Waiting for clientcached timed out."<<std::endl;
489 return &m_dummy_clientcached;
493 // Get item inventory texture
494 virtual video::ITexture* getInventoryTexture(const std::string &name,
495 IGameDef *gamedef) const
497 ClientCached *cc = getClientCached(name, gamedef);
500 return cc->inventory_texture;
502 // Get item wield mesh
503 virtual scene::IMesh* getWieldMesh(const std::string &name,
504 IGameDef *gamedef) const
506 ClientCached *cc = getClientCached(name, gamedef);
509 return cc->wield_mesh;
514 for(std::map<std::string, ItemDefinition*>::const_iterator
515 i = m_item_definitions.begin();
516 i != m_item_definitions.end(); i++)
520 m_item_definitions.clear();
523 // Add the four builtin items:
525 // "unknown" is returned whenever an undefined item
526 // is accessed (is also the unknown node)
527 // "air" is the air node
528 // "ignore" is the ignore node
530 ItemDefinition* hand_def = new ItemDefinition;
532 hand_def->wield_image = "wieldhand.png";
533 hand_def->tool_capabilities = new ToolCapabilities;
534 m_item_definitions.insert(std::make_pair("", hand_def));
536 ItemDefinition* unknown_def = new ItemDefinition;
537 unknown_def->type = ITEM_NODE;
538 unknown_def->name = "unknown";
539 m_item_definitions.insert(std::make_pair("unknown", unknown_def));
541 ItemDefinition* air_def = new ItemDefinition;
542 air_def->type = ITEM_NODE;
543 air_def->name = "air";
544 m_item_definitions.insert(std::make_pair("air", air_def));
546 ItemDefinition* ignore_def = new ItemDefinition;
547 ignore_def->type = ITEM_NODE;
548 ignore_def->name = "ignore";
549 m_item_definitions.insert(std::make_pair("ignore", ignore_def));
551 virtual void registerItem(const ItemDefinition &def)
553 verbosestream<<"ItemDefManager: registering \""<<def.name<<"\""<<std::endl;
554 // Ensure that the "" item (the hand) always has ToolCapabilities
556 assert(def.tool_capabilities != NULL);
558 if(m_item_definitions.count(def.name) == 0)
559 m_item_definitions[def.name] = new ItemDefinition(def);
561 *(m_item_definitions[def.name]) = def;
563 // Remove conflicting alias if it exists
564 bool alias_removed = (m_aliases.erase(def.name) != 0);
566 infostream<<"ItemDefManager: erased alias "<<def.name
567 <<" because item was defined"<<std::endl;
569 virtual void registerAlias(const std::string &name,
570 const std::string &convert_to)
572 if(m_item_definitions.find(name) == m_item_definitions.end())
574 verbosestream<<"ItemDefManager: setting alias "<<name
575 <<" -> "<<convert_to<<std::endl;
576 m_aliases[name] = convert_to;
579 void serialize(std::ostream &os, u16 protocol_version)
581 writeU8(os, 0); // version
582 u16 count = m_item_definitions.size();
584 for(std::map<std::string, ItemDefinition*>::const_iterator
585 i = m_item_definitions.begin();
586 i != m_item_definitions.end(); i++)
588 ItemDefinition *def = i->second;
589 // Serialize ItemDefinition and write wrapped in a string
590 std::ostringstream tmp_os(std::ios::binary);
591 def->serialize(tmp_os, protocol_version);
592 os<<serializeString(tmp_os.str());
594 writeU16(os, m_aliases.size());
595 for(std::map<std::string, std::string>::const_iterator
596 i = m_aliases.begin(); i != m_aliases.end(); i++)
598 os<<serializeString(i->first);
599 os<<serializeString(i->second);
602 void deSerialize(std::istream &is)
607 int version = readU8(is);
609 throw SerializationError("unsupported ItemDefManager version");
610 u16 count = readU16(is);
611 for(u16 i=0; i<count; i++)
613 // Deserialize a string and grab an ItemDefinition from it
614 std::istringstream tmp_is(deSerializeString(is), std::ios::binary);
616 def.deSerialize(tmp_is);
620 u16 num_aliases = readU16(is);
621 for(u16 i=0; i<num_aliases; i++)
623 std::string name = deSerializeString(is);
624 std::string convert_to = deSerializeString(is);
625 registerAlias(name, convert_to);
628 void processQueue(IGameDef *gamedef)
631 while(!m_get_clientcached_queue.empty())
633 GetRequest<std::string, ClientCached*, u8, u8>
634 request = m_get_clientcached_queue.pop();
635 GetResult<std::string, ClientCached*, u8, u8>
637 result.key = request.key;
638 result.callers = request.callers;
639 result.item = createClientCachedDirect(request.key, gamedef);
640 request.dest->push_back(result);
646 std::map<std::string, ItemDefinition*> m_item_definitions;
648 std::map<std::string, std::string> m_aliases;
650 // The id of the thread that is allowed to use irrlicht directly
651 threadid_t m_main_thread;
652 // A reference to this can be returned when nothing is found, to avoid NULLs
653 mutable ClientCached m_dummy_clientcached;
654 // Cached textures and meshes
655 mutable MutexedMap<std::string, ClientCached*> m_clientcached;
656 // Queued clientcached fetches (to be processed by the main thread)
657 mutable RequestQueue<std::string, ClientCached*, u8, u8> m_get_clientcached_queue;
661 IWritableItemDefManager* createItemDefManager()
663 return new CItemDefManager();