Fix player teleportation bug whilst sneaking
[oweals/minetest.git] / src / player.cpp
1 /*
2 Minetest
3 Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #include "player.h"
21
22 #include <fstream>
23 #include "threading/mutex_auto_lock.h"
24 #include "util/numeric.h"
25 #include "hud.h"
26 #include "constants.h"
27 #include "gamedef.h"
28 #include "settings.h"
29 #include "content_sao.h"
30 #include "filesys.h"
31 #include "log.h"
32 #include "porting.h"  // strlcpy
33
34
35 Player::Player(IGameDef *gamedef, const char *name):
36         got_teleported(false),
37         touching_ground(false),
38         in_liquid(false),
39         in_liquid_stable(false),
40         liquid_viscosity(0),
41         is_climbing(false),
42         swimming_vertical(false),
43         camera_barely_in_ceiling(false),
44         inventory(gamedef->idef()),
45         hp(PLAYER_MAX_HP),
46         hurt_tilt_timer(0),
47         hurt_tilt_strength(0),
48         protocol_version(0),
49         peer_id(PEER_ID_INEXISTENT),
50         keyPressed(0),
51 // protected
52         m_gamedef(gamedef),
53         m_breath(PLAYER_MAX_BREATH),
54         m_pitch(0),
55         m_yaw(0),
56         m_speed(0,0,0),
57         m_position(0,0,0),
58         m_collisionbox(-BS*0.30,0.0,-BS*0.30,BS*0.30,BS*1.75,BS*0.30),
59         m_dirty(false)
60 {
61         strlcpy(m_name, name, PLAYERNAME_SIZE);
62
63         inventory.clear();
64         inventory.addList("main", PLAYER_INVENTORY_SIZE);
65         InventoryList *craft = inventory.addList("craft", 9);
66         craft->setWidth(3);
67         inventory.addList("craftpreview", 1);
68         inventory.addList("craftresult", 1);
69         inventory.setModified(false);
70
71         // Can be redefined via Lua
72         inventory_formspec = "size[8,7.5]"
73                 //"image[1,0.6;1,2;player.png]"
74                 "list[current_player;main;0,3.5;8,4;]"
75                 "list[current_player;craft;3,0;3,3;]"
76                 "listring[]"
77                 "list[current_player;craftpreview;7,1;1,1;]";
78
79         // Initialize movement settings at default values, so movement can work
80         // if the server fails to send them
81         movement_acceleration_default   = 3    * BS;
82         movement_acceleration_air       = 2    * BS;
83         movement_acceleration_fast      = 10   * BS;
84         movement_speed_walk             = 4    * BS;
85         movement_speed_crouch           = 1.35 * BS;
86         movement_speed_fast             = 20   * BS;
87         movement_speed_climb            = 2    * BS;
88         movement_speed_jump             = 6.5  * BS;
89         movement_liquid_fluidity        = 1    * BS;
90         movement_liquid_fluidity_smooth = 0.5  * BS;
91         movement_liquid_sink            = 10   * BS;
92         movement_gravity                = 9.81 * BS;
93         local_animation_speed           = 0.0;
94
95         // Movement overrides are multipliers and must be 1 by default
96         physics_override_speed        = 1;
97         physics_override_jump         = 1;
98         physics_override_gravity      = 1;
99         physics_override_sneak        = true;
100         physics_override_sneak_glitch = true;
101
102         hud_flags =
103                 HUD_FLAG_HOTBAR_VISIBLE    | HUD_FLAG_HEALTHBAR_VISIBLE |
104                 HUD_FLAG_CROSSHAIR_VISIBLE | HUD_FLAG_WIELDITEM_VISIBLE |
105                 HUD_FLAG_BREATHBAR_VISIBLE | HUD_FLAG_MINIMAP_VISIBLE;
106
107         hud_hotbar_itemcount = HUD_HOTBAR_ITEMCOUNT_DEFAULT;
108 }
109
110 Player::~Player()
111 {
112         clearHud();
113 }
114
115 v3s16 Player::getLightPosition() const
116 {
117         return floatToInt(m_position + v3f(0,BS+BS/2,0), BS);
118 }
119
120 void Player::serialize(std::ostream &os)
121 {
122         // Utilize a Settings object for storing values
123         Settings args;
124         args.setS32("version", 1);
125         args.set("name", m_name);
126         //args.set("password", m_password);
127         args.setFloat("pitch", m_pitch);
128         args.setFloat("yaw", m_yaw);
129         args.setV3F("position", m_position);
130         args.setS32("hp", hp);
131         args.setS32("breath", m_breath);
132
133         args.writeLines(os);
134
135         os<<"PlayerArgsEnd\n";
136
137         inventory.serialize(os);
138 }
139
140 void Player::deSerialize(std::istream &is, std::string playername)
141 {
142         Settings args;
143
144         if (!args.parseConfigLines(is, "PlayerArgsEnd")) {
145                 throw SerializationError("PlayerArgsEnd of player " +
146                                 playername + " not found!");
147         }
148
149         m_dirty = true;
150         //args.getS32("version"); // Version field value not used
151         std::string name = args.get("name");
152         strlcpy(m_name, name.c_str(), PLAYERNAME_SIZE);
153         setPitch(args.getFloat("pitch"));
154         setYaw(args.getFloat("yaw"));
155         setPosition(args.getV3F("position"));
156         try{
157                 hp = args.getS32("hp");
158         }catch(SettingNotFoundException &e) {
159                 hp = PLAYER_MAX_HP;
160         }
161         try{
162                 m_breath = args.getS32("breath");
163         }catch(SettingNotFoundException &e) {
164                 m_breath = PLAYER_MAX_BREATH;
165         }
166
167         inventory.deSerialize(is);
168
169         if(inventory.getList("craftpreview") == NULL) {
170                 // Convert players without craftpreview
171                 inventory.addList("craftpreview", 1);
172
173                 bool craftresult_is_preview = true;
174                 if(args.exists("craftresult_is_preview"))
175                         craftresult_is_preview = args.getBool("craftresult_is_preview");
176                 if(craftresult_is_preview)
177                 {
178                         // Clear craftresult
179                         inventory.getList("craftresult")->changeItem(0, ItemStack());
180                 }
181         }
182 }
183
184 u32 Player::addHud(HudElement *toadd)
185 {
186         MutexAutoLock lock(m_mutex);
187
188         u32 id = getFreeHudID();
189
190         if (id < hud.size())
191                 hud[id] = toadd;
192         else
193                 hud.push_back(toadd);
194
195         return id;
196 }
197
198 HudElement* Player::getHud(u32 id)
199 {
200         MutexAutoLock lock(m_mutex);
201
202         if (id < hud.size())
203                 return hud[id];
204
205         return NULL;
206 }
207
208 HudElement* Player::removeHud(u32 id)
209 {
210         MutexAutoLock lock(m_mutex);
211
212         HudElement* retval = NULL;
213         if (id < hud.size()) {
214                 retval = hud[id];
215                 hud[id] = NULL;
216         }
217         return retval;
218 }
219
220 void Player::clearHud()
221 {
222         MutexAutoLock lock(m_mutex);
223
224         while(!hud.empty()) {
225                 delete hud.back();
226                 hud.pop_back();
227         }
228 }
229
230 RemotePlayer::RemotePlayer(IGameDef *gamedef, const char *name):
231         Player(gamedef, name),
232         m_sao(NULL)
233 {
234         movement_acceleration_default   = g_settings->getFloat("movement_acceleration_default")   * BS;
235         movement_acceleration_air       = g_settings->getFloat("movement_acceleration_air")       * BS;
236         movement_acceleration_fast      = g_settings->getFloat("movement_acceleration_fast")      * BS;
237         movement_speed_walk             = g_settings->getFloat("movement_speed_walk")             * BS;
238         movement_speed_crouch           = g_settings->getFloat("movement_speed_crouch")           * BS;
239         movement_speed_fast             = g_settings->getFloat("movement_speed_fast")             * BS;
240         movement_speed_climb            = g_settings->getFloat("movement_speed_climb")            * BS;
241         movement_speed_jump             = g_settings->getFloat("movement_speed_jump")             * BS;
242         movement_liquid_fluidity        = g_settings->getFloat("movement_liquid_fluidity")        * BS;
243         movement_liquid_fluidity_smooth = g_settings->getFloat("movement_liquid_fluidity_smooth") * BS;
244         movement_liquid_sink            = g_settings->getFloat("movement_liquid_sink")            * BS;
245         movement_gravity                = g_settings->getFloat("movement_gravity")                * BS;
246 }
247
248 void RemotePlayer::save(std::string savedir)
249 {
250         /*
251          * We have to open all possible player files in the players directory
252          * and check their player names because some file systems are not
253          * case-sensitive and player names are case-sensitive.
254          */
255
256         // A player to deserialize files into to check their names
257         RemotePlayer testplayer(m_gamedef, "");
258
259         savedir += DIR_DELIM;
260         std::string path = savedir + m_name;
261         for (u32 i = 0; i < PLAYER_FILE_ALTERNATE_TRIES; i++) {
262                 if (!fs::PathExists(path)) {
263                         // Open file and serialize
264                         std::ostringstream ss(std::ios_base::binary);
265                         serialize(ss);
266                         if (!fs::safeWriteToFile(path, ss.str())) {
267                                 infostream << "Failed to write " << path << std::endl;
268                         }
269                         setModified(false);
270                         return;
271                 }
272                 // Open file and deserialize
273                 std::ifstream is(path.c_str(), std::ios_base::binary);
274                 if (!is.good()) {
275                         infostream << "Failed to open " << path << std::endl;
276                         return;
277                 }
278                 testplayer.deSerialize(is, path);
279                 is.close();
280                 if (strcmp(testplayer.getName(), m_name) == 0) {
281                         // Open file and serialize
282                         std::ostringstream ss(std::ios_base::binary);
283                         serialize(ss);
284                         if (!fs::safeWriteToFile(path, ss.str())) {
285                                 infostream << "Failed to write " << path << std::endl;
286                         }
287                         setModified(false);
288                         return;
289                 }
290                 path = savedir + m_name + itos(i);
291         }
292
293         infostream << "Didn't find free file for player " << m_name << std::endl;
294         return;
295 }
296
297 /*
298         RemotePlayer
299 */
300 void RemotePlayer::setPosition(const v3f &position)
301 {
302         Player::setPosition(position);
303         if(m_sao)
304                 m_sao->setBasePosition(position);
305 }
306