]> git.lizzy.rs Git - dragonfireclient.git/blob - src/remoteplayer.cpp
Some performance optimizations (#5424)
[dragonfireclient.git] / src / remoteplayer.cpp
1 /*
2 Minetest
3 Copyright (C) 2010-2016 celeron55, Perttu Ahola <celeron55@gmail.com>
4 Copyright (C) 2014-2016 nerzhul, Loic Blot <loic.blot@unix-experience.fr>
5
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.
10
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.
15
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.
19 */
20
21 #include "remoteplayer.h"
22 #include <json/json.h>
23 #include "content_sao.h"
24 #include "filesys.h"
25 #include "gamedef.h"
26 #include "porting.h"  // strlcpy
27 #include "server.h"
28 #include "settings.h"
29
30 /*
31         RemotePlayer
32 */
33 // static config cache for remoteplayer
34 bool RemotePlayer::m_setting_cache_loaded = false;
35 float RemotePlayer::m_setting_chat_message_limit_per_10sec = 0.0f;
36 u16 RemotePlayer::m_setting_chat_message_limit_trigger_kick = 0;
37
38 RemotePlayer::RemotePlayer(const char *name, IItemDefManager *idef):
39         Player(name, idef),
40         protocol_version(0),
41         m_sao(NULL),
42         m_dirty(false),
43         m_last_chat_message_sent(time(NULL)),
44         m_chat_message_allowance(5.0f),
45         m_message_rate_overhead(0),
46         hud_hotbar_image(""),
47         hud_hotbar_selected_image("")
48 {
49         if (!RemotePlayer::m_setting_cache_loaded) {
50                 RemotePlayer::m_setting_chat_message_limit_per_10sec =
51                         g_settings->getFloat("chat_message_limit_per_10sec");
52                 RemotePlayer::m_setting_chat_message_limit_trigger_kick =
53                         g_settings->getU16("chat_message_limit_trigger_kick");
54                 RemotePlayer::m_setting_cache_loaded = true;
55         }
56         movement_acceleration_default   = g_settings->getFloat("movement_acceleration_default")   * BS;
57         movement_acceleration_air       = g_settings->getFloat("movement_acceleration_air")       * BS;
58         movement_acceleration_fast      = g_settings->getFloat("movement_acceleration_fast")      * BS;
59         movement_speed_walk             = g_settings->getFloat("movement_speed_walk")             * BS;
60         movement_speed_crouch           = g_settings->getFloat("movement_speed_crouch")           * BS;
61         movement_speed_fast             = g_settings->getFloat("movement_speed_fast")             * BS;
62         movement_speed_climb            = g_settings->getFloat("movement_speed_climb")            * BS;
63         movement_speed_jump             = g_settings->getFloat("movement_speed_jump")             * BS;
64         movement_liquid_fluidity        = g_settings->getFloat("movement_liquid_fluidity")        * BS;
65         movement_liquid_fluidity_smooth = g_settings->getFloat("movement_liquid_fluidity_smooth") * BS;
66         movement_liquid_sink            = g_settings->getFloat("movement_liquid_sink")            * BS;
67         movement_gravity                = g_settings->getFloat("movement_gravity")                * BS;
68 }
69
70 void RemotePlayer::save(std::string savedir, IGameDef *gamedef)
71 {
72         /*
73          * We have to open all possible player files in the players directory
74          * and check their player names because some file systems are not
75          * case-sensitive and player names are case-sensitive.
76          */
77
78         // A player to deserialize files into to check their names
79         RemotePlayer testplayer("", gamedef->idef());
80
81         savedir += DIR_DELIM;
82         std::string path = savedir + m_name;
83         for (u32 i = 0; i < PLAYER_FILE_ALTERNATE_TRIES; i++) {
84                 if (!fs::PathExists(path)) {
85                         // Open file and serialize
86                         std::ostringstream ss(std::ios_base::binary);
87                         serialize(ss);
88                         if (!fs::safeWriteToFile(path, ss.str())) {
89                                 infostream << "Failed to write " << path << std::endl;
90                         }
91                         setModified(false);
92                         return;
93                 }
94                 // Open file and deserialize
95                 std::ifstream is(path.c_str(), std::ios_base::binary);
96                 if (!is.good()) {
97                         infostream << "Failed to open " << path << std::endl;
98                         return;
99                 }
100                 testplayer.deSerialize(is, path, NULL);
101                 is.close();
102                 if (strcmp(testplayer.getName(), m_name) == 0) {
103                         // Open file and serialize
104                         std::ostringstream ss(std::ios_base::binary);
105                         serialize(ss);
106                         if (!fs::safeWriteToFile(path, ss.str())) {
107                                 infostream << "Failed to write " << path << std::endl;
108                         }
109                         setModified(false);
110                         return;
111                 }
112                 path = savedir + m_name + itos(i);
113         }
114
115         infostream << "Didn't find free file for player " << m_name << std::endl;
116 }
117
118 void RemotePlayer::serializeExtraAttributes(std::string &output)
119 {
120         assert(m_sao);
121         Json::Value json_root;
122         const PlayerAttributes &attrs = m_sao->getExtendedAttributes();
123         for (PlayerAttributes::const_iterator it = attrs.begin(); it != attrs.end(); ++it) {
124                 json_root[(*it).first] = (*it).second;
125         }
126
127         Json::FastWriter writer;
128         output = writer.write(json_root);
129         m_sao->setExtendedAttributeModified(false);
130 }
131
132
133 void RemotePlayer::deSerialize(std::istream &is, const std::string &playername,
134                 PlayerSAO *sao)
135 {
136         Settings args;
137
138         if (!args.parseConfigLines(is, "PlayerArgsEnd")) {
139                 throw SerializationError("PlayerArgsEnd of player " + playername + " not found!");
140         }
141
142         m_dirty = true;
143         //args.getS32("version"); // Version field value not used
144         const std::string &name = args.get("name");
145         strlcpy(m_name, name.c_str(), PLAYERNAME_SIZE);
146
147         if (sao) {
148                 try {
149                         sao->setHPRaw(args.getS32("hp"));
150                 } catch(SettingNotFoundException &e) {
151                         sao->setHPRaw(PLAYER_MAX_HP);
152                 }
153
154                 try {
155                         sao->setBasePosition(args.getV3F("position"));
156                 } catch (SettingNotFoundException &e) {}
157
158                 try {
159                         sao->setPitch(args.getFloat("pitch"));
160                 } catch (SettingNotFoundException &e) {}
161                 try {
162                         sao->setYaw(args.getFloat("yaw"));
163                 } catch (SettingNotFoundException &e) {}
164
165                 try {
166                         sao->setBreath(args.getS32("breath"), false);
167                 } catch (SettingNotFoundException &e) {}
168
169                 try {
170                         const std::string &extended_attributes = args.get("extended_attributes");
171                         Json::Reader reader;
172                         Json::Value attr_root;
173                         reader.parse(extended_attributes, attr_root);
174
175                         const Json::Value::Members attr_list = attr_root.getMemberNames();
176                         for (Json::Value::Members::const_iterator it = attr_list.begin();
177                                         it != attr_list.end(); ++it) {
178                                 Json::Value attr_value = attr_root[*it];
179                                 sao->setExtendedAttribute(*it, attr_value.asString());
180                         }
181                 } catch (SettingNotFoundException &e) {}
182         }
183
184         inventory.deSerialize(is);
185
186         if (inventory.getList("craftpreview") == NULL) {
187                 // Convert players without craftpreview
188                 inventory.addList("craftpreview", 1);
189
190                 bool craftresult_is_preview = true;
191                 if(args.exists("craftresult_is_preview"))
192                         craftresult_is_preview = args.getBool("craftresult_is_preview");
193                 if(craftresult_is_preview)
194                 {
195                         // Clear craftresult
196                         inventory.getList("craftresult")->changeItem(0, ItemStack());
197                 }
198         }
199 }
200
201 void RemotePlayer::serialize(std::ostream &os)
202 {
203         // Utilize a Settings object for storing values
204         Settings args;
205         args.setS32("version", 1);
206         args.set("name", m_name);
207
208         // This should not happen
209         assert(m_sao);
210         args.setS32("hp", m_sao->getHP());
211         args.setV3F("position", m_sao->getBasePosition());
212         args.setFloat("pitch", m_sao->getPitch());
213         args.setFloat("yaw", m_sao->getYaw());
214         args.setS32("breath", m_sao->getBreath());
215
216         std::string extended_attrs = "";
217         serializeExtraAttributes(extended_attrs);
218         args.set("extended_attributes", extended_attrs);
219
220         args.writeLines(os);
221
222         os<<"PlayerArgsEnd\n";
223
224         inventory.serialize(os);
225 }
226
227 const RemotePlayerChatResult RemotePlayer::canSendChatMessage()
228 {
229         // Rate limit messages
230         u32 now = time(NULL);
231         float time_passed = now - m_last_chat_message_sent;
232         m_last_chat_message_sent = now;
233
234         // If this feature is disabled
235         if (m_setting_chat_message_limit_per_10sec <= 0.0) {
236                 return RPLAYER_CHATRESULT_OK;
237         }
238
239         m_chat_message_allowance += time_passed * (m_setting_chat_message_limit_per_10sec / 8.0f);
240         if (m_chat_message_allowance > m_setting_chat_message_limit_per_10sec) {
241                 m_chat_message_allowance = m_setting_chat_message_limit_per_10sec;
242         }
243
244         if (m_chat_message_allowance < 1.0f) {
245                 infostream << "Player " << m_name
246                                 << " chat limited due to excessive message amount." << std::endl;
247
248                 // Kick player if flooding is too intensive
249                 m_message_rate_overhead++;
250                 if (m_message_rate_overhead > RemotePlayer::m_setting_chat_message_limit_trigger_kick) {
251                         return RPLAYER_CHATRESULT_KICK;
252                 }
253
254                 return RPLAYER_CHATRESULT_FLOODING;
255         }
256
257         // Reinit message overhead
258         if (m_message_rate_overhead > 0) {
259                 m_message_rate_overhead = 0;
260         }
261
262         m_chat_message_allowance -= 1.0f;
263         return RPLAYER_CHATRESULT_OK;
264 }