Only keep players loaded while they're connected
[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 #include "hud.h"
22 #include "constants.h"
23 #include "gamedef.h"
24 #include "settings.h"
25 #include "content_sao.h"
26 #include "util/numeric.h"
27
28 Player::Player(IGameDef *gamedef):
29         touching_ground(false),
30         in_liquid(false),
31         in_liquid_stable(false),
32         liquid_viscosity(0),
33         is_climbing(false),
34         swimming_vertical(false),
35         camera_barely_in_ceiling(false),
36         light(0),
37         inventory(gamedef->idef()),
38         hp(PLAYER_MAX_HP),
39         hurt_tilt_timer(0),
40         hurt_tilt_strength(0),
41         peer_id(PEER_ID_INEXISTENT),
42         keyPressed(0),
43 // protected
44         m_gamedef(gamedef),
45         m_breath(-1),
46         m_pitch(0),
47         m_yaw(0),
48         m_speed(0,0,0),
49         m_position(0,0,0),
50         m_collisionbox(-BS*0.30,0.0,-BS*0.30,BS*0.30,BS*1.75,BS*0.30),
51         m_last_pitch(0),
52         m_last_yaw(0),
53         m_last_pos(0,0,0),
54         m_last_hp(PLAYER_MAX_HP),
55         m_last_inventory(gamedef->idef())
56 {
57         updateName("<not set>");
58         inventory.clear();
59         inventory.addList("main", PLAYER_INVENTORY_SIZE);
60         InventoryList *craft = inventory.addList("craft", 9);
61         craft->setWidth(3);
62         inventory.addList("craftpreview", 1);
63         inventory.addList("craftresult", 1);
64         m_last_inventory = inventory;
65
66         // Can be redefined via Lua
67         inventory_formspec = "size[8,7.5]"
68                 //"image[1,0.6;1,2;player.png]"
69                 "list[current_player;main;0,3.5;8,4;]"
70                 "list[current_player;craft;3,0;3,3;]"
71                 "list[current_player;craftpreview;7,1;1,1;]";
72
73         // Initialize movement settings at default values, so movement can work if the server fails to send them
74         movement_acceleration_default   = 3    * BS;
75         movement_acceleration_air       = 2    * BS;
76         movement_acceleration_fast      = 10   * BS;
77         movement_speed_walk             = 4    * BS;
78         movement_speed_crouch           = 1.35 * BS;
79         movement_speed_fast             = 20   * BS;
80         movement_speed_climb            = 2    * BS;
81         movement_speed_jump             = 6.5  * BS;
82         movement_liquid_fluidity        = 1    * BS;
83         movement_liquid_fluidity_smooth = 0.5  * BS;
84         movement_liquid_sink            = 10   * BS;
85         movement_gravity                = 9.81 * BS;
86
87         // Movement overrides are multipliers and must be 1 by default
88         physics_override_speed        = 1;
89         physics_override_jump         = 1;
90         physics_override_gravity      = 1;
91         physics_override_sneak        = true;
92         physics_override_sneak_glitch = true;
93
94         hud_flags = HUD_FLAG_HOTBAR_VISIBLE | HUD_FLAG_HEALTHBAR_VISIBLE |
95                          HUD_FLAG_CROSSHAIR_VISIBLE | HUD_FLAG_WIELDITEM_VISIBLE |
96                          HUD_FLAG_BREATHBAR_VISIBLE;
97
98         hud_hotbar_itemcount = HUD_HOTBAR_ITEMCOUNT_DEFAULT;
99 }
100
101 Player::~Player()
102 {
103 }
104
105 // Horizontal acceleration (X and Z), Y direction is ignored
106 void Player::accelerateHorizontal(v3f target_speed, f32 max_increase)
107 {
108         if(max_increase == 0)
109                 return;
110
111         v3f d_wanted = target_speed - m_speed;
112         d_wanted.Y = 0;
113         f32 dl = d_wanted.getLength();
114         if(dl > max_increase)
115                 dl = max_increase;
116         
117         v3f d = d_wanted.normalize() * dl;
118
119         m_speed.X += d.X;
120         m_speed.Z += d.Z;
121
122 #if 0 // old code
123         if(m_speed.X < target_speed.X - max_increase)
124                 m_speed.X += max_increase;
125         else if(m_speed.X > target_speed.X + max_increase)
126                 m_speed.X -= max_increase;
127         else if(m_speed.X < target_speed.X)
128                 m_speed.X = target_speed.X;
129         else if(m_speed.X > target_speed.X)
130                 m_speed.X = target_speed.X;
131
132         if(m_speed.Z < target_speed.Z - max_increase)
133                 m_speed.Z += max_increase;
134         else if(m_speed.Z > target_speed.Z + max_increase)
135                 m_speed.Z -= max_increase;
136         else if(m_speed.Z < target_speed.Z)
137                 m_speed.Z = target_speed.Z;
138         else if(m_speed.Z > target_speed.Z)
139                 m_speed.Z = target_speed.Z;
140 #endif
141 }
142
143 // Vertical acceleration (Y), X and Z directions are ignored
144 void Player::accelerateVertical(v3f target_speed, f32 max_increase)
145 {
146         if(max_increase == 0)
147                 return;
148
149         f32 d_wanted = target_speed.Y - m_speed.Y;
150         if(d_wanted > max_increase)
151                 d_wanted = max_increase;
152         else if(d_wanted < -max_increase)
153                 d_wanted = -max_increase;
154
155         m_speed.Y += d_wanted;
156
157 #if 0 // old code
158         if(m_speed.Y < target_speed.Y - max_increase)
159                 m_speed.Y += max_increase;
160         else if(m_speed.Y > target_speed.Y + max_increase)
161                 m_speed.Y -= max_increase;
162         else if(m_speed.Y < target_speed.Y)
163                 m_speed.Y = target_speed.Y;
164         else if(m_speed.Y > target_speed.Y)
165                 m_speed.Y = target_speed.Y;
166 #endif
167 }
168
169 v3s16 Player::getLightPosition() const
170 {
171         return floatToInt(m_position + v3f(0,BS+BS/2,0), BS);
172 }
173
174 void Player::serialize(std::ostream &os)
175 {
176         // Utilize a Settings object for storing values
177         Settings args;
178         args.setS32("version", 1);
179         args.set("name", m_name);
180         //args.set("password", m_password);
181         args.setFloat("pitch", m_pitch);
182         args.setFloat("yaw", m_yaw);
183         args.setV3F("position", m_position);
184         args.setS32("hp", hp);
185         args.setS32("breath", m_breath);
186
187         args.writeLines(os);
188
189         os<<"PlayerArgsEnd\n";
190
191         inventory.serialize(os);
192 }
193
194 void Player::deSerialize(std::istream &is, std::string playername)
195 {
196         Settings args;
197         
198         for(;;)
199         {
200                 if(is.eof())
201                         throw SerializationError
202                                         (("Player::deSerialize(): PlayerArgsEnd of player \"" + playername + "\" not found").c_str());
203                 std::string line;
204                 std::getline(is, line);
205                 std::string trimmedline = trim(line);
206                 if(trimmedline == "PlayerArgsEnd")
207                         break;
208                 args.parseConfigLine(line);
209         }
210
211         //args.getS32("version"); // Version field value not used
212         std::string name = args.get("name");
213         updateName(name.c_str());
214         setPitch(args.getFloat("pitch"));
215         setYaw(args.getFloat("yaw"));
216         setPosition(args.getV3F("position"));
217         try{
218                 hp = args.getS32("hp");
219         }catch(SettingNotFoundException &e) {
220                 hp = 20;
221         }
222         try{
223                 m_breath = args.getS32("breath");
224         }catch(SettingNotFoundException &e) {
225                 m_breath = 11;
226         }
227
228         inventory.deSerialize(is);
229
230         if(inventory.getList("craftpreview") == NULL) {
231                 // Convert players without craftpreview
232                 inventory.addList("craftpreview", 1);
233
234                 bool craftresult_is_preview = true;
235                 if(args.exists("craftresult_is_preview"))
236                         craftresult_is_preview = args.getBool("craftresult_is_preview");
237                 if(craftresult_is_preview)
238                 {
239                         // Clear craftresult
240                         inventory.getList("craftresult")->changeItem(0, ItemStack());
241                 }
242         }
243
244         // Set m_last_*
245         checkModified();
246 }
247
248 u32 Player::addHud(HudElement *toadd)
249 {
250         u32 id = getFreeHudID();
251
252         if (id < hud.size())
253                 hud[id] = toadd;
254         else
255                 hud.push_back(toadd);
256
257         return id;
258 }
259
260 HudElement* Player::getHud(u32 id)
261 {
262         if (id < hud.size())
263                 return hud[id];
264
265         return NULL;
266 }
267
268 HudElement* Player::removeHud(u32 id)
269 {
270         HudElement* retval = NULL;
271         if (id < hud.size()) {
272                 retval = hud[id];
273                 hud[id] = NULL;
274         }
275         return retval;
276 }
277
278 void Player::clearHud()
279 {
280         while(!hud.empty()) {
281                 delete hud.back();
282                 hud.pop_back();
283         }
284 }
285
286
287 void RemotePlayer::save(const std::string &savedir)
288 {
289         bool newplayer = true;
290
291         /* We have to iterate through all files in the players directory
292          * and check their player names because some file systems are not
293          * case-sensitive and player names are case-sensitive.
294          */
295
296         // A player to deserialize files into to check their names
297         RemotePlayer testplayer(m_gamedef);
298
299         std::vector<fs::DirListNode> player_files = fs::GetDirListing(savedir);
300         for(u32 i = 0; i < player_files.size(); i++) {
301                 if (player_files[i].dir || player_files[i].name[0] == '.') {
302                         continue;
303                 }
304
305                 // Full path to this file
306                 std::string path = savedir + "/" + player_files[i].name;
307
308                 // Open file and deserialize
309                 std::ifstream is(path.c_str(), std::ios_base::binary);
310                 if (!is.good()) {
311                         infostream << "Failed to read " << path << std::endl;
312                         continue;
313                 }
314                 testplayer.deSerialize(is, player_files[i].name);
315
316                 if (strcmp(testplayer.getName(), m_name) == 0) {
317                         // Open file and serialize
318                         std::ostringstream ss(std::ios_base::binary);
319                         serialize(ss);
320                         if (!fs::safeWriteToFile(path, ss.str())) {
321                                 infostream << "Failed to write " << path << std::endl;
322                         }
323                         newplayer = false;
324                         break;
325                 }
326         }
327
328         if (newplayer) {
329                 bool found = false;
330                 std::string path = savedir + "/" + m_name;
331                 for (u32 i = 0; i < 1000; i++) {
332                         if (!fs::PathExists(path)) {
333                                 found = true;
334                                 break;
335                         }
336                         path = savedir + "/" + m_name + itos(i);
337                 }
338                 if (!found) {
339                         infostream << "Didn't find free file for player " << m_name << std::endl;
340                         return;
341                 }
342
343                 // Open file and serialize
344                 std::ostringstream ss(std::ios_base::binary);
345                 serialize(ss);
346                 if (!fs::safeWriteToFile(path, ss.str())) {
347                         infostream << "Failed to write " << path << std::endl;
348                 }
349         }
350 }
351
352 /*
353         RemotePlayer
354 */
355 void RemotePlayer::setPosition(const v3f &position)
356 {
357         Player::setPosition(position);
358         if(m_sao)
359                 m_sao->setBasePosition(position);
360 }
361