aboutsummaryrefslogtreecommitdiff
path: root/src/tool.cpp
blob: e013d5ea8ad63892b988744dc1855ffcc5982afc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
/*
Minetest
Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/

#include "tool.h"
#include "itemgroup.h"
#include "log.h"
#include "inventory.h"
#include "exceptions.h"
#include "util/serialize.h"
#include "util/numeric.h"

void ToolCapabilities::serialize(std::ostream &os, u16 protocol_version) const
{
	if(protocol_version <= 17)
		writeU8(os, 1); // version
	else
		writeU8(os, 2); // version
	writeF1000(os, full_punch_interval);
	writeS16(os, max_drop_level);
	writeU32(os, groupcaps.size());
	for(std::map<std::string, ToolGroupCap>::const_iterator
			i = groupcaps.begin(); i != groupcaps.end(); i++){
		const std::string *name = &i->first;
		const ToolGroupCap *cap = &i->second;
		os<<serializeString(*name);
		writeS16(os, cap->uses);
		writeS16(os, cap->maxlevel);
		writeU32(os, cap->times.size());
		for(std::map<int, float>::const_iterator
				i = cap->times.begin(); i != cap->times.end(); i++){
			writeS16(os, i->first);
			writeF1000(os, i->second);
		}
	}
	if(protocol_version > 17){
		writeU32(os, damageGroups.size());
		for(std::map<std::string, s16>::const_iterator
				i = damageGroups.begin(); i != damageGroups.end(); i++){
			os<<serializeString(i->first);
			writeS16(os, i->second);
		}
	}
}

void ToolCapabilities::deSerialize(std::istream &is)
{
	int version = readU8(is);
	if(version != 1 && version != 2) throw SerializationError(
			"unsupported ToolCapabilities version");
	full_punch_interval = readF1000(is);
	max_drop_level = readS16(is);
	groupcaps.clear();
	u32 groupcaps_size = readU32(is);
	for(u32 i=0; i<groupcaps_size; i++){
		std::string name = deSerializeString(is);
		ToolGroupCap cap;
		cap.uses = readS16(is);
		cap.maxlevel = readS16(is);
		u32 times_size = readU32(is);
		for(u32 i=0; i<times_size; i++){
			int level = readS16(is);
			float time = readF1000(is);
			cap.times[level] = time;
		}
		groupcaps[name] = cap;
	}
	if(version == 2)
	{
		u32 damage_groups_size = readU32(is);
		for(u32 i=0; i<damage_groups_size; i++){
			std::string name = deSerializeString(is);
			s16 rating = readS16(is);
			damageGroups[name] = rating;
		}
	}
}

DigParams getDigParams(const ItemGroupList &groups,
		const ToolCapabilities *tp, float time_from_last_punch)
{
	//infostream<<"getDigParams"<<std::endl;
	/* Check group dig_immediate */
	switch(itemgroup_get(groups, "dig_immediate")){
	case 2:
		//infostream<<"dig_immediate=2"<<std::endl;
		return DigParams(true, 0.5, 0, "dig_immediate");
	case 3:
		//infostream<<"dig_immediate=3"<<std::endl;
		return DigParams(true, 0.0, 0, "dig_immediate");
	default:
		break;
	}
	
	// Values to be returned (with a bit of conversion)
	bool result_diggable = false;
	float result_time = 0.0;
	float result_wear = 0.0;
	std::string result_main_group = "";

	int level = itemgroup_get(groups, "level");
	//infostream<<"level="<<level<<std::endl;
	for(std::map<std::string, ToolGroupCap>::const_iterator
			i = tp->groupcaps.begin(); i != tp->groupcaps.end(); i++){
		const std::string &name = i->first;
		//infostream<<"group="<<name<<std::endl;
		const ToolGroupCap &cap = i->second;
		int rating = itemgroup_get(groups, name);
		float time = 0;
		bool time_exists = cap.getTime(rating, &time);
		if(!result_diggable || time < result_time){
			if(cap.maxlevel >= level && time_exists){
				result_diggable = true;
				int leveldiff = cap.maxlevel - level;
				result_time = time / MYMAX(1, leveldiff);
				if(cap.uses != 0)
					result_wear = 1.0 / cap.uses / pow(3.0, (double)leveldiff);
				else
					result_wear = 0;
				result_main_group = name;
			}
		}
	}
	//infostream<<"result_diggable="<<result_diggable<<std::endl;
	//infostream<<"result_time="<<result_time<<std::endl;
	//infostream<<"result_wear="<<result_wear<<std::endl;

	if(time_from_last_punch < tp->full_punch_interval){
		float f = time_from_last_punch / tp->full_punch_interval;
		//infostream<<"f="<<f<<std::endl;
		result_time /= f;
		result_wear /= f;
	}

	u16 wear_i = 65535.*result_wear;
	return DigParams(result_diggable, result_time, wear_i, result_main_group);
}

DigParams getDigParams(const ItemGroupList &groups,
		const ToolCapabilities *tp)
{
	return getDigParams(groups, tp, 1000000);
}

HitParams getHitParams(const ItemGroupList &armor_groups,
		const ToolCapabilities *tp, float time_from_last_punch)
{
	s16 damage = 0;
	float full_punch_interval = tp->full_punch_interval;

	for(std::map<std::string, s16>::const_iterator
			i = tp->damageGroups.begin(); i != tp->damageGroups.end(); i++){
		s16 armor = itemgroup_get(armor_groups, i->first);
		damage += i->second * rangelim(time_from_last_punch / full_punch_interval, 0.0, 1.0)
				* armor / 100.0;
	}

	return HitParams(damage, 0);
}

HitParams getHitParams(const ItemGroupList &armor_groups,
		const ToolCapabilities *tp)
{
	return getHitParams(armor_groups, tp, 1000000);
}

PunchDamageResult getPunchDamage(
		const ItemGroupList &armor_groups,
		const ToolCapabilities *toolcap,
		const ItemStack *punchitem,
		float time_from_last_punch
){
	bool do_hit = true;
	{
		if(do_hit && punchitem){
			if(itemgroup_get(armor_groups, "punch_operable") &&
					(toolcap == NULL || punchitem->name == ""))
				do_hit = false;
		}
		if(do_hit){
			if(itemgroup_get(armor_groups, "immortal"))
				do_hit = false;
		}
	}
	
	PunchDamageResult result;
	if(do_hit)
	{
		HitParams hitparams = getHitParams(armor_groups, toolcap,
				time_from_last_punch);
		result.did_punch = true;
		result.wear = hitparams.wear;
		result.damage = hitparams.hp;
	}

	return result;
}


>); writeS16(os, i->second); } os << serializeString(node_placement_prediction); os << serializeString(sound_place.name); writeF1000(os, sound_place.gain); writeF1000(os, range); os << serializeString(sound_place_failed.name); writeF1000(os, sound_place_failed.gain); os << serializeString(palette_image); writeU32(os, color.color); } void ItemDefinition::deSerialize(std::istream &is) { // Reset everything reset(); // Deserialize int version = readU8(is); if(version < 1 || version > 3) throw SerializationError("unsupported ItemDefinition version"); type = (enum ItemType)readU8(is); name = deSerializeString(is); description = deSerializeString(is); inventory_image = deSerializeString(is); wield_image = deSerializeString(is); wield_scale = readV3F1000(is); stack_max = readS16(is); usable = readU8(is); liquids_pointable = readU8(is); std::string tool_capabilities_s = deSerializeString(is); if(!tool_capabilities_s.empty()) { std::istringstream tmp_is(tool_capabilities_s, std::ios::binary); tool_capabilities = new ToolCapabilities; tool_capabilities->deSerialize(tmp_is); } groups.clear(); u32 groups_size = readU16(is); for(u32 i=0; i<groups_size; i++){ std::string name = deSerializeString(is); int value = readS16(is); groups[name] = value; } if(version == 1){ // We cant be sure that node_placement_prediction is send in version 1 try{ node_placement_prediction = deSerializeString(is); }catch(SerializationError &e) {}; // Set the old default sound sound_place.name = "default_place_node"; sound_place.gain = 0.5; } else if(version >= 2) { node_placement_prediction = deSerializeString(is); //deserializeSimpleSoundSpec(sound_place, is); sound_place.name = deSerializeString(is); sound_place.gain = readF1000(is); } if(version == 3) { range = readF1000(is); } // If you add anything here, insert it primarily inside the try-catch // block to not need to increase the version. try { sound_place_failed.name = deSerializeString(is); sound_place_failed.gain = readF1000(is); palette_image = deSerializeString(is); color.set(readU32(is)); } catch(SerializationError &e) {}; } /* CItemDefManager */ // SUGG: Support chains of aliases? class CItemDefManager: public IWritableItemDefManager { #ifndef SERVER struct ClientCached { video::ITexture *inventory_texture; ItemMesh wield_mesh; Palette *palette; ClientCached(): inventory_texture(NULL), wield_mesh(), palette(NULL) {} }; #endif public: CItemDefManager() { #ifndef SERVER m_main_thread = thr_get_current_thread_id(); #endif clear(); } virtual ~CItemDefManager() { #ifndef SERVER const std::vector<ClientCached*> &values = m_clientcached.getValues(); for(std::vector<ClientCached*>::const_iterator i = values.begin(); i != values.end(); ++i) { ClientCached *cc = *i; if (cc->wield_mesh.mesh) cc->wield_mesh.mesh->drop(); delete cc; } #endif for (std::map<std::string, ItemDefinition*>::iterator iter = m_item_definitions.begin(); iter != m_item_definitions.end(); ++iter) { delete iter->second; } m_item_definitions.clear(); } virtual const ItemDefinition& get(const std::string &name_) const { // Convert name according to possible alias std::string name = getAlias(name_); // Get the definition std::map<std::string, ItemDefinition*>::const_iterator i; i = m_item_definitions.find(name); if(i == m_item_definitions.end()) i = m_item_definitions.find("unknown"); assert(i != m_item_definitions.end()); return *(i->second); } virtual const std::string &getAlias(const std::string &name) const { StringMap::const_iterator it = m_aliases.find(name); if (it != m_aliases.end()) return it->second; return name; } virtual void getAll(std::set<std::string> &result) const { result.clear(); for(std::map<std::string, ItemDefinition *>::const_iterator it = m_item_definitions.begin(); it != m_item_definitions.end(); ++it) { result.insert(it->first); } for (StringMap::const_iterator it = m_aliases.begin(); it != m_aliases.end(); ++it) { result.insert(it->first); } } virtual bool isKnown(const std::string &name_) const { // Convert name according to possible alias std::string name = getAlias(name_); // Get the definition std::map<std::string, ItemDefinition*>::const_iterator i; return m_item_definitions.find(name) != m_item_definitions.end(); } #ifndef SERVER public: ClientCached* createClientCachedDirect(const std::string &name, Client *client) const { infostream<<"Lazily creating item texture and mesh for \"" <<name<<"\""<<std::endl; // This is not thread-safe sanity_check(thr_is_current_thread(m_main_thread)); // Skip if already in cache ClientCached *cc = NULL; m_clientcached.get(name, &cc); if(cc) return cc; ITextureSource *tsrc = client->getTextureSource(); const ItemDefinition &def = get(name); // Create new ClientCached cc = new ClientCached(); // Create an inventory texture cc->inventory_texture = NULL; if(def.inventory_image != "") cc->inventory_texture = tsrc->getTexture(def.inventory_image); ItemStack item = ItemStack(); item.name = def.name; getItemMesh(client, item, &(cc->wield_mesh)); cc->palette = tsrc->getPalette(def.palette_image); // Put in cache m_clientcached.set(name, cc); return cc; } ClientCached* getClientCached(const std::string &name, Client *client) const { ClientCached *cc = NULL; m_clientcached.get(name, &cc); if(cc) return cc; if(thr_is_current_thread(m_main_thread)) { return createClientCachedDirect(name, client); } else { // We're gonna ask the result to be put into here static ResultQueue<std::string, ClientCached*, u8, u8> result_queue; // Throw a request in m_get_clientcached_queue.add(name, 0, 0, &result_queue); try{ while(true) { // Wait result for a second GetResult<std::string, ClientCached*, u8, u8> result = result_queue.pop_front(1000); if (result.key == name) { return result.item; } } } catch(ItemNotFoundException &e) { errorstream<<"Waiting for clientcached " << name << " timed out."<<std::endl; return &m_dummy_clientcached; } } } // Get item inventory texture virtual video::ITexture* getInventoryTexture(const std::string &name, Client *client) const { ClientCached *cc = getClientCached(name, client); if(!cc) return NULL; return cc->inventory_texture; } // Get item wield mesh virtual ItemMesh* getWieldMesh(const std::string &name, Client *client) const { ClientCached *cc = getClientCached(name, client); if(!cc) return NULL; return &(cc->wield_mesh); } // Get item palette virtual Palette* getPalette(const std::string &name, Client *client) const { ClientCached *cc = getClientCached(name, client); if(!cc) return NULL; return cc->palette; } virtual video::SColor getItemstackColor(const ItemStack &stack, Client *client) const { // Look for direct color definition const std::string &colorstring = stack.metadata.getString("color", 0); video::SColor directcolor; if ((colorstring != "") && parseColorString(colorstring, directcolor, true)) return directcolor; // See if there is a palette Palette *palette = getPalette(stack.name, client); const std::string &index = stack.metadata.getString("palette_index", 0); if ((palette != NULL) && (index != "")) return (*palette)[mystoi(index, 0, 255)]; // Fallback color return get(stack.name).color; } #endif void clear() { for(std::map<std::string, ItemDefinition*>::const_iterator i = m_item_definitions.begin(); i != m_item_definitions.end(); ++i) { delete i->second; } m_item_definitions.clear(); m_aliases.clear(); // Add the four builtin items: // "" is the hand // "unknown" is returned whenever an undefined item // is accessed (is also the unknown node) // "air" is the air node // "ignore" is the ignore node ItemDefinition* hand_def = new ItemDefinition; hand_def->name = ""; hand_def->wield_image = "wieldhand.png"; hand_def->tool_capabilities = new ToolCapabilities; m_item_definitions.insert(std::make_pair("", hand_def)); ItemDefinition* unknown_def = new ItemDefinition; unknown_def->type = ITEM_NODE; unknown_def->name = "unknown"; m_item_definitions.insert(std::make_pair("unknown", unknown_def)); ItemDefinition* air_def = new ItemDefinition; air_def->type = ITEM_NODE; air_def->name = "air"; m_item_definitions.insert(std::make_pair("air", air_def)); ItemDefinition* ignore_def = new ItemDefinition; ignore_def->type = ITEM_NODE; ignore_def->name = "ignore"; m_item_definitions.insert(std::make_pair("ignore", ignore_def)); } virtual void registerItem(const ItemDefinition &def) { verbosestream<<"ItemDefManager: registering \""<<def.name<<"\""<<std::endl; // Ensure that the "" item (the hand) always has ToolCapabilities if(def.name == "") FATAL_ERROR_IF(!def.tool_capabilities, "Hand does not have ToolCapabilities"); if(m_item_definitions.count(def.name) == 0) m_item_definitions[def.name] = new ItemDefinition(def); else *(m_item_definitions[def.name]) = def; // Remove conflicting alias if it exists bool alias_removed = (m_aliases.erase(def.name) != 0); if(alias_removed) infostream<<"ItemDefManager: erased alias "<<def.name <<" because item was defined"<<std::endl; } virtual void unregisterItem(const std::string &name) { verbosestream<<"ItemDefManager: unregistering \""<<name<<"\""<<std::endl; delete m_item_definitions[name]; m_item_definitions.erase(name); } virtual void registerAlias(const std::string &name, const std::string &convert_to) { if (m_item_definitions.find(name) == m_item_definitions.end()) { verbosestream<<"ItemDefManager: setting alias "<<name <<" -> "<<convert_to<<std::endl; m_aliases[name] = convert_to; } } void serialize(std::ostream &os, u16 protocol_version) { writeU8(os, 0); // version u16 count = m_item_definitions.size(); writeU16(os, count); for (std::map<std::string, ItemDefinition *>::const_iterator it = m_item_definitions.begin(); it != m_item_definitions.end(); ++it) { ItemDefinition *def = it->second; // Serialize ItemDefinition and write wrapped in a string std::ostringstream tmp_os(std::ios::binary); def->serialize(tmp_os, protocol_version); os << serializeString(tmp_os.str()); } writeU16(os, m_aliases.size()); for (StringMap::const_iterator it = m_aliases.begin(); it != m_aliases.end(); ++it) { os << serializeString(it->first); os << serializeString(it->second); } } void deSerialize(std::istream &is) { // Clear everything clear(); // Deserialize int version = readU8(is); if(version != 0) throw SerializationError("unsupported ItemDefManager version"); u16 count = readU16(is); for(u16 i=0; i<count; i++) { // Deserialize a string and grab an ItemDefinition from it std::istringstream tmp_is(deSerializeString(is), std::ios::binary); ItemDefinition def; def.deSerialize(tmp_is); // Register registerItem(def); } u16 num_aliases = readU16(is); for(u16 i=0; i<num_aliases; i++) { std::string name = deSerializeString(is); std::string convert_to = deSerializeString(is); registerAlias(name, convert_to); } } void processQueue(IGameDef *gamedef) { #ifndef SERVER //NOTE this is only thread safe for ONE consumer thread! while(!m_get_clientcached_queue.empty()) { GetRequest<std::string, ClientCached*, u8, u8> request = m_get_clientcached_queue.pop(); m_get_clientcached_queue.pushResult(request, createClientCachedDirect(request.key, (Client *)gamedef)); } #endif } private: // Key is name std::map<std::string, ItemDefinition*> m_item_definitions; // Aliases StringMap m_aliases; #ifndef SERVER // The id of the thread that is allowed to use irrlicht directly threadid_t m_main_thread; // A reference to this can be returned when nothing is found, to avoid NULLs mutable ClientCached m_dummy_clientcached; // Cached textures and meshes mutable MutexedMap<std::string, ClientCached*> m_clientcached; // Queued clientcached fetches (to be processed by the main thread) mutable RequestQueue<std::string, ClientCached*, u8, u8> m_get_clientcached_queue; #endif }; IWritableItemDefManager* createItemDefManager() { return new CItemDefManager(); }