3 Copyright (C) 2010-2011 celeron55, Perttu Ahola <celeron55@gmail.com>
4 Copyright (C) 2011 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 "util/serialize.h"
34 #include "util/container.h"
35 #include "util/thread.h"
42 ItemDefinition::ItemDefinition()
47 ItemDefinition::ItemDefinition(const ItemDefinition &def)
53 ItemDefinition& ItemDefinition::operator=(const ItemDefinition &def)
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;
68 liquids_pointable = def.liquids_pointable;
69 if(def.tool_capabilities)
71 tool_capabilities = new ToolCapabilities(
72 *def.tool_capabilities);
75 node_placement_prediction = def.node_placement_prediction;
79 ItemDefinition::~ItemDefinition()
84 void ItemDefinition::resetInitial()
86 // Initialize pointers to NULL so reset() does not delete undefined pointers
87 tool_capabilities = NULL;
91 void ItemDefinition::reset()
98 wield_scale = v3f(1.0, 1.0, 1.0);
101 liquids_pointable = false;
102 if(tool_capabilities)
104 delete tool_capabilities;
105 tool_capabilities = NULL;
109 node_placement_prediction = "";
112 void ItemDefinition::serialize(std::ostream &os) const
114 writeU8(os, 1); // version
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);
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();
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);
137 os<<serializeString(node_placement_prediction);
140 void ItemDefinition::deSerialize(std::istream &is)
146 int version = readU8(is);
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);
157 liquids_pointable = readU8(is);
158 std::string tool_capabilities_s = deSerializeString(is);
159 if(!tool_capabilities_s.empty())
161 std::istringstream tmp_is(tool_capabilities_s, std::ios::binary);
162 tool_capabilities = new ToolCapabilities;
163 tool_capabilities->deSerialize(tmp_is);
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;
172 // If you add anything here, insert it primarily inside the try-catch
173 // block to not need to increase the version.
175 node_placement_prediction = deSerializeString(is);
176 }catch(SerializationError &e) {};
183 // SUGG: Support chains of aliases?
185 class CItemDefManager: public IWritableItemDefManager
190 video::ITexture *inventory_texture;
191 scene::IMesh *wield_mesh;
194 inventory_texture(NULL),
204 m_main_thread = get_current_thread_id();
209 virtual ~CItemDefManager()
212 const core::list<ClientCached*> &values = m_clientcached.getValues();
213 for(core::list<ClientCached*>::ConstIterator
214 i = values.begin(); i != values.end(); ++i)
216 ClientCached *cc = *i;
217 cc->wield_mesh->drop();
221 virtual const ItemDefinition& get(const std::string &name_) const
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());
233 virtual std::string getAlias(const std::string &name) const
235 std::map<std::string, std::string>::const_iterator i;
236 i = m_aliases.find(name);
237 if(i != m_aliases.end())
241 virtual std::set<std::string> getAll() const
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++)
248 result.insert(i->first);
250 for(std::map<std::string, std::string>::const_iterator
251 i = m_aliases.begin();
252 i != m_aliases.end(); i++)
254 result.insert(i->first);
258 virtual bool isKnown(const std::string &name_) const
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();
267 ClientCached* createClientCachedDirect(const std::string &name,
268 IGameDef *gamedef) const
270 infostream<<"Lazily creating item texture and mesh for \""
271 <<name<<"\""<<std::endl;
273 // This is not thread-safe
274 assert(get_current_thread_id() == m_main_thread);
276 // Skip if already in cache
277 ClientCached *cc = NULL;
278 m_clientcached.get(name, &cc);
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);
288 // Create new ClientCached
289 cc = new ClientCached();
291 bool need_node_mesh = false;
293 // Create an inventory texture
294 cc->inventory_texture = NULL;
295 if(def->inventory_image != "")
297 cc->inventory_texture = tsrc->getTextureRaw(def->inventory_image);
299 else if(def->type == ITEM_NODE)
301 need_node_mesh = true;
304 // Create a wield mesh
305 if(cc->wield_mesh != NULL)
307 cc->wield_mesh->drop();
308 cc->wield_mesh = NULL;
310 if(def->type == ITEM_NODE && def->wield_image == "")
312 need_node_mesh = true;
314 else if(def->wield_image != "" || def->inventory_image != "")
316 // Extrude the wield image into a mesh
318 std::string imagename;
319 if(def->wield_image != "")
320 imagename = def->wield_image;
322 imagename = def->inventory_image;
324 cc->wield_mesh = createExtrudedMesh(
325 tsrc->getTextureRaw(imagename),
327 def->wield_scale * v3f(40.0, 40.0, 4.0));
328 if(cc->wield_mesh == NULL)
330 infostream<<"ItemDefManager: WARNING: "
331 <<"updateTexturesAndMeshes(): "
332 <<"Unable to create extruded mesh for item "
333 <<def->name<<std::endl;
342 content_t id = nodedef->getId(def->name);
343 const ContentFeatures &f = nodedef->get(id);
346 if(f.param_type == CPT_LIGHT)
350 Make a mesh from the node
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);
357 scene::IMesh *node_mesh = mapblock_mesh.getMesh();
359 setMeshColor(node_mesh, video::SColor(255, 255, 255, 255));
362 Scale and translate the mesh so it's a unit cube
363 centered on the origin
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));
369 Draw node mesh into a render target texture
371 if(cc->inventory_texture == NULL)
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(
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;
389 cc->inventory_texture = generateTextureFromMesh(
390 node_mesh, device, dim, rtt_texture_name,
393 camera_projection_matrix,
399 // render-to-target didn't work
400 if(cc->inventory_texture == NULL)
402 cc->inventory_texture =
403 tsrc->getTextureRaw(f.tiledef[0].name);
408 Use the node mesh as the wield mesh
410 if(cc->wield_mesh == NULL)
412 // Scale to proper wield mesh proportions
413 scaleMesh(node_mesh, v3f(30.0, 30.0, 30.0)
415 cc->wield_mesh = node_mesh;
416 cc->wield_mesh->grab();
419 // falling outside of here deletes node_mesh
423 m_clientcached.set(name, cc);
427 ClientCached* getClientCached(const std::string &name,
428 IGameDef *gamedef) const
430 ClientCached *cc = NULL;
431 m_clientcached.get(name, &cc);
435 if(get_current_thread_id() == m_main_thread)
437 return createClientCachedDirect(name, gamedef);
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);
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);
454 catch(ItemNotFoundException &e)
456 errorstream<<"Waiting for clientcached timed out."<<std::endl;
457 return &m_dummy_clientcached;
461 // Get item inventory texture
462 virtual video::ITexture* getInventoryTexture(const std::string &name,
463 IGameDef *gamedef) const
465 ClientCached *cc = getClientCached(name, gamedef);
468 return cc->inventory_texture;
470 // Get item wield mesh
471 virtual scene::IMesh* getWieldMesh(const std::string &name,
472 IGameDef *gamedef) const
474 ClientCached *cc = getClientCached(name, gamedef);
477 return cc->wield_mesh;
482 for(std::map<std::string, ItemDefinition*>::const_iterator
483 i = m_item_definitions.begin();
484 i != m_item_definitions.end(); i++)
488 m_item_definitions.clear();
491 // Add the four builtin items:
493 // "unknown" is returned whenever an undefined item is accessed
494 // "air" is the air node
495 // "ignore" is the ignore node
497 ItemDefinition* hand_def = new ItemDefinition;
499 hand_def->wield_image = "wieldhand.png";
500 hand_def->tool_capabilities = new ToolCapabilities;
501 m_item_definitions.insert(std::make_pair("", hand_def));
503 ItemDefinition* unknown_def = new ItemDefinition;
504 unknown_def->name = "unknown";
505 m_item_definitions.insert(std::make_pair("unknown", unknown_def));
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));
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));
517 virtual void registerItem(const ItemDefinition &def)
519 verbosestream<<"ItemDefManager: registering \""<<def.name<<"\""<<std::endl;
520 // Ensure that the "" item (the hand) always has ToolCapabilities
522 assert(def.tool_capabilities != NULL);
524 if(m_item_definitions.count(def.name) == 0)
525 m_item_definitions[def.name] = new ItemDefinition(def);
527 *(m_item_definitions[def.name]) = def;
529 // Remove conflicting alias if it exists
530 bool alias_removed = (m_aliases.erase(def.name) != 0);
532 infostream<<"ItemDefManager: erased alias "<<def.name
533 <<" because item was defined"<<std::endl;
535 virtual void registerAlias(const std::string &name,
536 const std::string &convert_to)
538 if(m_item_definitions.find(name) == m_item_definitions.end())
540 verbosestream<<"ItemDefManager: setting alias "<<name
541 <<" -> "<<convert_to<<std::endl;
542 m_aliases[name] = convert_to;
545 void serialize(std::ostream &os)
547 writeU8(os, 0); // version
548 u16 count = m_item_definitions.size();
550 for(std::map<std::string, ItemDefinition*>::const_iterator
551 i = m_item_definitions.begin();
552 i != m_item_definitions.end(); i++)
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());
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++)
564 os<<serializeString(i->first);
565 os<<serializeString(i->second);
568 void deSerialize(std::istream &is)
573 int version = readU8(is);
575 throw SerializationError("unsupported ItemDefManager version");
576 u16 count = readU16(is);
577 for(u16 i=0; i<count; i++)
579 // Deserialize a string and grab an ItemDefinition from it
580 std::istringstream tmp_is(deSerializeString(is), std::ios::binary);
582 def.deSerialize(tmp_is);
586 u16 num_aliases = readU16(is);
587 for(u16 i=0; i<num_aliases; i++)
589 std::string name = deSerializeString(is);
590 std::string convert_to = deSerializeString(is);
591 registerAlias(name, convert_to);
594 void processQueue(IGameDef *gamedef)
597 while(m_get_clientcached_queue.size() > 0)
599 GetRequest<std::string, ClientCached*, u8, u8>
600 request = m_get_clientcached_queue.pop();
601 GetResult<std::string, ClientCached*, u8, u8>
603 result.key = request.key;
604 result.callers = request.callers;
605 result.item = createClientCachedDirect(request.key, gamedef);
606 request.dest->push_back(result);
612 std::map<std::string, ItemDefinition*> m_item_definitions;
614 std::map<std::string, std::string> m_aliases;
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;
627 IWritableItemDefManager* createItemDefManager()
629 return new CItemDefManager();