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"
30 #include "wieldmesh.h"
34 #include "main.h" // g_settings
36 #include "util/serialize.h"
37 #include "util/container.h"
38 #include "util/thread.h"
49 ItemDefinition::ItemDefinition()
54 ItemDefinition::ItemDefinition(const ItemDefinition &def)
60 ItemDefinition& ItemDefinition::operator=(const ItemDefinition &def)
69 description = def.description;
70 inventory_image = def.inventory_image;
71 wield_image = def.wield_image;
72 wield_scale = def.wield_scale;
73 stack_max = def.stack_max;
75 liquids_pointable = def.liquids_pointable;
76 if(def.tool_capabilities)
78 tool_capabilities = new ToolCapabilities(
79 *def.tool_capabilities);
82 node_placement_prediction = def.node_placement_prediction;
83 sound_place = def.sound_place;
88 ItemDefinition::~ItemDefinition()
93 void ItemDefinition::resetInitial()
95 // Initialize pointers to NULL so reset() does not delete undefined pointers
96 tool_capabilities = NULL;
100 void ItemDefinition::reset()
105 inventory_image = "";
107 wield_scale = v3f(1.0, 1.0, 1.0);
110 liquids_pointable = false;
111 if(tool_capabilities)
113 delete tool_capabilities;
114 tool_capabilities = NULL;
117 sound_place = SimpleSoundSpec();
120 node_placement_prediction = "";
123 void ItemDefinition::serialize(std::ostream &os, u16 protocol_version) const
125 if(protocol_version <= 17)
126 writeU8(os, 1); // version
127 else if(protocol_version <= 20)
128 writeU8(os, 2); // version
130 writeU8(os, 3); // version
132 os<<serializeString(name);
133 os<<serializeString(description);
134 os<<serializeString(inventory_image);
135 os<<serializeString(wield_image);
136 writeV3F1000(os, wield_scale);
137 writeS16(os, stack_max);
139 writeU8(os, liquids_pointable);
140 std::string tool_capabilities_s = "";
141 if(tool_capabilities){
142 std::ostringstream tmp_os(std::ios::binary);
143 tool_capabilities->serialize(tmp_os, protocol_version);
144 tool_capabilities_s = tmp_os.str();
146 os<<serializeString(tool_capabilities_s);
147 writeU16(os, groups.size());
148 for(std::map<std::string, int>::const_iterator
149 i = groups.begin(); i != groups.end(); i++){
150 os<<serializeString(i->first);
151 writeS16(os, i->second);
153 os<<serializeString(node_placement_prediction);
154 if(protocol_version > 17){
155 //serializeSimpleSoundSpec(sound_place, os);
156 os<<serializeString(sound_place.name);
157 writeF1000(os, sound_place.gain);
159 if(protocol_version > 20){
160 writeF1000(os, range);
164 void ItemDefinition::deSerialize(std::istream &is)
170 int version = readU8(is);
171 if(version < 1 || version > 3)
172 throw SerializationError("unsupported ItemDefinition version");
173 type = (enum ItemType)readU8(is);
174 name = deSerializeString(is);
175 description = deSerializeString(is);
176 inventory_image = deSerializeString(is);
177 wield_image = deSerializeString(is);
178 wield_scale = readV3F1000(is);
179 stack_max = readS16(is);
181 liquids_pointable = readU8(is);
182 std::string tool_capabilities_s = deSerializeString(is);
183 if(!tool_capabilities_s.empty())
185 std::istringstream tmp_is(tool_capabilities_s, std::ios::binary);
186 tool_capabilities = new ToolCapabilities;
187 tool_capabilities->deSerialize(tmp_is);
190 u32 groups_size = readU16(is);
191 for(u32 i=0; i<groups_size; i++){
192 std::string name = deSerializeString(is);
193 int value = readS16(is);
194 groups[name] = value;
197 // We cant be sure that node_placement_prediction is send in version 1
199 node_placement_prediction = deSerializeString(is);
200 }catch(SerializationError &e) {};
201 // Set the old default sound
202 sound_place.name = "default_place_node";
203 sound_place.gain = 0.5;
204 } else if(version >= 2) {
205 node_placement_prediction = deSerializeString(is);
206 //deserializeSimpleSoundSpec(sound_place, is);
207 sound_place.name = deSerializeString(is);
208 sound_place.gain = readF1000(is);
211 range = readF1000(is);
213 // If you add anything here, insert it primarily inside the try-catch
214 // block to not need to increase the version.
216 }catch(SerializationError &e) {};
223 // SUGG: Support chains of aliases?
225 class CItemDefManager: public IWritableItemDefManager
230 video::ITexture *inventory_texture;
231 scene::IMesh *wield_mesh;
234 inventory_texture(NULL),
245 m_main_thread = get_current_thread_id();
249 virtual ~CItemDefManager()
252 const std::list<ClientCached*> &values = m_clientcached.getValues();
253 for(std::list<ClientCached*>::const_iterator
254 i = values.begin(); i != values.end(); ++i)
256 ClientCached *cc = *i;
258 cc->wield_mesh->drop();
263 for (std::map<std::string, ItemDefinition*>::iterator iter =
264 m_item_definitions.begin(); iter != m_item_definitions.end();
268 m_item_definitions.clear();
270 virtual const ItemDefinition& get(const std::string &name_) const
272 // Convert name according to possible alias
273 std::string name = getAlias(name_);
274 // Get the definition
275 std::map<std::string, ItemDefinition*>::const_iterator i;
276 i = m_item_definitions.find(name);
277 if(i == m_item_definitions.end())
278 i = m_item_definitions.find("unknown");
279 assert(i != m_item_definitions.end());
282 virtual std::string getAlias(const std::string &name) const
284 std::map<std::string, std::string>::const_iterator i;
285 i = m_aliases.find(name);
286 if(i != m_aliases.end())
290 virtual std::set<std::string> getAll() const
292 std::set<std::string> result;
293 for(std::map<std::string, ItemDefinition*>::const_iterator
294 i = m_item_definitions.begin();
295 i != m_item_definitions.end(); i++)
297 result.insert(i->first);
299 for(std::map<std::string, std::string>::const_iterator
300 i = m_aliases.begin();
301 i != m_aliases.end(); i++)
303 result.insert(i->first);
307 virtual bool isKnown(const std::string &name_) const
309 // Convert name according to possible alias
310 std::string name = getAlias(name_);
311 // Get the definition
312 std::map<std::string, ItemDefinition*>::const_iterator i;
313 return m_item_definitions.find(name) != m_item_definitions.end();
317 ClientCached* createClientCachedDirect(const std::string &name,
318 IGameDef *gamedef) const
320 infostream<<"Lazily creating item texture and mesh for \""
321 <<name<<"\""<<std::endl;
323 // This is not thread-safe
324 assert(get_current_thread_id() == m_main_thread);
326 // Skip if already in cache
327 ClientCached *cc = NULL;
328 m_clientcached.get(name, &cc);
332 ITextureSource *tsrc = gamedef->getTextureSource();
333 INodeDefManager *nodedef = gamedef->getNodeDefManager();
334 const ItemDefinition &def = get(name);
336 // Create new ClientCached
337 cc = new ClientCached();
339 // Create an inventory texture
340 cc->inventory_texture = NULL;
341 if(def.inventory_image != "")
342 cc->inventory_texture = tsrc->getTexture(def.inventory_image);
344 // Additional processing for nodes:
345 // - Create a wield mesh if WieldMeshSceneNode can't render
346 // the node on its own.
347 // - If inventory_texture isn't set yet, create one using
348 // render-to-texture.
349 if (def.type == ITEM_NODE) {
350 // Get node properties
351 content_t id = nodedef->getId(name);
352 const ContentFeatures &f = nodedef->get(id);
354 bool need_rtt_mesh = cc->inventory_texture == NULL;
356 // Keep this in sync with WieldMeshSceneNode::setItem()
357 bool need_wield_mesh =
359 f.drawtype == NDT_NORMAL ||
360 f.drawtype == NDT_ALLFACES ||
361 f.drawtype == NDT_AIRLIKE);
363 scene::IMesh *node_mesh = NULL;
365 if (need_rtt_mesh || need_wield_mesh) {
367 if (f.param_type == CPT_LIGHT)
371 Make a mesh from the node
373 MeshMakeData mesh_make_data(gamedef, false);
375 if (f.param_type_2 == CPT2_WALLMOUNTED)
377 MapNode mesh_make_node(id, param1, param2);
378 mesh_make_data.fillSingleNode(&mesh_make_node);
379 MapBlockMesh mapblock_mesh(&mesh_make_data, v3s16(0, 0, 0));
380 node_mesh = mapblock_mesh.getMesh();
382 video::SColor c(255, 255, 255, 255);
383 setMeshColor(node_mesh, c);
385 // scale and translate the mesh so it's a
386 // unit cube centered on the origin
387 scaleMesh(node_mesh, v3f(1.0/BS, 1.0/BS, 1.0/BS));
388 translateMesh(node_mesh, v3f(-1.0, -1.0, -1.0));
392 Draw node mesh into a render target texture
395 TextureFromMeshParams params;
396 params.mesh = node_mesh;
397 params.dim.set(64, 64);
398 params.rtt_texture_name = "INVENTORY_"
400 params.delete_texture_on_shutdown = true;
401 params.camera_position.set(0, 1.0, -1.5);
402 params.camera_position.rotateXZBy(45);
403 params.camera_lookat.set(0, 0, 0);
404 // Set orthogonal projection
405 params.camera_projection_matrix.buildProjectionMatrixOrthoLH(
407 params.ambient_light.set(1.0, 0.2, 0.2, 0.2);
408 params.light_position.set(10, 100, -50);
409 params.light_color.set(1.0, 0.5, 0.5, 0.5);
410 params.light_radius = 1000;
413 params.camera_position.set(0, -1.0, -1.5);
414 params.camera_position.rotateXZBy(45);
415 params.light_position.set(10, -100, -50);
417 cc->inventory_texture =
418 tsrc->generateTextureFromMesh(params);
420 // render-to-target didn't work
421 if (cc->inventory_texture == NULL) {
422 cc->inventory_texture =
423 tsrc->getTexture(f.tiledef[0].name);
428 Use the node mesh as the wield mesh
430 if (need_wield_mesh) {
431 cc->wield_mesh = node_mesh;
432 cc->wield_mesh->grab();
434 // no way reference count can be smaller than 2 in this place!
435 assert(cc->wield_mesh->getReferenceCount() >= 2);
443 m_clientcached.set(name, cc);
447 ClientCached* getClientCached(const std::string &name,
448 IGameDef *gamedef) const
450 ClientCached *cc = NULL;
451 m_clientcached.get(name, &cc);
455 if(get_current_thread_id() == m_main_thread)
457 return createClientCachedDirect(name, gamedef);
461 // We're gonna ask the result to be put into here
462 static ResultQueue<std::string, ClientCached*, u8, u8> result_queue;
464 // Throw a request in
465 m_get_clientcached_queue.add(name, 0, 0, &result_queue);
468 // Wait result for a second
469 GetResult<std::string, ClientCached*, u8, u8>
470 result = result_queue.pop_front(1000);
472 if (result.key == name) {
477 catch(ItemNotFoundException &e)
479 errorstream<<"Waiting for clientcached " << name << " timed out."<<std::endl;
480 return &m_dummy_clientcached;
484 // Get item inventory texture
485 virtual video::ITexture* getInventoryTexture(const std::string &name,
486 IGameDef *gamedef) const
488 ClientCached *cc = getClientCached(name, gamedef);
491 return cc->inventory_texture;
493 // Get item wield mesh
494 virtual scene::IMesh* getWieldMesh(const std::string &name,
495 IGameDef *gamedef) const
497 ClientCached *cc = getClientCached(name, gamedef);
500 return cc->wield_mesh;
505 for(std::map<std::string, ItemDefinition*>::const_iterator
506 i = m_item_definitions.begin();
507 i != m_item_definitions.end(); i++)
511 m_item_definitions.clear();
514 // Add the four builtin items:
516 // "unknown" is returned whenever an undefined item
517 // is accessed (is also the unknown node)
518 // "air" is the air node
519 // "ignore" is the ignore node
521 ItemDefinition* hand_def = new ItemDefinition;
523 hand_def->wield_image = "wieldhand.png";
524 hand_def->tool_capabilities = new ToolCapabilities;
525 m_item_definitions.insert(std::make_pair("", hand_def));
527 ItemDefinition* unknown_def = new ItemDefinition;
528 unknown_def->type = ITEM_NODE;
529 unknown_def->name = "unknown";
530 m_item_definitions.insert(std::make_pair("unknown", unknown_def));
532 ItemDefinition* air_def = new ItemDefinition;
533 air_def->type = ITEM_NODE;
534 air_def->name = "air";
535 m_item_definitions.insert(std::make_pair("air", air_def));
537 ItemDefinition* ignore_def = new ItemDefinition;
538 ignore_def->type = ITEM_NODE;
539 ignore_def->name = "ignore";
540 m_item_definitions.insert(std::make_pair("ignore", ignore_def));
542 virtual void registerItem(const ItemDefinition &def)
544 verbosestream<<"ItemDefManager: registering \""<<def.name<<"\""<<std::endl;
545 // Ensure that the "" item (the hand) always has ToolCapabilities
547 assert(def.tool_capabilities != NULL);
549 if(m_item_definitions.count(def.name) == 0)
550 m_item_definitions[def.name] = new ItemDefinition(def);
552 *(m_item_definitions[def.name]) = def;
554 // Remove conflicting alias if it exists
555 bool alias_removed = (m_aliases.erase(def.name) != 0);
557 infostream<<"ItemDefManager: erased alias "<<def.name
558 <<" because item was defined"<<std::endl;
560 virtual void registerAlias(const std::string &name,
561 const std::string &convert_to)
563 if(m_item_definitions.find(name) == m_item_definitions.end())
565 verbosestream<<"ItemDefManager: setting alias "<<name
566 <<" -> "<<convert_to<<std::endl;
567 m_aliases[name] = convert_to;
570 void serialize(std::ostream &os, u16 protocol_version)
572 writeU8(os, 0); // version
573 u16 count = m_item_definitions.size();
575 for(std::map<std::string, ItemDefinition*>::const_iterator
576 i = m_item_definitions.begin();
577 i != m_item_definitions.end(); i++)
579 ItemDefinition *def = i->second;
580 // Serialize ItemDefinition and write wrapped in a string
581 std::ostringstream tmp_os(std::ios::binary);
582 def->serialize(tmp_os, protocol_version);
583 os<<serializeString(tmp_os.str());
585 writeU16(os, m_aliases.size());
586 for(std::map<std::string, std::string>::const_iterator
587 i = m_aliases.begin(); i != m_aliases.end(); i++)
589 os<<serializeString(i->first);
590 os<<serializeString(i->second);
593 void deSerialize(std::istream &is)
598 int version = readU8(is);
600 throw SerializationError("unsupported ItemDefManager version");
601 u16 count = readU16(is);
602 for(u16 i=0; i<count; i++)
604 // Deserialize a string and grab an ItemDefinition from it
605 std::istringstream tmp_is(deSerializeString(is), std::ios::binary);
607 def.deSerialize(tmp_is);
611 u16 num_aliases = readU16(is);
612 for(u16 i=0; i<num_aliases; i++)
614 std::string name = deSerializeString(is);
615 std::string convert_to = deSerializeString(is);
616 registerAlias(name, convert_to);
619 void processQueue(IGameDef *gamedef)
622 //NOTE this is only thread safe for ONE consumer thread!
623 while(!m_get_clientcached_queue.empty())
625 GetRequest<std::string, ClientCached*, u8, u8>
626 request = m_get_clientcached_queue.pop();
628 m_get_clientcached_queue.pushResult(request,
629 createClientCachedDirect(request.key, gamedef));
635 std::map<std::string, ItemDefinition*> m_item_definitions;
637 std::map<std::string, std::string> m_aliases;
639 // The id of the thread that is allowed to use irrlicht directly
640 threadid_t m_main_thread;
641 // A reference to this can be returned when nothing is found, to avoid NULLs
642 mutable ClientCached m_dummy_clientcached;
643 // Cached textures and meshes
644 mutable MutexedMap<std::string, ClientCached*> m_clientcached;
645 // Queued clientcached fetches (to be processed by the main thread)
646 mutable RequestQueue<std::string, ClientCached*, u8, u8> m_get_clientcached_queue;
650 IWritableItemDefManager* createItemDefManager()
652 return new CItemDefManager();