fixed the object update interval thingy
[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 #include "porting.h"
23
24 Environment::Environment()
25 {
26         m_daynight_ratio = 0.5;
27 }
28
29 Environment::~Environment()
30 {
31         // Deallocate players
32         for(core::list<Player*>::Iterator i = m_players.begin();
33                         i != m_players.end(); i++)
34         {
35                 delete (*i);
36         }
37 }
38
39 void Environment::addPlayer(Player *player)
40 {
41         DSTACK(__FUNCTION_NAME);
42         /*
43                 Check that peer_ids are unique.
44                 Also check that names are unique.
45                 Exception: there can be multiple players with peer_id=0
46         */
47         // If peer id is non-zero, it has to be unique.
48         if(player->peer_id != 0)
49                 assert(getPlayer(player->peer_id) == NULL);
50         // Name has to be unique.
51         assert(getPlayer(player->getName()) == NULL);
52         // Add.
53         m_players.push_back(player);
54 }
55
56 void Environment::removePlayer(u16 peer_id)
57 {
58         DSTACK(__FUNCTION_NAME);
59 re_search:
60         for(core::list<Player*>::Iterator i = m_players.begin();
61                         i != m_players.end(); i++)
62         {
63                 Player *player = *i;
64                 if(player->peer_id != peer_id)
65                         continue;
66                 
67                 delete player;
68                 m_players.erase(i);
69                 // See if there is an another one
70                 // (shouldn't be, but just to be sure)
71                 goto re_search;
72         }
73 }
74
75 Player * Environment::getPlayer(u16 peer_id)
76 {
77         for(core::list<Player*>::Iterator i = m_players.begin();
78                         i != m_players.end(); i++)
79         {
80                 Player *player = *i;
81                 if(player->peer_id == peer_id)
82                         return player;
83         }
84         return NULL;
85 }
86
87 Player * Environment::getPlayer(const char *name)
88 {
89         for(core::list<Player*>::Iterator i = m_players.begin();
90                         i != m_players.end(); i++)
91         {
92                 Player *player = *i;
93                 if(strcmp(player->getName(), name) == 0)
94                         return player;
95         }
96         return NULL;
97 }
98
99 Player * Environment::getRandomConnectedPlayer()
100 {
101         core::list<Player*> connected_players = getPlayers(true);
102         u32 chosen_one = myrand() % connected_players.size();
103         u32 j = 0;
104         for(core::list<Player*>::Iterator
105                         i = connected_players.begin();
106                         i != connected_players.end(); i++)
107         {
108                 if(j == chosen_one)
109                 {
110                         Player *player = *i;
111                         return player;
112                 }
113                 j++;
114         }
115         return NULL;
116 }
117
118 Player * Environment::getNearestConnectedPlayer(v3f pos)
119 {
120         core::list<Player*> connected_players = getPlayers(true);
121         f32 nearest_d = 0;
122         Player *nearest_player = NULL;
123         for(core::list<Player*>::Iterator
124                         i = connected_players.begin();
125                         i != connected_players.end(); i++)
126         {
127                 Player *player = *i;
128                 f32 d = player->getPosition().getDistanceFrom(pos);
129                 if(d < nearest_d || nearest_player == NULL)
130                 {
131                         nearest_d = d;
132                         nearest_player = player;
133                 }
134         }
135         return nearest_player;
136 }
137
138 core::list<Player*> Environment::getPlayers()
139 {
140         return m_players;
141 }
142
143 core::list<Player*> Environment::getPlayers(bool ignore_disconnected)
144 {
145         core::list<Player*> newlist;
146         for(core::list<Player*>::Iterator
147                         i = m_players.begin();
148                         i != m_players.end(); i++)
149         {
150                 Player *player = *i;
151                 
152                 if(ignore_disconnected)
153                 {
154                         // Ignore disconnected players
155                         if(player->peer_id == 0)
156                                 continue;
157                 }
158
159                 newlist.push_back(player);
160         }
161         return newlist;
162 }
163
164 void Environment::printPlayers(std::ostream &o)
165 {
166         o<<"Players in environment:"<<std::endl;
167         for(core::list<Player*>::Iterator i = m_players.begin();
168                         i != m_players.end(); i++)
169         {
170                 Player *player = *i;
171                 o<<"Player peer_id="<<player->peer_id<<std::endl;
172         }
173 }
174
175 void Environment::setDayNightRatio(u32 r)
176 {
177         m_daynight_ratio = r;
178 }
179
180 u32 Environment::getDayNightRatio()
181 {
182         return m_daynight_ratio;
183 }
184
185 /*
186         ServerEnvironment
187 */
188
189 ServerEnvironment::ServerEnvironment(ServerMap *map, Server *server):
190         m_map(map),
191         m_server(server),
192         m_random_spawn_timer(3),
193         m_send_recommended_timer(0)
194 {
195 }
196
197 ServerEnvironment::~ServerEnvironment()
198 {
199         // Drop/delete map
200         m_map->drop();
201 }
202
203 void ServerEnvironment::serializePlayers(const std::string &savedir)
204 {
205         std::string players_path = savedir + "/players";
206         fs::CreateDir(players_path);
207
208         core::map<Player*, bool> saved_players;
209
210         std::vector<fs::DirListNode> player_files = fs::GetDirListing(players_path);
211         for(u32 i=0; i<player_files.size(); i++)
212         {
213                 if(player_files[i].dir)
214                         continue;
215                 
216                 // Full path to this file
217                 std::string path = players_path + "/" + player_files[i].name;
218
219                 //dstream<<"Checking player file "<<path<<std::endl;
220
221                 // Load player to see what is its name
222                 ServerRemotePlayer testplayer;
223                 {
224                         // Open file and deserialize
225                         std::ifstream is(path.c_str(), std::ios_base::binary);
226                         if(is.good() == false)
227                         {
228                                 dstream<<"Failed to read "<<path<<std::endl;
229                                 continue;
230                         }
231                         testplayer.deSerialize(is);
232                 }
233
234                 //dstream<<"Loaded test player with name "<<testplayer.getName()<<std::endl;
235                 
236                 // Search for the player
237                 std::string playername = testplayer.getName();
238                 Player *player = getPlayer(playername.c_str());
239                 if(player == NULL)
240                 {
241                         dstream<<"Didn't find matching player, ignoring file "<<path<<std::endl;
242                         continue;
243                 }
244
245                 //dstream<<"Found matching player, overwriting."<<std::endl;
246
247                 // OK, found. Save player there.
248                 {
249                         // Open file and serialize
250                         std::ofstream os(path.c_str(), std::ios_base::binary);
251                         if(os.good() == false)
252                         {
253                                 dstream<<"Failed to overwrite "<<path<<std::endl;
254                                 continue;
255                         }
256                         player->serialize(os);
257                         saved_players.insert(player, true);
258                 }
259         }
260
261         for(core::list<Player*>::Iterator i = m_players.begin();
262                         i != m_players.end(); i++)
263         {
264                 Player *player = *i;
265                 if(saved_players.find(player) != NULL)
266                 {
267                         /*dstream<<"Player "<<player->getName()
268                                         <<" was already saved."<<std::endl;*/
269                         continue;
270                 }
271                 std::string playername = player->getName();
272                 // Don't save unnamed player
273                 if(playername == "")
274                 {
275                         //dstream<<"Not saving unnamed player."<<std::endl;
276                         continue;
277                 }
278                 /*
279                         Find a sane filename
280                 */
281                 if(string_allowed(playername, PLAYERNAME_ALLOWED_CHARS) == false)
282                         playername = "player";
283                 std::string path = players_path + "/" + playername;
284                 bool found = false;
285                 for(u32 i=0; i<1000; i++)
286                 {
287                         if(fs::PathExists(path) == false)
288                         {
289                                 found = true;
290                                 break;
291                         }
292                         path = players_path + "/" + playername + itos(i);
293                 }
294                 if(found == false)
295                 {
296                         dstream<<"WARNING: Didn't find free file for player"<<std::endl;
297                         continue;
298                 }
299
300                 {
301                         /*dstream<<"Saving player "<<player->getName()<<" to "
302                                         <<path<<std::endl;*/
303                         // Open file and serialize
304                         std::ofstream os(path.c_str(), std::ios_base::binary);
305                         if(os.good() == false)
306                         {
307                                 dstream<<"WARNING: Failed to overwrite "<<path<<std::endl;
308                                 continue;
309                         }
310                         player->serialize(os);
311                         saved_players.insert(player, true);
312                 }
313         }
314
315         //dstream<<"Saved "<<saved_players.size()<<" players."<<std::endl;
316 }
317
318 void ServerEnvironment::deSerializePlayers(const std::string &savedir)
319 {
320         std::string players_path = savedir + "/players";
321
322         core::map<Player*, bool> saved_players;
323
324         std::vector<fs::DirListNode> player_files = fs::GetDirListing(players_path);
325         for(u32 i=0; i<player_files.size(); i++)
326         {
327                 if(player_files[i].dir)
328                         continue;
329                 
330                 // Full path to this file
331                 std::string path = players_path + "/" + player_files[i].name;
332
333                 dstream<<"Checking player file "<<path<<std::endl;
334
335                 // Load player to see what is its name
336                 ServerRemotePlayer testplayer;
337                 {
338                         // Open file and deserialize
339                         std::ifstream is(path.c_str(), std::ios_base::binary);
340                         if(is.good() == false)
341                         {
342                                 dstream<<"Failed to read "<<path<<std::endl;
343                                 continue;
344                         }
345                         testplayer.deSerialize(is);
346                 }
347
348                 dstream<<"Loaded test player with name "<<testplayer.getName()<<std::endl;
349                 
350                 // Search for the player
351                 std::string playername = testplayer.getName();
352                 Player *player = getPlayer(playername.c_str());
353                 bool newplayer = false;
354                 if(player == NULL)
355                 {
356                         dstream<<"Is a new player"<<std::endl;
357                         player = new ServerRemotePlayer();
358                         newplayer = true;
359                 }
360
361                 // Load player
362                 {
363                         dstream<<"Reading player "<<testplayer.getName()<<" from "
364                                         <<path<<std::endl;
365                         // Open file and deserialize
366                         std::ifstream is(path.c_str(), std::ios_base::binary);
367                         if(is.good() == false)
368                         {
369                                 dstream<<"Failed to read "<<path<<std::endl;
370                                 continue;
371                         }
372                         player->deSerialize(is);
373                 }
374
375                 if(newplayer)
376                         addPlayer(player);
377         }
378 }
379
380 void ServerEnvironment::step(float dtime)
381 {
382         DSTACK(__FUNCTION_NAME);
383         
384         //TimeTaker timer("ServerEnv step");
385
386         // Get some settings
387         //bool free_move = g_settings.getBool("free_move");
388         bool footprints = g_settings.getBool("footprints");
389
390         {
391                 //TimeTaker timer("Server m_map->timerUpdate()", g_device);
392                 m_map->timerUpdate(dtime);
393         }
394
395         /*
396                 Handle players
397         */
398         for(core::list<Player*>::Iterator i = m_players.begin();
399                         i != m_players.end(); i++)
400         {
401                 Player *player = *i;
402                 
403                 // Ignore disconnected players
404                 if(player->peer_id == 0)
405                         continue;
406
407                 v3f playerpos = player->getPosition();
408                 
409                 // Move
410                 player->move(dtime, *m_map, 100*BS);
411                 
412                 /*
413                         Add footsteps to grass
414                 */
415                 if(footprints)
416                 {
417                         // Get node that is at BS/4 under player
418                         v3s16 bottompos = floatToInt(playerpos + v3f(0,-BS/4,0), BS);
419                         try{
420                                 MapNode n = m_map->getNode(bottompos);
421                                 if(n.d == CONTENT_GRASS)
422                                 {
423                                         n.d = CONTENT_GRASS_FOOTSTEPS;
424                                         m_map->setNode(bottompos, n);
425                                 }
426                         }
427                         catch(InvalidPositionException &e)
428                         {
429                         }
430                 }
431         }
432         
433         /*
434                 Step active objects
435         */
436
437         bool send_recommended = false;
438         m_send_recommended_timer += dtime;
439         if(m_send_recommended_timer > 0.15)
440         {
441                 m_send_recommended_timer = 0;
442                 send_recommended = true;
443         }
444
445         for(core::map<u16, ServerActiveObject*>::Iterator
446                         i = m_active_objects.getIterator();
447                         i.atEnd()==false; i++)
448         {
449                 ServerActiveObject* obj = i.getNode()->getValue();
450                 // Step object, putting messages directly to the queue
451                 obj->step(dtime, m_active_object_messages, send_recommended);
452         }
453
454         if(m_object_management_interval.step(dtime, 0.5))
455         {
456                 //TimeTaker timer("ServerEnv object management");
457
458                 /*
459                         Remove objects that satisfy (m_removed && m_known_by_count==0)
460                 */
461                 {
462                         core::list<u16> objects_to_remove;
463                         for(core::map<u16, ServerActiveObject*>::Iterator
464                                         i = m_active_objects.getIterator();
465                                         i.atEnd()==false; i++)
466                         {
467                                 u16 id = i.getNode()->getKey();
468                                 ServerActiveObject* obj = i.getNode()->getValue();
469                                 // This shouldn't happen but check it
470                                 if(obj == NULL)
471                                 {
472                                         dstream<<"WARNING: NULL object found in ServerEnvironment"
473                                                         <<" while finding removed objects. id="<<id<<std::endl;
474                                         // Id to be removed from m_active_objects
475                                         objects_to_remove.push_back(id);
476                                         continue;
477                                 }
478                                 // If not m_removed, don't remove.
479                                 if(obj->m_removed == false)
480                                         continue;
481                                 // Delete static data from block
482                                 if(obj->m_static_exists)
483                                 {
484                                         MapBlock *block = m_map->getBlockNoCreateNoEx(obj->m_static_block);
485                                         if(block)
486                                         {
487                                                 block->m_static_objects.remove(id);
488                                                 block->setChangedFlag();
489                                         }
490                                 }
491                                 // If m_known_by_count > 0, don't actually remove.
492                                 if(obj->m_known_by_count > 0)
493                                         continue;
494                                 // Delete
495                                 delete obj;
496                                 // Id to be removed from m_active_objects
497                                 objects_to_remove.push_back(id);
498                         }
499                         // Remove references from m_active_objects
500                         for(core::list<u16>::Iterator i = objects_to_remove.begin();
501                                         i != objects_to_remove.end(); i++)
502                         {
503                                 m_active_objects.remove(*i);
504                         }
505                 }
506                 
507
508                 const s16 to_active_max_blocks = 3;
509                 const f32 to_static_max_f = (to_active_max_blocks+1)*MAP_BLOCKSIZE*BS;
510
511                 /*
512                         Convert stored objects from blocks near the players to active.
513                 */
514                 for(core::list<Player*>::Iterator i = m_players.begin();
515                                 i != m_players.end(); i++)
516                 {
517                         Player *player = *i;
518                         
519                         // Ignore disconnected players
520                         if(player->peer_id == 0)
521                                 continue;
522
523                         v3f playerpos = player->getPosition();
524                         
525                         v3s16 blockpos0 = getNodeBlockPos(floatToInt(playerpos, BS));
526                         v3s16 bpmin = blockpos0 - v3s16(1,1,1)*to_active_max_blocks;
527                         v3s16 bpmax = blockpos0 + v3s16(1,1,1)*to_active_max_blocks;
528                         // Loop through all nearby blocks
529                         for(s16 x=bpmin.X; x<=bpmax.X; x++)
530                         for(s16 y=bpmin.Y; y<=bpmax.Y; y++)
531                         for(s16 z=bpmin.Z; z<=bpmax.Z; z++)
532                         {
533                                 v3s16 blockpos(x,y,z);
534                                 MapBlock *block = m_map->getBlockNoCreateNoEx(blockpos);
535                                 if(block==NULL)
536                                         continue;
537                                 // Ignore if no stored objects (to not set changed flag)
538                                 if(block->m_static_objects.m_stored.size() == 0)
539                                         continue;
540                                 // This will contain the leftovers of the stored list
541                                 core::list<StaticObject> new_stored;
542                                 // Loop through stored static objects
543                                 for(core::list<StaticObject>::Iterator
544                                                 i = block->m_static_objects.m_stored.begin();
545                                                 i != block->m_static_objects.m_stored.end(); i++)
546                                 {
547                                         /*dstream<<"INFO: Server: Creating an active object from "
548                                                         <<"static data"<<std::endl;*/
549                                         StaticObject &s_obj = *i;
550                                         // Create an active object from the data
551                                         ServerActiveObject *obj = ServerActiveObject::create
552                                                         (s_obj.type, this, 0, s_obj.pos, s_obj.data);
553                                         if(obj==NULL)
554                                         {
555                                                 // This is necessary to preserve stuff during bugs
556                                                 // and errors
557                                                 new_stored.push_back(s_obj);
558                                                 continue;
559                                         }
560                                         // This will also add the object to the active static list
561                                         addActiveObject(obj);
562                                         //u16 id = addActiveObject(obj);
563                                 }
564                                 // Clear stored list
565                                 block->m_static_objects.m_stored.clear();
566                                 // Add leftover stuff to stored list
567                                 for(core::list<StaticObject>::Iterator
568                                                 i = new_stored.begin();
569                                                 i != new_stored.end(); i++)
570                                 {
571                                         StaticObject &s_obj = *i;
572                                         block->m_static_objects.m_stored.push_back(s_obj);
573                                 }
574                                 block->setChangedFlag();
575                         }
576                 }
577
578                 /*
579                         Convert objects that are far away from all the players to static.
580                 */
581                 {
582                         core::list<u16> objects_to_remove;
583                         for(core::map<u16, ServerActiveObject*>::Iterator
584                                         i = m_active_objects.getIterator();
585                                         i.atEnd()==false; i++)
586                         {
587                                 ServerActiveObject* obj = i.getNode()->getValue();
588                                 u16 id = i.getNode()->getKey();
589                                 v3f objectpos = obj->getBasePosition();
590
591                                 // This shouldn't happen but check it
592                                 if(obj == NULL)
593                                 {
594                                         dstream<<"WARNING: NULL object found in ServerEnvironment"
595                                                         <<std::endl;
596                                         continue;
597                                 }
598                                 // If known by some client, don't convert to static.
599                                 if(obj->m_known_by_count > 0)
600                                         continue;
601
602                                 // If close to some player, don't convert to static.
603                                 bool close_to_player = false;
604                                 for(core::list<Player*>::Iterator i = m_players.begin();
605                                                 i != m_players.end(); i++)
606                                 {
607                                         Player *player = *i;
608                                         
609                                         // Ignore disconnected players
610                                         if(player->peer_id == 0)
611                                                 continue;
612
613                                         v3f playerpos = player->getPosition();
614                                         f32 d = playerpos.getDistanceFrom(objectpos);
615                                         if(d < to_static_max_f)
616                                         {
617                                                 close_to_player = true;
618                                                 break;
619                                         }
620                                 }
621
622                                 if(close_to_player)
623                                         continue;
624
625                                 /*
626                                         Update the static data and remove the active object.
627                                 */
628
629                                 // Delete old static object
630                                 MapBlock *oldblock = NULL;
631                                 if(obj->m_static_exists)
632                                 {
633                                         MapBlock *block = m_map->getBlockNoCreateNoEx
634                                                         (obj->m_static_block);
635                                         if(block)
636                                         {
637                                                 block->m_static_objects.remove(id);
638                                                 oldblock = block;
639                                         }
640                                 }
641                                 // Add new static object
642                                 std::string staticdata = obj->getStaticData();
643                                 StaticObject s_obj(obj->getType(), objectpos, staticdata);
644                                 // Add to the block where the object is located in
645                                 v3s16 blockpos = getNodeBlockPos(floatToInt(objectpos, BS));
646                                 MapBlock *block = m_map->getBlockNoCreateNoEx(blockpos);
647                                 if(block)
648                                 {
649                                         block->m_static_objects.insert(0, s_obj);
650                                         block->setChangedFlag();
651                                         obj->m_static_exists = true;
652                                         obj->m_static_block = block->getPos();
653                                 }
654                                 // If not possible, add back to previous block
655                                 else if(oldblock)
656                                 {
657                                         oldblock->m_static_objects.insert(0, s_obj);
658                                         oldblock->setChangedFlag();
659                                         obj->m_static_exists = true;
660                                         obj->m_static_block = oldblock->getPos();
661                                 }
662                                 else{
663                                         dstream<<"WARNING: Server: Could not find a block for "
664                                                         <<"storing static object"<<std::endl;
665                                         obj->m_static_exists = false;
666                                         continue;
667                                 }
668                                 /*dstream<<"INFO: Server: Stored static data. Deleting object."
669                                                 <<std::endl;*/
670                                 // Delete active object
671                                 delete obj;
672                                 // Id to be removed from m_active_objects
673                                 objects_to_remove.push_back(id);
674                         }
675                         // Remove references from m_active_objects
676                         for(core::list<u16>::Iterator i = objects_to_remove.begin();
677                                         i != objects_to_remove.end(); i++)
678                         {
679                                 m_active_objects.remove(*i);
680                         }
681                 }
682         }
683
684         if(g_settings.getBool("enable_experimental"))
685         {
686
687         /*
688                 TEST CODE
689         */
690 #if 1
691         m_random_spawn_timer -= dtime;
692         if(m_random_spawn_timer < 0)
693         {
694                 //m_random_spawn_timer += myrand_range(2.0, 20.0);
695                 //m_random_spawn_timer += 2.0;
696                 m_random_spawn_timer += 200.0;
697
698                 /*
699                         Find some position
700                 */
701
702                 /*v2s16 p2d(myrand_range(-5,5), myrand_range(-5,5));
703                 s16 y = 1 + getServerMap().findGroundLevel(p2d);
704                 v3f pos(p2d.X*BS,y*BS,p2d.Y*BS);*/
705                 
706                 Player *player = getRandomConnectedPlayer();
707                 v3f pos(0,0,0);
708                 if(player)
709                         pos = player->getPosition();
710                 pos += v3f(
711                         myrand_range(-3,3)*BS,
712                         0,
713                         myrand_range(-3,3)*BS
714                 );
715
716                 /*
717                         Create a ServerActiveObject
718                 */
719
720                 //TestSAO *obj = new TestSAO(this, 0, pos);
721                 //ServerActiveObject *obj = new ItemSAO(this, 0, pos, "CraftItem Stick 1");
722                 ServerActiveObject *obj = new RatSAO(this, 0, pos);
723                 addActiveObject(obj);
724         }
725 #endif
726
727         } // enable_experimental
728 }
729
730 ServerActiveObject* ServerEnvironment::getActiveObject(u16 id)
731 {
732         core::map<u16, ServerActiveObject*>::Node *n;
733         n = m_active_objects.find(id);
734         if(n == NULL)
735                 return NULL;
736         return n->getValue();
737 }
738
739 bool isFreeServerActiveObjectId(u16 id,
740                 core::map<u16, ServerActiveObject*> &objects)
741 {
742         if(id == 0)
743                 return false;
744         
745         for(core::map<u16, ServerActiveObject*>::Iterator
746                         i = objects.getIterator();
747                         i.atEnd()==false; i++)
748         {
749                 if(i.getNode()->getKey() == id)
750                         return false;
751         }
752         return true;
753 }
754
755 u16 getFreeServerActiveObjectId(
756                 core::map<u16, ServerActiveObject*> &objects)
757 {
758         u16 new_id = 1;
759         for(;;)
760         {
761                 if(isFreeServerActiveObjectId(new_id, objects))
762                         return new_id;
763                 
764                 if(new_id == 65535)
765                         return 0;
766
767                 new_id++;
768         }
769 }
770
771 u16 ServerEnvironment::addActiveObject(ServerActiveObject *object)
772 {
773         assert(object);
774         if(object->getId() == 0)
775         {
776                 u16 new_id = getFreeServerActiveObjectId(m_active_objects);
777                 if(new_id == 0)
778                 {
779                         dstream<<"WARNING: ServerEnvironment::addActiveObject(): "
780                                         <<"no free ids available"<<std::endl;
781                         delete object;
782                         return 0;
783                 }
784                 object->setId(new_id);
785         }
786         if(isFreeServerActiveObjectId(object->getId(), m_active_objects) == false)
787         {
788                 dstream<<"WARNING: ServerEnvironment::addActiveObject(): "
789                                 <<"id is not free ("<<object->getId()<<")"<<std::endl;
790                 delete object;
791                 return 0;
792         }
793         /*dstream<<"INGO: ServerEnvironment::addActiveObject(): "
794                         <<"added (id="<<object->getId()<<")"<<std::endl;*/
795                         
796         m_active_objects.insert(object->getId(), object);
797
798         // Add static object to active static list of the block
799         v3f objectpos = object->getBasePosition();
800         std::string staticdata = object->getStaticData();
801         StaticObject s_obj(object->getType(), objectpos, staticdata);
802         // Add to the block where the object is located in
803         v3s16 blockpos = getNodeBlockPos(floatToInt(objectpos, BS));
804         MapBlock *block = m_map->getBlockNoCreateNoEx(blockpos);
805         if(block)
806         {
807                 block->m_static_objects.m_active.insert(object->getId(), s_obj);
808                 object->m_static_exists = true;
809                 object->m_static_block = blockpos;
810         }
811         else{
812                 dstream<<"WARNING: Server: Could not find a block for "
813                                 <<"storing newly added static active object"<<std::endl;
814         }
815
816         return object->getId();
817 }
818
819 /*
820         Finds out what new objects have been added to
821         inside a radius around a position
822 */
823 void ServerEnvironment::getAddedActiveObjects(v3s16 pos, s16 radius,
824                 core::map<u16, bool> &current_objects,
825                 core::map<u16, bool> &added_objects)
826 {
827         v3f pos_f = intToFloat(pos, BS);
828         f32 radius_f = radius * BS;
829         /*
830                 Go through the object list,
831                 - discard m_removed objects,
832                 - discard objects that are too far away,
833                 - discard objects that are found in current_objects.
834                 - add remaining objects to added_objects
835         */
836         for(core::map<u16, ServerActiveObject*>::Iterator
837                         i = m_active_objects.getIterator();
838                         i.atEnd()==false; i++)
839         {
840                 u16 id = i.getNode()->getKey();
841                 // Get object
842                 ServerActiveObject *object = i.getNode()->getValue();
843                 if(object == NULL)
844                         continue;
845                 // Discard if removed
846                 if(object->m_removed)
847                         continue;
848                 // Discard if too far
849                 f32 distance_f = object->getBasePosition().getDistanceFrom(pos_f);
850                 if(distance_f > radius_f)
851                         continue;
852                 // Discard if already on current_objects
853                 core::map<u16, bool>::Node *n;
854                 n = current_objects.find(id);
855                 if(n != NULL)
856                         continue;
857                 // Add to added_objects
858                 added_objects.insert(id, false);
859         }
860 }
861
862 /*
863         Finds out what objects have been removed from
864         inside a radius around a position
865 */
866 void ServerEnvironment::getRemovedActiveObjects(v3s16 pos, s16 radius,
867                 core::map<u16, bool> &current_objects,
868                 core::map<u16, bool> &removed_objects)
869 {
870         v3f pos_f = intToFloat(pos, BS);
871         f32 radius_f = radius * BS;
872         /*
873                 Go through current_objects; object is removed if:
874                 - object is not found in m_active_objects (this is actually an
875                   error condition; objects should be set m_removed=true and removed
876                   only after all clients have been informed about removal), or
877                 - object has m_removed=true, or
878                 - object is too far away
879         */
880         for(core::map<u16, bool>::Iterator
881                         i = current_objects.getIterator();
882                         i.atEnd()==false; i++)
883         {
884                 u16 id = i.getNode()->getKey();
885                 ServerActiveObject *object = getActiveObject(id);
886                 if(object == NULL)
887                 {
888                         dstream<<"WARNING: ServerEnvironment::getRemovedActiveObjects():"
889                                         <<" object in current_objects is NULL"<<std::endl;
890                 }
891                 else if(object->m_removed == false)
892                 {
893                         f32 distance_f = object->getBasePosition().getDistanceFrom(pos_f);
894                         /*dstream<<"removed == false"
895                                         <<"distance_f = "<<distance_f
896                                         <<", radius_f = "<<radius_f<<std::endl;*/
897                         if(distance_f < radius_f)
898                         {
899                                 // Not removed
900                                 continue;
901                         }
902                 }
903                 removed_objects.insert(id, false);
904         }
905 }
906
907 ActiveObjectMessage ServerEnvironment::getActiveObjectMessage()
908 {
909         if(m_active_object_messages.size() == 0)
910                 return ActiveObjectMessage(0);
911         
912         return m_active_object_messages.pop_front();
913 }
914
915 #ifndef SERVER
916
917 /*
918         ClientEnvironment
919 */
920
921 ClientEnvironment::ClientEnvironment(ClientMap *map, scene::ISceneManager *smgr):
922         m_map(map),
923         m_smgr(smgr)
924 {
925         assert(m_map);
926         assert(m_smgr);
927 }
928
929 ClientEnvironment::~ClientEnvironment()
930 {
931         // delete active objects
932         for(core::map<u16, ClientActiveObject*>::Iterator
933                         i = m_active_objects.getIterator();
934                         i.atEnd()==false; i++)
935         {
936                 delete i.getNode()->getValue();
937         }
938
939         // Drop/delete map
940         m_map->drop();
941 }
942
943 void ClientEnvironment::addPlayer(Player *player)
944 {
945         DSTACK(__FUNCTION_NAME);
946         /*
947                 It is a failure if player is local and there already is a local
948                 player
949         */
950         assert(!(player->isLocal() == true && getLocalPlayer() != NULL));
951
952         Environment::addPlayer(player);
953 }
954
955 LocalPlayer * ClientEnvironment::getLocalPlayer()
956 {
957         for(core::list<Player*>::Iterator i = m_players.begin();
958                         i != m_players.end(); i++)
959         {
960                 Player *player = *i;
961                 if(player->isLocal())
962                         return (LocalPlayer*)player;
963         }
964         return NULL;
965 }
966
967 void ClientEnvironment::step(float dtime)
968 {
969         DSTACK(__FUNCTION_NAME);
970
971         // Get some settings
972         bool free_move = g_settings.getBool("free_move");
973         bool footprints = g_settings.getBool("footprints");
974
975         {
976                 //TimeTaker timer("Client m_map->timerUpdate()", g_device);
977                 m_map->timerUpdate(dtime);
978         }
979
980         /*
981                 Get the speed the player is going
982         */
983         f32 player_speed = 0.001; // just some small value
984         LocalPlayer *lplayer = getLocalPlayer();
985         if(lplayer)
986                 player_speed = lplayer->getSpeed().getLength();
987         
988         /*
989                 Maximum position increment
990         */
991         //f32 position_max_increment = 0.05*BS;
992         f32 position_max_increment = 0.1*BS;
993
994         // Maximum time increment (for collision detection etc)
995         // time = distance / speed
996         f32 dtime_max_increment = position_max_increment / player_speed;
997         
998         // Maximum time increment is 10ms or lower
999         if(dtime_max_increment > 0.01)
1000                 dtime_max_increment = 0.01;
1001         
1002         // Don't allow overly huge dtime
1003         if(dtime > 0.5)
1004                 dtime = 0.5;
1005         
1006         f32 dtime_downcount = dtime;
1007
1008         /*
1009                 Stuff that has a maximum time increment
1010         */
1011
1012         u32 loopcount = 0;
1013         do
1014         {
1015                 loopcount++;
1016
1017                 f32 dtime_part;
1018                 if(dtime_downcount > dtime_max_increment)
1019                 {
1020                         dtime_part = dtime_max_increment;
1021                         dtime_downcount -= dtime_part;
1022                 }
1023                 else
1024                 {
1025                         dtime_part = dtime_downcount;
1026                         /*
1027                                 Setting this to 0 (no -=dtime_part) disables an infinite loop
1028                                 when dtime_part is so small that dtime_downcount -= dtime_part
1029                                 does nothing
1030                         */
1031                         dtime_downcount = 0;
1032                 }
1033                 
1034                 /*
1035                         Handle local player
1036                 */
1037                 
1038                 {
1039                         Player *player = getLocalPlayer();
1040
1041                         v3f playerpos = player->getPosition();
1042                         
1043                         // Apply physics
1044                         if(free_move == false)
1045                         {
1046                                 // Gravity
1047                                 v3f speed = player->getSpeed();
1048                                 if(player->swimming_up == false)
1049                                         speed.Y -= 9.81 * BS * dtime_part * 2;
1050
1051                                 // Water resistance
1052                                 if(player->in_water_stable || player->in_water)
1053                                 {
1054                                         f32 max_down = 2.0*BS;
1055                                         if(speed.Y < -max_down) speed.Y = -max_down;
1056
1057                                         f32 max = 2.5*BS;
1058                                         if(speed.getLength() > max)
1059                                         {
1060                                                 speed = speed / speed.getLength() * max;
1061                                         }
1062                                 }
1063
1064                                 player->setSpeed(speed);
1065                         }
1066
1067                         /*
1068                                 Move the player.
1069                                 This also does collision detection.
1070                         */
1071                         player->move(dtime_part, *m_map, position_max_increment);
1072                 }
1073         }
1074         while(dtime_downcount > 0.001);
1075                 
1076         //std::cout<<"Looped "<<loopcount<<" times."<<std::endl;
1077         
1078         /*
1079                 Stuff that can be done in an arbitarily large dtime
1080         */
1081         for(core::list<Player*>::Iterator i = m_players.begin();
1082                         i != m_players.end(); i++)
1083         {
1084                 Player *player = *i;
1085                 v3f playerpos = player->getPosition();
1086                 
1087                 /*
1088                         Handle non-local players
1089                 */
1090                 if(player->isLocal() == false)
1091                 {
1092                         // Move
1093                         player->move(dtime, *m_map, 100*BS);
1094
1095                         // Update lighting on remote players on client
1096                         u8 light = LIGHT_MAX;
1097                         try{
1098                                 // Get node at head
1099                                 v3s16 p = floatToInt(playerpos + v3f(0,BS+BS/2,0), BS);
1100                                 MapNode n = m_map->getNode(p);
1101                                 light = n.getLightBlend(m_daynight_ratio);
1102                         }
1103                         catch(InvalidPositionException &e) {}
1104                         player->updateLight(light);
1105                 }
1106                 
1107                 /*
1108                         Add footsteps to grass
1109                 */
1110                 if(footprints)
1111                 {
1112                         // Get node that is at BS/4 under player
1113                         v3s16 bottompos = floatToInt(playerpos + v3f(0,-BS/4,0), BS);
1114                         try{
1115                                 MapNode n = m_map->getNode(bottompos);
1116                                 if(n.d == CONTENT_GRASS)
1117                                 {
1118                                         n.d = CONTENT_GRASS_FOOTSTEPS;
1119                                         m_map->setNode(bottompos, n);
1120                                         // Update mesh on client
1121                                         if(m_map->mapType() == MAPTYPE_CLIENT)
1122                                         {
1123                                                 v3s16 p_blocks = getNodeBlockPos(bottompos);
1124                                                 MapBlock *b = m_map->getBlockNoCreate(p_blocks);
1125                                                 //b->updateMesh(m_daynight_ratio);
1126                                                 b->setMeshExpired(true);
1127                                         }
1128                                 }
1129                         }
1130                         catch(InvalidPositionException &e)
1131                         {
1132                         }
1133                 }
1134         }
1135         
1136         /*
1137                 Step active objects and update lighting of them
1138         */
1139         
1140         for(core::map<u16, ClientActiveObject*>::Iterator
1141                         i = m_active_objects.getIterator();
1142                         i.atEnd()==false; i++)
1143         {
1144                 ClientActiveObject* obj = i.getNode()->getValue();
1145                 // Step object
1146                 obj->step(dtime, this);
1147                 // Update lighting
1148                 //u8 light = LIGHT_MAX;
1149                 u8 light = 0;
1150                 try{
1151                         // Get node at head
1152                         v3s16 p = obj->getLightPosition();
1153                         MapNode n = m_map->getNode(p);
1154                         light = n.getLightBlend(m_daynight_ratio);
1155                 }
1156                 catch(InvalidPositionException &e) {}
1157                 obj->updateLight(light);
1158         }
1159 }
1160
1161 void ClientEnvironment::updateMeshes(v3s16 blockpos)
1162 {
1163         m_map->updateMeshes(blockpos, m_daynight_ratio);
1164 }
1165
1166 void ClientEnvironment::expireMeshes(bool only_daynight_diffed)
1167 {
1168         m_map->expireMeshes(only_daynight_diffed);
1169 }
1170
1171 ClientActiveObject* ClientEnvironment::getActiveObject(u16 id)
1172 {
1173         core::map<u16, ClientActiveObject*>::Node *n;
1174         n = m_active_objects.find(id);
1175         if(n == NULL)
1176                 return NULL;
1177         return n->getValue();
1178 }
1179
1180 bool isFreeClientActiveObjectId(u16 id,
1181                 core::map<u16, ClientActiveObject*> &objects)
1182 {
1183         if(id == 0)
1184                 return false;
1185         
1186         for(core::map<u16, ClientActiveObject*>::Iterator
1187                         i = objects.getIterator();
1188                         i.atEnd()==false; i++)
1189         {
1190                 if(i.getNode()->getKey() == id)
1191                         return false;
1192         }
1193         return true;
1194 }
1195
1196 u16 getFreeClientActiveObjectId(
1197                 core::map<u16, ClientActiveObject*> &objects)
1198 {
1199         u16 new_id = 1;
1200         for(;;)
1201         {
1202                 if(isFreeClientActiveObjectId(new_id, objects))
1203                         return new_id;
1204                 
1205                 if(new_id == 65535)
1206                         return 0;
1207
1208                 new_id++;
1209         }
1210 }
1211
1212 u16 ClientEnvironment::addActiveObject(ClientActiveObject *object)
1213 {
1214         assert(object);
1215         if(object->getId() == 0)
1216         {
1217                 u16 new_id = getFreeClientActiveObjectId(m_active_objects);
1218                 if(new_id == 0)
1219                 {
1220                         dstream<<"WARNING: ClientEnvironment::addActiveObject(): "
1221                                         <<"no free ids available"<<std::endl;
1222                         delete object;
1223                         return 0;
1224                 }
1225                 object->setId(new_id);
1226         }
1227         if(isFreeClientActiveObjectId(object->getId(), m_active_objects) == false)
1228         {
1229                 dstream<<"WARNING: ClientEnvironment::addActiveObject(): "
1230                                 <<"id is not free ("<<object->getId()<<")"<<std::endl;
1231                 delete object;
1232                 return 0;
1233         }
1234         dstream<<"INGO: ClientEnvironment::addActiveObject(): "
1235                         <<"added (id="<<object->getId()<<")"<<std::endl;
1236         m_active_objects.insert(object->getId(), object);
1237         object->addToScene(m_smgr);
1238         return object->getId();
1239 }
1240
1241 void ClientEnvironment::addActiveObject(u16 id, u8 type,
1242                 const std::string &init_data)
1243 {
1244         ClientActiveObject* obj = ClientActiveObject::create(type);
1245         if(obj == NULL)
1246         {
1247                 dstream<<"WARNING: ClientEnvironment::addActiveObject(): "
1248                                 <<"id="<<id<<" type="<<type<<": Couldn't create object"
1249                                 <<std::endl;
1250                 return;
1251         }
1252         
1253         obj->setId(id);
1254
1255         addActiveObject(obj);
1256
1257         obj->initialize(init_data);
1258 }
1259
1260 void ClientEnvironment::removeActiveObject(u16 id)
1261 {
1262         dstream<<"ClientEnvironment::removeActiveObject(): "
1263                         <<"id="<<id<<std::endl;
1264         ClientActiveObject* obj = getActiveObject(id);
1265         if(obj == NULL)
1266         {
1267                 dstream<<"WARNING: ClientEnvironment::removeActiveObject(): "
1268                                 <<"id="<<id<<" not found"<<std::endl;
1269                 return;
1270         }
1271         obj->removeFromScene();
1272         delete obj;
1273         m_active_objects.remove(id);
1274 }
1275
1276 void ClientEnvironment::processActiveObjectMessage(u16 id,
1277                 const std::string &data)
1278 {
1279         ClientActiveObject* obj = getActiveObject(id);
1280         if(obj == NULL)
1281         {
1282                 dstream<<"WARNING: ClientEnvironment::processActiveObjectMessage():"
1283                                 <<" got message for id="<<id<<", which doesn't exist."
1284                                 <<std::endl;
1285                 return;
1286         }
1287         obj->processMessage(data);
1288 }
1289
1290 void ClientEnvironment::getActiveObjects(v3f origin, f32 max_d,
1291                 core::array<DistanceSortedActiveObject> &dest)
1292 {
1293         for(core::map<u16, ClientActiveObject*>::Iterator
1294                         i = m_active_objects.getIterator();
1295                         i.atEnd()==false; i++)
1296         {
1297                 ClientActiveObject* obj = i.getNode()->getValue();
1298
1299                 f32 d = (obj->getPosition() - origin).getLength();
1300
1301                 if(d > max_d)
1302                         continue;
1303
1304                 DistanceSortedActiveObject dso(obj, d);
1305
1306                 dest.push_back(dso);
1307         }
1308 }
1309
1310
1311 #endif // #ifndef SERVER
1312
1313