tweaking mapgenv2 settings for maximum awesomeness.
[oweals/minetest.git] / src / environment.cpp
1 /*
2 Minetest-c55
3 Copyright (C) 2010 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 General Public License as published by
7 the Free Software Foundation; either version 2 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 General Public License for more details.
14
15 You should have received a copy of the GNU 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 "environment.h"
21 #include "filesys.h"
22
23 Environment::Environment(Map *map, std::ostream &dout):
24                 m_dout(dout)
25 {
26         m_map = map;
27         m_daynight_ratio = 0.2;
28 }
29
30 Environment::~Environment()
31 {
32         // Deallocate players
33         for(core::list<Player*>::Iterator i = m_players.begin();
34                         i != m_players.end(); i++)
35         {
36                 delete (*i);
37         }
38         
39         // The map is removed by the SceneManager
40         m_map->drop();
41         //delete m_map;
42 }
43
44 void Environment::step(float dtime)
45 {
46         DSTACK(__FUNCTION_NAME);
47         /*
48                 Run Map's timers
49         */
50         //TimeTaker maptimerupdatetimer("m_map->timerUpdate()", g_device);
51         // 0ms
52         m_map->timerUpdate(dtime);
53         //maptimerupdatetimer.stop();
54
55         /*
56                 Get the highest speed some player is going
57         */
58         //TimeTaker playerspeed("playerspeed", g_device);
59         // 0ms
60         f32 maximum_player_speed = 0.001; // just some small value
61         for(core::list<Player*>::Iterator i = m_players.begin();
62                         i != m_players.end(); i++)
63         {
64                 f32 speed = (*i)->getSpeed().getLength();
65                 if(speed > maximum_player_speed)
66                         maximum_player_speed = speed;
67         }
68         //playerspeed.stop();
69         
70         // Maximum time increment (for collision detection etc)
71         // Allow 0.1 blocks per increment
72         // time = distance / speed
73         f32 dtime_max_increment = 0.1*BS / maximum_player_speed;
74         // Maximum time increment is 10ms or lower
75         if(dtime_max_increment > 0.01)
76                 dtime_max_increment = 0.01;
77         
78         //TimeTaker playerupdate("playerupdate", g_device);
79         
80         /*
81                 Stuff that has a maximum time increment
82         */
83         // Don't allow overly huge dtime
84         if(dtime > 0.5)
85                 dtime = 0.5;
86
87         u32 loopcount = 0;
88         do
89         {
90                 loopcount++;
91
92                 f32 dtime_part;
93                 if(dtime > dtime_max_increment)
94                         dtime_part = dtime_max_increment;
95                 else
96                         dtime_part = dtime;
97                 dtime -= dtime_part;
98                 
99                 /*
100                         Handle players
101                 */
102                 for(core::list<Player*>::Iterator i = m_players.begin();
103                                 i != m_players.end(); i++)
104                 {
105                         Player *player = *i;
106
107                         v3f playerpos = player->getPosition();
108                         
109                         // Apply physics to local player
110                         bool haxmode = g_settings.getBool("haxmode");
111                         if(player->isLocal() && haxmode == false)
112                         {
113                                 // Apply gravity to local player
114                                 v3f speed = player->getSpeed();
115                                 if(player->swimming_up == false)
116                                         speed.Y -= 9.81 * BS * dtime_part * 2;
117
118                                 /*
119                                         Apply water resistance
120                                 */
121                                 if(player->in_water)
122                                 {
123                                         f32 max_down = 1.0*BS;
124                                         if(speed.Y < -max_down) speed.Y = -max_down;
125
126                                         f32 max = 2.5*BS;
127                                         if(speed.getLength() > max)
128                                         {
129                                                 speed = speed / speed.getLength() * max;
130                                         }
131                                 }
132
133                                 player->setSpeed(speed);
134                         }
135
136                         /*
137                                 Move the player.
138                                 For local player, this also calculates collision detection.
139                         */
140                         player->move(dtime_part, *m_map);
141                         
142                         /*
143                                 Update lighting on remote players on client
144                         */
145                         u8 light = LIGHT_MAX;
146                         try{
147                                 // Get node at feet
148                                 v3s16 p = floatToInt(playerpos + v3f(0,BS/4,0));
149                                 MapNode n = m_map->getNode(p);
150                                 light = n.getLightBlend(m_daynight_ratio);
151                         }
152                         catch(InvalidPositionException &e) {}
153                         player->updateLight(light);
154
155                         /*
156                                 Add footsteps to grass
157                         */
158                         // Get node that is at BS/4 under player
159                         v3s16 bottompos = floatToInt(playerpos + v3f(0,-BS/4,0));
160                         try{
161                                 MapNode n = m_map->getNode(bottompos);
162                                 if(n.d == CONTENT_GRASS)
163                                 {
164                                         n.d = CONTENT_GRASS_FOOTSTEPS;
165                                         m_map->setNode(bottompos, n);
166 #ifndef SERVER
167                                         // Update mesh on client
168                                         if(m_map->mapType() == MAPTYPE_CLIENT)
169                                         {
170                                                 v3s16 p_blocks = getNodeBlockPos(bottompos);
171                                                 MapBlock *b = m_map->getBlockNoCreate(p_blocks);
172                                                 b->updateMesh(m_daynight_ratio);
173                                         }
174 #endif
175                                 }
176                         }
177                         catch(InvalidPositionException &e)
178                         {
179                         }
180                 }
181         }
182         while(dtime > 0.001);
183         
184         //std::cout<<"Looped "<<loopcount<<" times."<<std::endl;
185 }
186
187 Map & Environment::getMap()
188 {
189         return *m_map;
190 }
191
192 void Environment::addPlayer(Player *player)
193 {
194         DSTACK(__FUNCTION_NAME);
195         /*
196                 Check that only one local player exists and peer_ids are unique.
197                 Also check that names are unique.
198                 Exception: there can be multiple players with peer_id=0
199         */
200 #ifndef SERVER
201         /*
202                 It is a failure if player is local and there already is a local
203                 player
204         */
205         assert(!(player->isLocal() == true && getLocalPlayer() != NULL));
206 #endif
207         // If peer id is non-zero, it has to be unique.
208         if(player->peer_id != 0)
209                 assert(getPlayer(player->peer_id) == NULL);
210         // Name has to be unique.
211         assert(getPlayer(player->getName()) == NULL);
212         // Add.
213         m_players.push_back(player);
214 }
215
216 void Environment::removePlayer(u16 peer_id)
217 {
218         DSTACK(__FUNCTION_NAME);
219 re_search:
220         for(core::list<Player*>::Iterator i = m_players.begin();
221                         i != m_players.end(); i++)
222         {
223                 Player *player = *i;
224                 if(player->peer_id != peer_id)
225                         continue;
226                 
227                 delete player;
228                 m_players.erase(i);
229                 // See if there is an another one
230                 // (shouldn't be, but just to be sure)
231                 goto re_search;
232         }
233 }
234
235 #ifndef SERVER
236 LocalPlayer * Environment::getLocalPlayer()
237 {
238         for(core::list<Player*>::Iterator i = m_players.begin();
239                         i != m_players.end(); i++)
240         {
241                 Player *player = *i;
242                 if(player->isLocal())
243                         return (LocalPlayer*)player;
244         }
245         return NULL;
246 }
247 #endif
248
249 Player * Environment::getPlayer(u16 peer_id)
250 {
251         for(core::list<Player*>::Iterator i = m_players.begin();
252                         i != m_players.end(); i++)
253         {
254                 Player *player = *i;
255                 if(player->peer_id == peer_id)
256                         return player;
257         }
258         return NULL;
259 }
260
261 Player * Environment::getPlayer(const char *name)
262 {
263         for(core::list<Player*>::Iterator i = m_players.begin();
264                         i != m_players.end(); i++)
265         {
266                 Player *player = *i;
267                 if(strcmp(player->getName(), name) == 0)
268                         return player;
269         }
270         return NULL;
271 }
272
273 core::list<Player*> Environment::getPlayers()
274 {
275         return m_players;
276 }
277
278 core::list<Player*> Environment::getPlayers(bool ignore_disconnected)
279 {
280         core::list<Player*> newlist;
281         for(core::list<Player*>::Iterator
282                         i = m_players.begin();
283                         i != m_players.end(); i++)
284         {
285                 Player *player = *i;
286                 
287                 if(ignore_disconnected)
288                 {
289                         // Ignore disconnected players
290                         if(player->peer_id == 0)
291                                 continue;
292                 }
293
294                 newlist.push_back(player);
295         }
296         return newlist;
297 }
298
299 void Environment::printPlayers(std::ostream &o)
300 {
301         o<<"Players in environment:"<<std::endl;
302         for(core::list<Player*>::Iterator i = m_players.begin();
303                         i != m_players.end(); i++)
304         {
305                 Player *player = *i;
306                 o<<"Player peer_id="<<player->peer_id<<std::endl;
307         }
308 }
309
310 void Environment::serializePlayers(const std::string &savedir)
311 {
312         std::string players_path = savedir + "/players";
313         fs::CreateDir(players_path);
314
315         core::map<Player*, bool> saved_players;
316
317         std::vector<fs::DirListNode> player_files = fs::GetDirListing(players_path);
318         for(u32 i=0; i<player_files.size(); i++)
319         {
320                 if(player_files[i].dir)
321                         continue;
322                 
323                 // Full path to this file
324                 std::string path = players_path + "/" + player_files[i].name;
325
326                 //dstream<<"Checking player file "<<path<<std::endl;
327
328                 // Load player to see what is its name
329                 ServerRemotePlayer testplayer;
330                 {
331                         // Open file and deserialize
332                         std::ifstream is(path.c_str(), std::ios_base::binary);
333                         if(is.good() == false)
334                         {
335                                 dstream<<"Failed to read "<<path<<std::endl;
336                                 continue;
337                         }
338                         testplayer.deSerialize(is);
339                 }
340
341                 //dstream<<"Loaded test player with name "<<testplayer.getName()<<std::endl;
342                 
343                 // Search for the player
344                 std::string playername = testplayer.getName();
345                 Player *player = getPlayer(playername.c_str());
346                 if(player == NULL)
347                 {
348                         dstream<<"Didn't find matching player, ignoring file "<<path<<std::endl;
349                         continue;
350                 }
351
352                 //dstream<<"Found matching player, overwriting."<<std::endl;
353
354                 // OK, found. Save player there.
355                 {
356                         // Open file and serialize
357                         std::ofstream os(path.c_str(), std::ios_base::binary);
358                         if(os.good() == false)
359                         {
360                                 dstream<<"Failed to overwrite "<<path<<std::endl;
361                                 continue;
362                         }
363                         player->serialize(os);
364                         saved_players.insert(player, true);
365                 }
366         }
367
368         for(core::list<Player*>::Iterator i = m_players.begin();
369                         i != m_players.end(); i++)
370         {
371                 Player *player = *i;
372                 if(saved_players.find(player) != NULL)
373                 {
374                         /*dstream<<"Player "<<player->getName()
375                                         <<" was already saved."<<std::endl;*/
376                         continue;
377                 }
378                 std::string playername = player->getName();
379                 // Don't save unnamed player
380                 if(playername == "")
381                 {
382                         //dstream<<"Not saving unnamed player."<<std::endl;
383                         continue;
384                 }
385                 /*
386                         Find a sane filename
387                 */
388                 if(string_allowed(playername, PLAYERNAME_ALLOWED_CHARS) == false)
389                         playername = "player";
390                 std::string path = players_path + "/" + playername;
391                 bool found = false;
392                 for(u32 i=0; i<1000; i++)
393                 {
394                         if(fs::PathExists(path) == false)
395                         {
396                                 found = true;
397                                 break;
398                         }
399                         path = players_path + "/" + playername + itos(i);
400                 }
401                 if(found == false)
402                 {
403                         dstream<<"WARNING: Didn't find free file for player"<<std::endl;
404                         continue;
405                 }
406
407                 {
408                         /*dstream<<"Saving player "<<player->getName()<<" to "
409                                         <<path<<std::endl;*/
410                         // Open file and serialize
411                         std::ofstream os(path.c_str(), std::ios_base::binary);
412                         if(os.good() == false)
413                         {
414                                 dstream<<"WARNING: Failed to overwrite "<<path<<std::endl;
415                                 continue;
416                         }
417                         player->serialize(os);
418                         saved_players.insert(player, true);
419                 }
420         }
421
422         //dstream<<"Saved "<<saved_players.size()<<" players."<<std::endl;
423 }
424
425 void Environment::deSerializePlayers(const std::string &savedir)
426 {
427         std::string players_path = savedir + "/players";
428
429         core::map<Player*, bool> saved_players;
430
431         std::vector<fs::DirListNode> player_files = fs::GetDirListing(players_path);
432         for(u32 i=0; i<player_files.size(); i++)
433         {
434                 if(player_files[i].dir)
435                         continue;
436                 
437                 // Full path to this file
438                 std::string path = players_path + "/" + player_files[i].name;
439
440                 dstream<<"Checking player file "<<path<<std::endl;
441
442                 // Load player to see what is its name
443                 ServerRemotePlayer testplayer;
444                 {
445                         // Open file and deserialize
446                         std::ifstream is(path.c_str(), std::ios_base::binary);
447                         if(is.good() == false)
448                         {
449                                 dstream<<"Failed to read "<<path<<std::endl;
450                                 continue;
451                         }
452                         testplayer.deSerialize(is);
453                 }
454
455                 dstream<<"Loaded test player with name "<<testplayer.getName()<<std::endl;
456                 
457                 // Search for the player
458                 std::string playername = testplayer.getName();
459                 Player *player = getPlayer(playername.c_str());
460                 bool newplayer = false;
461                 if(player == NULL)
462                 {
463                         dstream<<"Is a new player"<<std::endl;
464                         player = new ServerRemotePlayer();
465                         newplayer = true;
466                 }
467
468                 // Load player
469                 {
470                         dstream<<"Reading player "<<testplayer.getName()<<" from "
471                                         <<path<<std::endl;
472                         // Open file and deserialize
473                         std::ifstream is(path.c_str(), std::ios_base::binary);
474                         if(is.good() == false)
475                         {
476                                 dstream<<"Failed to read "<<path<<std::endl;
477                                 continue;
478                         }
479                         player->deSerialize(is);
480                 }
481
482                 if(newplayer)
483                         addPlayer(player);
484         }
485 }
486
487 #ifndef SERVER
488 void Environment::updateMeshes(v3s16 blockpos)
489 {
490         m_map->updateMeshes(blockpos, m_daynight_ratio);
491 }
492
493 void Environment::expireMeshes(bool only_daynight_diffed)
494 {
495         m_map->expireMeshes(only_daynight_diffed);
496 }
497 #endif
498
499 void Environment::setDayNightRatio(u32 r)
500 {
501         m_daynight_ratio = r;
502 }
503
504 u32 Environment::getDayNightRatio()
505 {
506         return m_daynight_ratio;
507 }
508