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
122 else if(protocol_version <= 20)
123 writeU8(os, 2); // version
125 writeU8(os, 3); // version
127 os<<serializeString(name);
128 os<<serializeString(description);
129 os<<serializeString(inventory_image);
130 os<<serializeString(wield_image);
131 writeV3F1000(os, wield_scale);
132 writeS16(os, stack_max);
134 writeU8(os, liquids_pointable);
135 std::string tool_capabilities_s = "";
136 if(tool_capabilities){
137 std::ostringstream tmp_os(std::ios::binary);
138 tool_capabilities->serialize(tmp_os, protocol_version);
139 tool_capabilities_s = tmp_os.str();
141 os<<serializeString(tool_capabilities_s);
142 writeU16(os, groups.size());
143 for(std::map<std::string, int>::const_iterator
144 i = groups.begin(); i != groups.end(); i++){
145 os<<serializeString(i->first);
146 writeS16(os, i->second);
148 os<<serializeString(node_placement_prediction);
149 if(protocol_version > 17){
150 //serializeSimpleSoundSpec(sound_place, os);
151 os<<serializeString(sound_place.name);
152 writeF1000(os, sound_place.gain);
154 if(protocol_version > 20){
155 writeF1000(os, range);
159 void ItemDefinition::deSerialize(std::istream &is)
165 int version = readU8(is);
166 if(version < 1 || version > 3)
167 throw SerializationError("unsupported ItemDefinition version");
168 type = (enum ItemType)readU8(is);
169 name = deSerializeString(is);
170 description = deSerializeString(is);
171 inventory_image = deSerializeString(is);
172 wield_image = deSerializeString(is);
173 wield_scale = readV3F1000(is);
174 stack_max = readS16(is);
176 liquids_pointable = readU8(is);
177 std::string tool_capabilities_s = deSerializeString(is);
178 if(!tool_capabilities_s.empty())
180 std::istringstream tmp_is(tool_capabilities_s, std::ios::binary);
181 tool_capabilities = new ToolCapabilities;
182 tool_capabilities->deSerialize(tmp_is);
185 u32 groups_size = readU16(is);
186 for(u32 i=0; i<groups_size; i++){
187 std::string name = deSerializeString(is);
188 int value = readS16(is);
189 groups[name] = value;
192 // We cant be sure that node_placement_prediction is send in version 1
194 node_placement_prediction = deSerializeString(is);
195 }catch(SerializationError &e) {};
196 // Set the old default sound
197 sound_place.name = "default_place_node";
198 sound_place.gain = 0.5;
199 } else if(version >= 2) {
200 node_placement_prediction = deSerializeString(is);
201 //deserializeSimpleSoundSpec(sound_place, is);
202 sound_place.name = deSerializeString(is);
203 sound_place.gain = readF1000(is);
206 range = readF1000(is);
208 // If you add anything here, insert it primarily inside the try-catch
209 // block to not need to increase the version.
211 }catch(SerializationError &e) {};
218 // SUGG: Support chains of aliases?
220 class CItemDefManager: public IWritableItemDefManager
225 video::ITexture *inventory_texture;
226 scene::IMesh *wield_mesh;
229 inventory_texture(NULL),
240 m_main_thread = get_current_thread_id();
244 virtual ~CItemDefManager()
247 const std::list<ClientCached*> &values = m_clientcached.getValues();
248 for(std::list<ClientCached*>::const_iterator
249 i = values.begin(); i != values.end(); ++i)
251 ClientCached *cc = *i;
253 cc->wield_mesh->drop();
258 for (std::map<std::string, ItemDefinition*>::iterator iter =
259 m_item_definitions.begin(); iter != m_item_definitions.end();
263 m_item_definitions.clear();
265 virtual const ItemDefinition& get(const std::string &name_) const
267 // Convert name according to possible alias
268 std::string name = getAlias(name_);
269 // Get the definition
270 std::map<std::string, ItemDefinition*>::const_iterator i;
271 i = m_item_definitions.find(name);
272 if(i == m_item_definitions.end())
273 i = m_item_definitions.find("unknown");
274 assert(i != m_item_definitions.end());
277 virtual std::string getAlias(const std::string &name) const
279 std::map<std::string, std::string>::const_iterator i;
280 i = m_aliases.find(name);
281 if(i != m_aliases.end())
285 virtual std::set<std::string> getAll() const
287 std::set<std::string> result;
288 for(std::map<std::string, ItemDefinition*>::const_iterator
289 i = m_item_definitions.begin();
290 i != m_item_definitions.end(); i++)
292 result.insert(i->first);
294 for(std::map<std::string, std::string>::const_iterator
295 i = m_aliases.begin();
296 i != m_aliases.end(); i++)
298 result.insert(i->first);
302 virtual bool isKnown(const std::string &name_) const
304 // Convert name according to possible alias
305 std::string name = getAlias(name_);
306 // Get the definition
307 std::map<std::string, ItemDefinition*>::const_iterator i;
308 return m_item_definitions.find(name) != m_item_definitions.end();
312 ClientCached* createClientCachedDirect(const std::string &name,
313 IGameDef *gamedef) const
315 infostream<<"Lazily creating item texture and mesh for \""
316 <<name<<"\""<<std::endl;
318 // This is not thread-safe
319 assert(get_current_thread_id() == m_main_thread);
321 // Skip if already in cache
322 ClientCached *cc = NULL;
323 m_clientcached.get(name, &cc);
327 ITextureSource *tsrc = gamedef->getTextureSource();
328 INodeDefManager *nodedef = gamedef->getNodeDefManager();
329 IrrlichtDevice *device = tsrc->getDevice();
330 video::IVideoDriver *driver = device->getVideoDriver();
331 const ItemDefinition *def = &get(name);
333 // Create new ClientCached
334 cc = new ClientCached();
336 bool need_node_mesh = false;
338 // Create an inventory texture
339 cc->inventory_texture = NULL;
340 if(def->inventory_image != "")
342 cc->inventory_texture = tsrc->getTexture(def->inventory_image);
344 else if(def->type == ITEM_NODE)
346 need_node_mesh = true;
349 // Create a wield mesh
350 assert(cc->wield_mesh == NULL);
351 if(def->type == ITEM_NODE && def->wield_image == "")
353 need_node_mesh = true;
355 else if(def->wield_image != "" || def->inventory_image != "")
357 // Extrude the wield image into a mesh
359 std::string imagename;
360 if(def->wield_image != "")
361 imagename = def->wield_image;
363 imagename = def->inventory_image;
365 cc->wield_mesh = createExtrudedMesh(
366 tsrc->getTexture(imagename),
368 def->wield_scale * v3f(40.0, 40.0, 4.0));
369 if(cc->wield_mesh == NULL)
371 infostream<<"ItemDefManager: WARNING: "
372 <<"updateTexturesAndMeshes(): "
373 <<"Unable to create extruded mesh for item "
374 <<def->name<<std::endl;
383 content_t id = nodedef->getId(def->name);
384 const ContentFeatures &f = nodedef->get(id);
387 if(f.param_type == CPT_LIGHT)
391 Make a mesh from the node
393 bool reenable_shaders = false;
394 if(g_settings->getBool("enable_shaders")){
395 reenable_shaders = true;
396 g_settings->setBool("enable_shaders",false);
398 MeshMakeData mesh_make_data(gamedef);
399 MapNode mesh_make_node(id, param1, 0);
400 mesh_make_data.fillSingleNode(&mesh_make_node);
401 MapBlockMesh mapblock_mesh(&mesh_make_data, v3s16(0, 0, 0));
402 scene::IMesh *node_mesh = mapblock_mesh.getMesh();
404 video::SColor c(255, 255, 255, 255);
405 setMeshColor(node_mesh, c);
408 Scale and translate the mesh so it's a unit cube
409 centered on the origin
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));
415 Draw node mesh into a render target texture
417 if(cc->inventory_texture == NULL)
419 TextureFromMeshParams params;
420 params.mesh = node_mesh;
421 params.dim.set(64, 64);
422 params.rtt_texture_name = "INVENTORY_"
423 + def->name + "_RTT";
424 params.delete_texture_on_shutdown = true;
425 params.camera_position.set(0, 1.0, -1.5);
426 params.camera_position.rotateXZBy(45);
427 params.camera_lookat.set(0, 0, 0);
428 // Set orthogonal projection
429 params.camera_projection_matrix.buildProjectionMatrixOrthoLH(
431 params.ambient_light.set(1.0, 0.2, 0.2, 0.2);
432 params.light_position.set(10, 100, -50);
433 params.light_color.set(1.0, 0.5, 0.5, 0.5);
434 params.light_radius = 1000;
436 cc->inventory_texture =
437 tsrc->generateTextureFromMesh(params);
439 // render-to-target didn't work
440 if(cc->inventory_texture == NULL)
442 cc->inventory_texture =
443 tsrc->getTexture(f.tiledef[0].name);
448 Use the node mesh as the wield mesh
451 // Scale to proper wield mesh proportions
452 scaleMesh(node_mesh, v3f(30.0, 30.0, 30.0)
455 cc->wield_mesh = node_mesh;
456 cc->wield_mesh->grab();
458 //no way reference count can be smaller than 2 in this place!
459 assert(cc->wield_mesh->getReferenceCount() >= 2);
461 if (reenable_shaders)
462 g_settings->setBool("enable_shaders",true);
466 m_clientcached.set(name, cc);
470 ClientCached* getClientCached(const std::string &name,
471 IGameDef *gamedef) const
473 ClientCached *cc = NULL;
474 m_clientcached.get(name, &cc);
478 if(get_current_thread_id() == m_main_thread)
480 return createClientCachedDirect(name, gamedef);
484 // We're gonna ask the result to be put into here
485 static ResultQueue<std::string, ClientCached*, u8, u8> result_queue;
487 // Throw a request in
488 m_get_clientcached_queue.add(name, 0, 0, &result_queue);
491 // Wait result for a second
492 GetResult<std::string, ClientCached*, u8, u8>
493 result = result_queue.pop_front(1000);
495 if (result.key == name) {
500 catch(ItemNotFoundException &e)
502 errorstream<<"Waiting for clientcached " << name << " timed out."<<std::endl;
503 return &m_dummy_clientcached;
507 // Get item inventory texture
508 virtual video::ITexture* getInventoryTexture(const std::string &name,
509 IGameDef *gamedef) const
511 ClientCached *cc = getClientCached(name, gamedef);
514 return cc->inventory_texture;
516 // Get item wield mesh
517 virtual scene::IMesh* getWieldMesh(const std::string &name,
518 IGameDef *gamedef) const
520 ClientCached *cc = getClientCached(name, gamedef);
523 return cc->wield_mesh;
528 for(std::map<std::string, ItemDefinition*>::const_iterator
529 i = m_item_definitions.begin();
530 i != m_item_definitions.end(); i++)
534 m_item_definitions.clear();
537 // Add the four builtin items:
539 // "unknown" is returned whenever an undefined item
540 // is accessed (is also the unknown node)
541 // "air" is the air node
542 // "ignore" is the ignore node
544 ItemDefinition* hand_def = new ItemDefinition;
546 hand_def->wield_image = "wieldhand.png";
547 hand_def->tool_capabilities = new ToolCapabilities;
548 m_item_definitions.insert(std::make_pair("", hand_def));
550 ItemDefinition* unknown_def = new ItemDefinition;
551 unknown_def->type = ITEM_NODE;
552 unknown_def->name = "unknown";
553 m_item_definitions.insert(std::make_pair("unknown", unknown_def));
555 ItemDefinition* air_def = new ItemDefinition;
556 air_def->type = ITEM_NODE;
557 air_def->name = "air";
558 m_item_definitions.insert(std::make_pair("air", air_def));
560 ItemDefinition* ignore_def = new ItemDefinition;
561 ignore_def->type = ITEM_NODE;
562 ignore_def->name = "ignore";
563 m_item_definitions.insert(std::make_pair("ignore", ignore_def));
565 virtual void registerItem(const ItemDefinition &def)
567 verbosestream<<"ItemDefManager: registering \""<<def.name<<"\""<<std::endl;
568 // Ensure that the "" item (the hand) always has ToolCapabilities
570 assert(def.tool_capabilities != NULL);
572 if(m_item_definitions.count(def.name) == 0)
573 m_item_definitions[def.name] = new ItemDefinition(def);
575 *(m_item_definitions[def.name]) = def;
577 // Remove conflicting alias if it exists
578 bool alias_removed = (m_aliases.erase(def.name) != 0);
580 infostream<<"ItemDefManager: erased alias "<<def.name
581 <<" because item was defined"<<std::endl;
583 virtual void registerAlias(const std::string &name,
584 const std::string &convert_to)
586 if(m_item_definitions.find(name) == m_item_definitions.end())
588 verbosestream<<"ItemDefManager: setting alias "<<name
589 <<" -> "<<convert_to<<std::endl;
590 m_aliases[name] = convert_to;
593 void serialize(std::ostream &os, u16 protocol_version)
595 writeU8(os, 0); // version
596 u16 count = m_item_definitions.size();
598 for(std::map<std::string, ItemDefinition*>::const_iterator
599 i = m_item_definitions.begin();
600 i != m_item_definitions.end(); i++)
602 ItemDefinition *def = i->second;
603 // Serialize ItemDefinition and write wrapped in a string
604 std::ostringstream tmp_os(std::ios::binary);
605 def->serialize(tmp_os, protocol_version);
606 os<<serializeString(tmp_os.str());
608 writeU16(os, m_aliases.size());
609 for(std::map<std::string, std::string>::const_iterator
610 i = m_aliases.begin(); i != m_aliases.end(); i++)
612 os<<serializeString(i->first);
613 os<<serializeString(i->second);
616 void deSerialize(std::istream &is)
621 int version = readU8(is);
623 throw SerializationError("unsupported ItemDefManager version");
624 u16 count = readU16(is);
625 for(u16 i=0; i<count; i++)
627 // Deserialize a string and grab an ItemDefinition from it
628 std::istringstream tmp_is(deSerializeString(is), std::ios::binary);
630 def.deSerialize(tmp_is);
634 u16 num_aliases = readU16(is);
635 for(u16 i=0; i<num_aliases; i++)
637 std::string name = deSerializeString(is);
638 std::string convert_to = deSerializeString(is);
639 registerAlias(name, convert_to);
642 void processQueue(IGameDef *gamedef)
645 //NOTE this is only thread safe for ONE consumer thread!
646 while(!m_get_clientcached_queue.empty())
648 GetRequest<std::string, ClientCached*, u8, u8>
649 request = m_get_clientcached_queue.pop();
651 m_get_clientcached_queue.pushResult(request,
652 createClientCachedDirect(request.key, gamedef));
658 std::map<std::string, ItemDefinition*> m_item_definitions;
660 std::map<std::string, std::string> m_aliases;
662 // The id of the thread that is allowed to use irrlicht directly
663 threadid_t m_main_thread;
664 // A reference to this can be returned when nothing is found, to avoid NULLs
665 mutable ClientCached m_dummy_clientcached;
666 // Cached textures and meshes
667 mutable MutexedMap<std::string, ClientCached*> m_clientcached;
668 // Queued clientcached fetches (to be processed by the main thread)
669 mutable RequestQueue<std::string, ClientCached*, u8, u8> m_get_clientcached_queue;
673 IWritableItemDefManager* createItemDefManager()
675 return new CItemDefManager();