mapgen work-in-progress
[oweals/minetest.git] / src / client.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 "client.h"
21 #include "utility.h"
22 #include <iostream>
23 #include "clientserver.h"
24 #include "jmutexautolock.h"
25 #include "main.h"
26 #include <sstream>
27 #include "porting.h"
28
29 void * ClientUpdateThread::Thread()
30 {
31         ThreadStarted();
32
33         DSTACK(__FUNCTION_NAME);
34         
35         BEGIN_DEBUG_EXCEPTION_HANDLER
36         
37         while(getRun())
38         {
39                 m_client->asyncStep();
40
41                 //m_client->updateSomeExpiredMeshes();
42
43                 bool was = m_client->AsyncProcessData();
44
45                 if(was == false)
46                         sleep_ms(10);
47         }
48
49         END_DEBUG_EXCEPTION_HANDLER
50
51         return NULL;
52 }
53
54 Client::Client(
55                 IrrlichtDevice *device,
56                 const char *playername,
57                 MapDrawControl &control):
58         m_thread(this),
59         m_env(
60                 new ClientMap(this, control,
61                         device->getSceneManager()->getRootSceneNode(),
62                         device->getSceneManager(), 666),
63                 device->getSceneManager()
64         ),
65         m_con(PROTOCOL_ID, 512, CONNECTION_TIMEOUT, this),
66         m_device(device),
67         camera_position(0,0,0),
68         camera_direction(0,0,1),
69         m_server_ser_ver(SER_FMT_VER_INVALID),
70         m_step_dtime(0.0),
71         m_inventory_updated(false),
72         m_time_of_day(0)
73 {
74         m_packetcounter_timer = 0.0;
75         m_delete_unused_sectors_timer = 0.0;
76         m_connection_reinit_timer = 0.0;
77         m_avg_rtt_timer = 0.0;
78         m_playerpos_send_timer = 0.0;
79
80         //m_fetchblock_mutex.Init();
81         m_incoming_queue_mutex.Init();
82         m_env_mutex.Init();
83         m_con_mutex.Init();
84         m_step_dtime_mutex.Init();
85
86         m_thread.Start();
87
88         /*
89                 Add local player
90         */
91         {
92                 JMutexAutoLock envlock(m_env_mutex);
93
94                 Player *player = new LocalPlayer();
95
96                 player->updateName(playername);
97
98                 m_env.addPlayer(player);
99         }
100
101         // Add some active objects for testing
102         /*{
103                 ClientActiveObject *obj = new TestCAO(0, v3f(0, 10*BS, 0));
104                 m_env.addActiveObject(obj);
105         }*/
106 }
107
108 Client::~Client()
109 {
110         {
111                 JMutexAutoLock conlock(m_con_mutex);
112                 m_con.Disconnect();
113         }
114
115         m_thread.setRun(false);
116         while(m_thread.IsRunning())
117                 sleep_ms(100);
118 }
119
120 void Client::connect(Address address)
121 {
122         DSTACK(__FUNCTION_NAME);
123         JMutexAutoLock lock(m_con_mutex);
124         m_con.setTimeoutMs(0);
125         m_con.Connect(address);
126 }
127
128 bool Client::connectedAndInitialized()
129 {
130         JMutexAutoLock lock(m_con_mutex);
131
132         if(m_con.Connected() == false)
133                 return false;
134         
135         if(m_server_ser_ver == SER_FMT_VER_INVALID)
136                 return false;
137         
138         return true;
139 }
140
141 void Client::step(float dtime)
142 {
143         DSTACK(__FUNCTION_NAME);
144         
145         // Limit a bit
146         if(dtime > 2.0)
147                 dtime = 2.0;
148         
149         
150         //dstream<<"Client steps "<<dtime<<std::endl;
151
152         {
153                 //TimeTaker timer("ReceiveAll()", m_device);
154                 // 0ms
155                 ReceiveAll();
156         }
157         
158         {
159                 //TimeTaker timer("m_con_mutex + m_con.RunTimeouts()", m_device);
160                 // 0ms
161                 JMutexAutoLock lock(m_con_mutex);
162                 m_con.RunTimeouts(dtime);
163         }
164
165         /*
166                 Packet counter
167         */
168         {
169                 float &counter = m_packetcounter_timer;
170                 counter -= dtime;
171                 if(counter <= 0.0)
172                 {
173                         counter = 20.0;
174                         
175                         dout_client<<"Client packetcounter (20s):"<<std::endl;
176                         m_packetcounter.print(dout_client);
177                         m_packetcounter.clear();
178                 }
179         }
180
181         {
182                 /*
183                         Delete unused sectors
184
185                         NOTE: This jams the game for a while because deleting sectors
186                               clear caches
187                 */
188                 
189                 float &counter = m_delete_unused_sectors_timer;
190                 counter -= dtime;
191                 if(counter <= 0.0)
192                 {
193                         // 3 minute interval
194                         //counter = 180.0;
195                         counter = 60.0;
196
197                         JMutexAutoLock lock(m_env_mutex);
198
199                         core::list<v3s16> deleted_blocks;
200
201                         float delete_unused_sectors_timeout = 
202                                 g_settings.getFloat("client_delete_unused_sectors_timeout");
203         
204                         // Delete sector blocks
205                         /*u32 num = m_env.getMap().deleteUnusedSectors
206                                         (delete_unused_sectors_timeout,
207                                         true, &deleted_blocks);*/
208                         
209                         // Delete whole sectors
210                         u32 num = m_env.getMap().deleteUnusedSectors
211                                         (delete_unused_sectors_timeout,
212                                         false, &deleted_blocks);
213
214                         if(num > 0)
215                         {
216                                 /*dstream<<DTIME<<"Client: Deleted blocks of "<<num
217                                                 <<" unused sectors"<<std::endl;*/
218                                 dstream<<DTIME<<"Client: Deleted "<<num
219                                                 <<" unused sectors"<<std::endl;
220                                 
221                                 /*
222                                         Send info to server
223                                 */
224
225                                 // Env is locked so con can be locked.
226                                 JMutexAutoLock lock(m_con_mutex);
227                                 
228                                 core::list<v3s16>::Iterator i = deleted_blocks.begin();
229                                 core::list<v3s16> sendlist;
230                                 for(;;)
231                                 {
232                                         if(sendlist.size() == 255 || i == deleted_blocks.end())
233                                         {
234                                                 if(sendlist.size() == 0)
235                                                         break;
236                                                 /*
237                                                         [0] u16 command
238                                                         [2] u8 count
239                                                         [3] v3s16 pos_0
240                                                         [3+6] v3s16 pos_1
241                                                         ...
242                                                 */
243                                                 u32 replysize = 2+1+6*sendlist.size();
244                                                 SharedBuffer<u8> reply(replysize);
245                                                 writeU16(&reply[0], TOSERVER_DELETEDBLOCKS);
246                                                 reply[2] = sendlist.size();
247                                                 u32 k = 0;
248                                                 for(core::list<v3s16>::Iterator
249                                                                 j = sendlist.begin();
250                                                                 j != sendlist.end(); j++)
251                                                 {
252                                                         writeV3S16(&reply[2+1+6*k], *j);
253                                                         k++;
254                                                 }
255                                                 m_con.Send(PEER_ID_SERVER, 1, reply, true);
256
257                                                 if(i == deleted_blocks.end())
258                                                         break;
259
260                                                 sendlist.clear();
261                                         }
262
263                                         sendlist.push_back(*i);
264                                         i++;
265                                 }
266                         }
267                 }
268         }
269
270         bool connected = connectedAndInitialized();
271
272         if(connected == false)
273         {
274                 float &counter = m_connection_reinit_timer;
275                 counter -= dtime;
276                 if(counter <= 0.0)
277                 {
278                         counter = 2.0;
279
280                         JMutexAutoLock envlock(m_env_mutex);
281                         
282                         Player *myplayer = m_env.getLocalPlayer();
283                         assert(myplayer != NULL);
284         
285                         // Send TOSERVER_INIT
286                         // [0] u16 TOSERVER_INIT
287                         // [2] u8 SER_FMT_VER_HIGHEST
288                         // [3] u8[20] player_name
289                         SharedBuffer<u8> data(2+1+PLAYERNAME_SIZE);
290                         writeU16(&data[0], TOSERVER_INIT);
291                         writeU8(&data[2], SER_FMT_VER_HIGHEST);
292                         memset((char*)&data[3], 0, PLAYERNAME_SIZE);
293                         snprintf((char*)&data[3], PLAYERNAME_SIZE, "%s", myplayer->getName());
294                         // Send as unreliable
295                         Send(0, data, false);
296                 }
297
298                 // Not connected, return
299                 return;
300         }
301
302         /*
303                 Do stuff if connected
304         */
305         
306         {
307                 // 0ms
308                 JMutexAutoLock lock(m_env_mutex);
309
310                 // Control local player (0ms)
311                 LocalPlayer *player = m_env.getLocalPlayer();
312                 assert(player != NULL);
313                 player->applyControl(dtime);
314
315                 //TimeTaker envtimer("env step", m_device);
316                 // Step environment
317                 m_env.step(dtime);
318
319                 // Step active blocks
320                 for(core::map<v3s16, bool>::Iterator
321                                 i = m_active_blocks.getIterator();
322                                 i.atEnd() == false; i++)
323                 {
324                         v3s16 p = i.getNode()->getKey();
325
326                         MapBlock *block = NULL;
327                         try
328                         {
329                                 block = m_env.getMap().getBlockNoCreate(p);
330                                 block->stepObjects(dtime, false, m_env.getDayNightRatio());
331                         }
332                         catch(InvalidPositionException &e)
333                         {
334                         }
335                 }
336         }
337
338         {
339                 float &counter = m_avg_rtt_timer;
340                 counter += dtime;
341                 if(counter >= 10)
342                 {
343                         counter = 0.0;
344                         JMutexAutoLock lock(m_con_mutex);
345                         // connectedAndInitialized() is true, peer exists.
346                         con::Peer *peer = m_con.GetPeer(PEER_ID_SERVER);
347                         dstream<<DTIME<<"Client: avg_rtt="<<peer->avg_rtt<<std::endl;
348                 }
349         }
350         {
351                 float &counter = m_playerpos_send_timer;
352                 counter += dtime;
353                 if(counter >= 0.2)
354                 {
355                         counter = 0.0;
356                         sendPlayerPos();
357                 }
358         }
359
360         /*{
361                 JMutexAutoLock lock(m_step_dtime_mutex);
362                 m_step_dtime += dtime;
363         }*/
364 }
365
366 float Client::asyncStep()
367 {
368         DSTACK(__FUNCTION_NAME);
369         //dstream<<"Client::asyncStep()"<<std::endl;
370         
371         /*float dtime;
372         {
373                 JMutexAutoLock lock1(m_step_dtime_mutex);
374                 if(m_step_dtime < 0.001)
375                         return 0.0;
376                 dtime = m_step_dtime;
377                 m_step_dtime = 0.0;
378         }
379
380         return dtime;*/
381         return 0.0;
382 }
383
384 // Virtual methods from con::PeerHandler
385 void Client::peerAdded(con::Peer *peer)
386 {
387         derr_client<<"Client::peerAdded(): peer->id="
388                         <<peer->id<<std::endl;
389 }
390 void Client::deletingPeer(con::Peer *peer, bool timeout)
391 {
392         derr_client<<"Client::deletingPeer(): "
393                         "Server Peer is getting deleted "
394                         <<"(timeout="<<timeout<<")"<<std::endl;
395 }
396
397 void Client::ReceiveAll()
398 {
399         DSTACK(__FUNCTION_NAME);
400         for(;;)
401         {
402                 try{
403                         Receive();
404                 }
405                 catch(con::NoIncomingDataException &e)
406                 {
407                         break;
408                 }
409                 catch(con::InvalidIncomingDataException &e)
410                 {
411                         dout_client<<DTIME<<"Client::ReceiveAll(): "
412                                         "InvalidIncomingDataException: what()="
413                                         <<e.what()<<std::endl;
414                 }
415         }
416 }
417
418 void Client::Receive()
419 {
420         DSTACK(__FUNCTION_NAME);
421         u32 data_maxsize = 10000;
422         Buffer<u8> data(data_maxsize);
423         u16 sender_peer_id;
424         u32 datasize;
425         {
426                 //TimeTaker t1("con mutex and receive", m_device);
427                 JMutexAutoLock lock(m_con_mutex);
428                 datasize = m_con.Receive(sender_peer_id, *data, data_maxsize);
429         }
430         //TimeTaker t1("ProcessData", m_device);
431         ProcessData(*data, datasize, sender_peer_id);
432 }
433
434 /*
435         sender_peer_id given to this shall be quaranteed to be a valid peer
436 */
437 void Client::ProcessData(u8 *data, u32 datasize, u16 sender_peer_id)
438 {
439         DSTACK(__FUNCTION_NAME);
440
441         // Ignore packets that don't even fit a command
442         if(datasize < 2)
443         {
444                 m_packetcounter.add(60000);
445                 return;
446         }
447
448         ToClientCommand command = (ToClientCommand)readU16(&data[0]);
449
450         //dstream<<"Client: received command="<<command<<std::endl;
451         m_packetcounter.add((u16)command);
452         
453         /*
454                 If this check is removed, be sure to change the queue
455                 system to know the ids
456         */
457         if(sender_peer_id != PEER_ID_SERVER)
458         {
459                 dout_client<<DTIME<<"Client::ProcessData(): Discarding data not "
460                                 "coming from server: peer_id="<<sender_peer_id
461                                 <<std::endl;
462                 return;
463         }
464
465         con::Peer *peer;
466         {
467                 JMutexAutoLock lock(m_con_mutex);
468                 // All data is coming from the server
469                 // PeerNotFoundException is handled by caller.
470                 peer = m_con.GetPeer(PEER_ID_SERVER);
471         }
472
473         u8 ser_version = m_server_ser_ver;
474
475         //dstream<<"Client received command="<<(int)command<<std::endl;
476
477         // Execute fast commands straight away
478
479         if(command == TOCLIENT_INIT)
480         {
481                 if(datasize < 3)
482                         return;
483
484                 u8 deployed = data[2];
485
486                 dout_client<<DTIME<<"Client: TOCLIENT_INIT received with "
487                                 "deployed="<<((int)deployed&0xff)<<std::endl;
488
489                 if(deployed < SER_FMT_VER_LOWEST
490                                 || deployed > SER_FMT_VER_HIGHEST)
491                 {
492                         derr_client<<DTIME<<"Client: TOCLIENT_INIT: Server sent "
493                                         <<"unsupported ser_fmt_ver"<<std::endl;
494                         return;
495                 }
496                 
497                 m_server_ser_ver = deployed;
498
499                 // Get player position
500                 v3s16 playerpos_s16(0, BS*2+BS*20, 0);
501                 if(datasize >= 2+1+6)
502                         playerpos_s16 = readV3S16(&data[2+1]);
503                 v3f playerpos_f = intToFloat(playerpos_s16, BS) - v3f(0, BS/2, 0);
504
505                 { //envlock
506                         JMutexAutoLock envlock(m_env_mutex);
507                         
508                         // Set player position
509                         Player *player = m_env.getLocalPlayer();
510                         assert(player != NULL);
511                         player->setPosition(playerpos_f);
512                 }
513                 
514                 if(datasize >= 2+1+6+8)
515                 {
516                         // Get map seed
517                         m_map_seed = readU64(&data[2+1+6]);
518                         dstream<<"Client: received map seed: "<<m_map_seed<<std::endl;
519                 }
520                 
521                 // Reply to server
522                 u32 replysize = 2;
523                 SharedBuffer<u8> reply(replysize);
524                 writeU16(&reply[0], TOSERVER_INIT2);
525                 // Send as reliable
526                 m_con.Send(PEER_ID_SERVER, 1, reply, true);
527
528                 return;
529         }
530         
531         if(ser_version == SER_FMT_VER_INVALID)
532         {
533                 dout_client<<DTIME<<"WARNING: Client: Server serialization"
534                                 " format invalid or not initialized."
535                                 " Skipping incoming command="<<command<<std::endl;
536                 return;
537         }
538         
539         // Just here to avoid putting the two if's together when
540         // making some copypasta
541         {}
542
543         if(command == TOCLIENT_REMOVENODE)
544         {
545                 if(datasize < 8)
546                         return;
547                 v3s16 p;
548                 p.X = readS16(&data[2]);
549                 p.Y = readS16(&data[4]);
550                 p.Z = readS16(&data[6]);
551                 
552                 //TimeTaker t1("TOCLIENT_REMOVENODE", g_device);
553                 
554                 // This will clear the cracking animation after digging
555                 ((ClientMap&)m_env.getMap()).clearTempMod(p);
556
557                 removeNode(p);
558         }
559         else if(command == TOCLIENT_ADDNODE)
560         {
561                 if(datasize < 8 + MapNode::serializedLength(ser_version))
562                         return;
563
564                 v3s16 p;
565                 p.X = readS16(&data[2]);
566                 p.Y = readS16(&data[4]);
567                 p.Z = readS16(&data[6]);
568                 
569                 //TimeTaker t1("TOCLIENT_ADDNODE", g_device);
570
571                 MapNode n;
572                 n.deSerialize(&data[8], ser_version);
573                 
574                 addNode(p, n);
575         }
576         else if(command == TOCLIENT_PLAYERPOS)
577         {
578                 dstream<<"WARNING: Received deprecated TOCLIENT_PLAYERPOS"
579                                 <<std::endl;
580                 /*u16 our_peer_id;
581                 {
582                         JMutexAutoLock lock(m_con_mutex);
583                         our_peer_id = m_con.GetPeerID();
584                 }
585                 // Cancel if we don't have a peer id
586                 if(our_peer_id == PEER_ID_INEXISTENT){
587                         dout_client<<DTIME<<"TOCLIENT_PLAYERPOS cancelled: "
588                                         "we have no peer id"
589                                         <<std::endl;
590                         return;
591                 }*/
592
593                 { //envlock
594                         JMutexAutoLock envlock(m_env_mutex);
595                         
596                         u32 player_size = 2+12+12+4+4;
597                                 
598                         u32 player_count = (datasize-2) / player_size;
599                         u32 start = 2;
600                         for(u32 i=0; i<player_count; i++)
601                         {
602                                 u16 peer_id = readU16(&data[start]);
603
604                                 Player *player = m_env.getPlayer(peer_id);
605
606                                 // Skip if player doesn't exist
607                                 if(player == NULL)
608                                 {
609                                         start += player_size;
610                                         continue;
611                                 }
612
613                                 // Skip if player is local player
614                                 if(player->isLocal())
615                                 {
616                                         start += player_size;
617                                         continue;
618                                 }
619
620                                 v3s32 ps = readV3S32(&data[start+2]);
621                                 v3s32 ss = readV3S32(&data[start+2+12]);
622                                 s32 pitch_i = readS32(&data[start+2+12+12]);
623                                 s32 yaw_i = readS32(&data[start+2+12+12+4]);
624                                 /*dstream<<"Client: got "
625                                                 <<"pitch_i="<<pitch_i
626                                                 <<" yaw_i="<<yaw_i<<std::endl;*/
627                                 f32 pitch = (f32)pitch_i / 100.0;
628                                 f32 yaw = (f32)yaw_i / 100.0;
629                                 v3f position((f32)ps.X/100., (f32)ps.Y/100., (f32)ps.Z/100.);
630                                 v3f speed((f32)ss.X/100., (f32)ss.Y/100., (f32)ss.Z/100.);
631                                 player->setPosition(position);
632                                 player->setSpeed(speed);
633                                 player->setPitch(pitch);
634                                 player->setYaw(yaw);
635
636                                 /*dstream<<"Client: player "<<peer_id
637                                                 <<" pitch="<<pitch
638                                                 <<" yaw="<<yaw<<std::endl;*/
639
640                                 start += player_size;
641                         }
642                 } //envlock
643         }
644         else if(command == TOCLIENT_PLAYERINFO)
645         {
646                 u16 our_peer_id;
647                 {
648                         JMutexAutoLock lock(m_con_mutex);
649                         our_peer_id = m_con.GetPeerID();
650                 }
651                 // Cancel if we don't have a peer id
652                 if(our_peer_id == PEER_ID_INEXISTENT){
653                         dout_client<<DTIME<<"TOCLIENT_PLAYERINFO cancelled: "
654                                         "we have no peer id"
655                                         <<std::endl;
656                         return;
657                 }
658                 
659                 //dstream<<DTIME<<"Client: Server reports players:"<<std::endl;
660
661                 { //envlock
662                         JMutexAutoLock envlock(m_env_mutex);
663                         
664                         u32 item_size = 2+PLAYERNAME_SIZE;
665                         u32 player_count = (datasize-2) / item_size;
666                         u32 start = 2;
667                         // peer_ids
668                         core::list<u16> players_alive;
669                         for(u32 i=0; i<player_count; i++)
670                         {
671                                 // Make sure the name ends in '\0'
672                                 data[start+2+20-1] = 0;
673
674                                 u16 peer_id = readU16(&data[start]);
675
676                                 players_alive.push_back(peer_id);
677                                 
678                                 /*dstream<<DTIME<<"peer_id="<<peer_id
679                                                 <<" name="<<((char*)&data[start+2])<<std::endl;*/
680
681                                 // Don't update the info of the local player
682                                 if(peer_id == our_peer_id)
683                                 {
684                                         start += item_size;
685                                         continue;
686                                 }
687
688                                 Player *player = m_env.getPlayer(peer_id);
689
690                                 // Create a player if it doesn't exist
691                                 if(player == NULL)
692                                 {
693                                         player = new RemotePlayer(
694                                                         m_device->getSceneManager()->getRootSceneNode(),
695                                                         m_device,
696                                                         -1);
697                                         player->peer_id = peer_id;
698                                         m_env.addPlayer(player);
699                                         dout_client<<DTIME<<"Client: Adding new player "
700                                                         <<peer_id<<std::endl;
701                                 }
702                                 
703                                 player->updateName((char*)&data[start+2]);
704
705                                 start += item_size;
706                         }
707                         
708                         /*
709                                 Remove those players from the environment that
710                                 weren't listed by the server.
711                         */
712                         //dstream<<DTIME<<"Removing dead players"<<std::endl;
713                         core::list<Player*> players = m_env.getPlayers();
714                         core::list<Player*>::Iterator ip;
715                         for(ip=players.begin(); ip!=players.end(); ip++)
716                         {
717                                 // Ingore local player
718                                 if((*ip)->isLocal())
719                                         continue;
720                                 
721                                 // Warn about a special case
722                                 if((*ip)->peer_id == 0)
723                                 {
724                                         dstream<<DTIME<<"WARNING: Client: Removing "
725                                                         "dead player with id=0"<<std::endl;
726                                 }
727
728                                 bool is_alive = false;
729                                 core::list<u16>::Iterator i;
730                                 for(i=players_alive.begin(); i!=players_alive.end(); i++)
731                                 {
732                                         if((*ip)->peer_id == *i)
733                                         {
734                                                 is_alive = true;
735                                                 break;
736                                         }
737                                 }
738                                 /*dstream<<DTIME<<"peer_id="<<((*ip)->peer_id)
739                                                 <<" is_alive="<<is_alive<<std::endl;*/
740                                 if(is_alive)
741                                         continue;
742                                 dstream<<DTIME<<"Removing dead player "<<(*ip)->peer_id
743                                                 <<std::endl;
744                                 m_env.removePlayer((*ip)->peer_id);
745                         }
746                 } //envlock
747         }
748         else if(command == TOCLIENT_SECTORMETA)
749         {
750                 /*
751                         [0] u16 command
752                         [2] u8 sector count
753                         [3...] v2s16 pos + sector metadata
754                 */
755                 if(datasize < 3)
756                         return;
757
758                 //dstream<<"Client received TOCLIENT_SECTORMETA"<<std::endl;
759
760                 { //envlock
761                         JMutexAutoLock envlock(m_env_mutex);
762                         
763                         std::string datastring((char*)&data[2], datasize-2);
764                         std::istringstream is(datastring, std::ios_base::binary);
765
766                         u8 buf[4];
767
768                         is.read((char*)buf, 1);
769                         u16 sector_count = readU8(buf);
770                         
771                         //dstream<<"sector_count="<<sector_count<<std::endl;
772
773                         for(u16 i=0; i<sector_count; i++)
774                         {
775                                 // Read position
776                                 is.read((char*)buf, 4);
777                                 v2s16 pos = readV2S16(buf);
778                                 /*dstream<<"Client: deserializing sector at "
779                                                 <<"("<<pos.X<<","<<pos.Y<<")"<<std::endl;*/
780                                 // Create sector
781                                 assert(m_env.getMap().mapType() == MAPTYPE_CLIENT);
782                                 ((ClientMap&)m_env.getMap()).deSerializeSector(pos, is);
783                         }
784                 } //envlock
785         }
786         else if(command == TOCLIENT_INVENTORY)
787         {
788                 if(datasize < 3)
789                         return;
790
791                 //TimeTaker t1("Parsing TOCLIENT_INVENTORY", m_device);
792
793                 { //envlock
794                         //TimeTaker t2("mutex locking", m_device);
795                         JMutexAutoLock envlock(m_env_mutex);
796                         //t2.stop();
797                         
798                         //TimeTaker t3("istringstream init", m_device);
799                         std::string datastring((char*)&data[2], datasize-2);
800                         std::istringstream is(datastring, std::ios_base::binary);
801                         //t3.stop();
802                         
803                         //m_env.printPlayers(dstream);
804
805                         //TimeTaker t4("player get", m_device);
806                         Player *player = m_env.getLocalPlayer();
807                         assert(player != NULL);
808                         //t4.stop();
809
810                         //TimeTaker t1("inventory.deSerialize()", m_device);
811                         player->inventory.deSerialize(is);
812                         //t1.stop();
813
814                         m_inventory_updated = true;
815
816                         //dstream<<"Client got player inventory:"<<std::endl;
817                         //player->inventory.print(dstream);
818                 }
819         }
820         //DEBUG
821         else if(command == TOCLIENT_OBJECTDATA)
822         //else if(0)
823         {
824                 // Strip command word and create a stringstream
825                 std::string datastring((char*)&data[2], datasize-2);
826                 std::istringstream is(datastring, std::ios_base::binary);
827                 
828                 { //envlock
829                 
830                 JMutexAutoLock envlock(m_env_mutex);
831
832                 u8 buf[12];
833
834                 /*
835                         Read players
836                 */
837
838                 is.read((char*)buf, 2);
839                 u16 playercount = readU16(buf);
840                 
841                 for(u16 i=0; i<playercount; i++)
842                 {
843                         is.read((char*)buf, 2);
844                         u16 peer_id = readU16(buf);
845                         is.read((char*)buf, 12);
846                         v3s32 p_i = readV3S32(buf);
847                         is.read((char*)buf, 12);
848                         v3s32 s_i = readV3S32(buf);
849                         is.read((char*)buf, 4);
850                         s32 pitch_i = readS32(buf);
851                         is.read((char*)buf, 4);
852                         s32 yaw_i = readS32(buf);
853                         
854                         Player *player = m_env.getPlayer(peer_id);
855
856                         // Skip if player doesn't exist
857                         if(player == NULL)
858                         {
859                                 continue;
860                         }
861
862                         // Skip if player is local player
863                         if(player->isLocal())
864                         {
865                                 continue;
866                         }
867         
868                         f32 pitch = (f32)pitch_i / 100.0;
869                         f32 yaw = (f32)yaw_i / 100.0;
870                         v3f position((f32)p_i.X/100., (f32)p_i.Y/100., (f32)p_i.Z/100.);
871                         v3f speed((f32)s_i.X/100., (f32)s_i.Y/100., (f32)s_i.Z/100.);
872                         
873                         player->setPosition(position);
874                         player->setSpeed(speed);
875                         player->setPitch(pitch);
876                         player->setYaw(yaw);
877                 }
878
879                 /*
880                         Read block objects
881                 */
882
883                 // Read active block count
884                 is.read((char*)buf, 2);
885                 u16 blockcount = readU16(buf);
886                 
887                 // Initialize delete queue with all active blocks
888                 core::map<v3s16, bool> abs_to_delete;
889                 for(core::map<v3s16, bool>::Iterator
890                                 i = m_active_blocks.getIterator();
891                                 i.atEnd() == false; i++)
892                 {
893                         v3s16 p = i.getNode()->getKey();
894                         /*dstream<<"adding "
895                                         <<"("<<p.x<<","<<p.y<<","<<p.z<<") "
896                                         <<" to abs_to_delete"
897                                         <<std::endl;*/
898                         abs_to_delete.insert(p, true);
899                 }
900
901                 /*dstream<<"Initial delete queue size: "<<abs_to_delete.size()
902                                 <<std::endl;*/
903                 
904                 for(u16 i=0; i<blockcount; i++)
905                 {
906                         // Read blockpos
907                         is.read((char*)buf, 6);
908                         v3s16 p = readV3S16(buf);
909                         // Get block from somewhere
910                         MapBlock *block = NULL;
911                         try{
912                                 block = m_env.getMap().getBlockNoCreate(p);
913                         }
914                         catch(InvalidPositionException &e)
915                         {
916                                 //TODO: Create a dummy block?
917                         }
918                         if(block == NULL)
919                         {
920                                 dstream<<"WARNING: "
921                                                 <<"Could not get block at blockpos "
922                                                 <<"("<<p.X<<","<<p.Y<<","<<p.Z<<") "
923                                                 <<"in TOCLIENT_OBJECTDATA. Ignoring "
924                                                 <<"following block object data."
925                                                 <<std::endl;
926                                 return;
927                         }
928
929                         /*dstream<<"Client updating objects for block "
930                                         <<"("<<p.X<<","<<p.Y<<","<<p.Z<<")"
931                                         <<std::endl;*/
932
933                         // Insert to active block list
934                         m_active_blocks.insert(p, true);
935
936                         // Remove from deletion queue
937                         if(abs_to_delete.find(p) != NULL)
938                                 abs_to_delete.remove(p);
939
940                         /*
941                                 Update objects of block
942                                 
943                                 NOTE: Be sure this is done in the main thread.
944                         */
945                         block->updateObjects(is, m_server_ser_ver,
946                                         m_device->getSceneManager(), m_env.getDayNightRatio());
947                 }
948                 
949                 /*dstream<<"Final delete queue size: "<<abs_to_delete.size()
950                                 <<std::endl;*/
951                 
952                 // Delete objects of blocks in delete queue
953                 for(core::map<v3s16, bool>::Iterator
954                                 i = abs_to_delete.getIterator();
955                                 i.atEnd() == false; i++)
956                 {
957                         v3s16 p = i.getNode()->getKey();
958                         try
959                         {
960                                 MapBlock *block = m_env.getMap().getBlockNoCreate(p);
961                                 
962                                 // Clear objects
963                                 block->clearObjects();
964                                 // Remove from active blocks list
965                                 m_active_blocks.remove(p);
966                         }
967                         catch(InvalidPositionException &e)
968                         {
969                                 dstream<<"WARNAING: Client: "
970                                                 <<"Couldn't clear objects of active->inactive"
971                                                 <<" block "
972                                                 <<"("<<p.X<<","<<p.Y<<","<<p.Z<<")"
973                                                 <<" because block was not found"
974                                                 <<std::endl;
975                                 // Ignore
976                         }
977                 }
978
979                 } //envlock
980         }
981         else if(command == TOCLIENT_TIME_OF_DAY)
982         {
983                 if(datasize < 4)
984                         return;
985                 
986                 u16 time = readU16(&data[2]);
987                 time = time % 24000;
988                 m_time_of_day.set(time);
989                 //dstream<<"Client: time="<<time<<std::endl;
990                 
991                 /*
992                         Day/night
993
994                         time_of_day:
995                         0 = midnight
996                         12000 = midday
997                 */
998                 {
999                         u32 dr = time_to_daynight_ratio(m_time_of_day.get());
1000
1001                         dstream<<"Client: time_of_day="<<m_time_of_day.get()
1002                                         <<", dr="<<dr
1003                                         <<std::endl;
1004                         
1005                         if(dr != m_env.getDayNightRatio())
1006                         {
1007                                 dout_client<<DTIME<<"Client: changing day-night ratio"<<std::endl;
1008                                 m_env.setDayNightRatio(dr);
1009                                 m_env.expireMeshes(true);
1010                         }
1011                 }
1012
1013         }
1014         else if(command == TOCLIENT_CHAT_MESSAGE)
1015         {
1016                 /*
1017                         u16 command
1018                         u16 length
1019                         wstring message
1020                 */
1021                 u8 buf[6];
1022                 std::string datastring((char*)&data[2], datasize-2);
1023                 std::istringstream is(datastring, std::ios_base::binary);
1024                 
1025                 // Read stuff
1026                 is.read((char*)buf, 2);
1027                 u16 len = readU16(buf);
1028                 
1029                 std::wstring message;
1030                 for(u16 i=0; i<len; i++)
1031                 {
1032                         is.read((char*)buf, 2);
1033                         message += (wchar_t)readU16(buf);
1034                 }
1035
1036                 /*dstream<<"Client received chat message: "
1037                                 <<wide_to_narrow(message)<<std::endl;*/
1038                 
1039                 m_chat_queue.push_back(message);
1040         }
1041         else if(command == TOCLIENT_ACTIVE_OBJECT_REMOVE_ADD)
1042         {
1043                 /*
1044                         u16 command
1045                         u16 count of removed objects
1046                         for all removed objects {
1047                                 u16 id
1048                         }
1049                         u16 count of added objects
1050                         for all added objects {
1051                                 u16 id
1052                                 u8 type
1053                                 u16 initialization data length
1054                                 string initialization data
1055                         }
1056                 */
1057
1058                 char buf[6];
1059                 // Get all data except the command number
1060                 std::string datastring((char*)&data[2], datasize-2);
1061                 // Throw them in an istringstream
1062                 std::istringstream is(datastring, std::ios_base::binary);
1063
1064                 // Read stuff
1065                 
1066                 // Read removed objects
1067                 is.read(buf, 2);
1068                 u16 removed_count = readU16((u8*)buf);
1069                 for(u16 i=0; i<removed_count; i++)
1070                 {
1071                         is.read(buf, 2);
1072                         u16 id = readU16((u8*)buf);
1073                         // Remove it
1074                         {
1075                                 JMutexAutoLock envlock(m_env_mutex);
1076                                 m_env.removeActiveObject(id);
1077                         }
1078                 }
1079                 
1080                 // Read added objects
1081                 is.read(buf, 2);
1082                 u16 added_count = readU16((u8*)buf);
1083                 for(u16 i=0; i<added_count; i++)
1084                 {
1085                         is.read(buf, 2);
1086                         u16 id = readU16((u8*)buf);
1087                         is.read(buf, 1);
1088                         u8 type = readU8((u8*)buf);
1089                         std::string data = deSerializeLongString(is);
1090                         // Add it
1091                         {
1092                                 JMutexAutoLock envlock(m_env_mutex);
1093                                 m_env.addActiveObject(id, type, data);
1094                         }
1095                 }
1096         }
1097         else if(command == TOCLIENT_ACTIVE_OBJECT_MESSAGES)
1098         {
1099                 /*
1100                         u16 command
1101                         for all objects
1102                         {
1103                                 u16 id
1104                                 u16 message length
1105                                 string message
1106                         }
1107                 */
1108                 char buf[6];
1109                 // Get all data except the command number
1110                 std::string datastring((char*)&data[2], datasize-2);
1111                 // Throw them in an istringstream
1112                 std::istringstream is(datastring, std::ios_base::binary);
1113                 
1114                 while(is.eof() == false)
1115                 {
1116                         // Read stuff
1117                         is.read(buf, 2);
1118                         u16 id = readU16((u8*)buf);
1119                         if(is.eof())
1120                                 break;
1121                         is.read(buf, 2);
1122                         u16 message_size = readU16((u8*)buf);
1123                         std::string message;
1124                         message.reserve(message_size);
1125                         for(u16 i=0; i<message_size; i++)
1126                         {
1127                                 is.read(buf, 1);
1128                                 message.append(buf, 1);
1129                         }
1130                         // Pass on to the environment
1131                         {
1132                                 JMutexAutoLock envlock(m_env_mutex);
1133                                 m_env.processActiveObjectMessage(id, message);
1134                         }
1135                 }
1136         }
1137         // Default to queueing it (for slow commands)
1138         else
1139         {
1140                 JMutexAutoLock lock(m_incoming_queue_mutex);
1141                 
1142                 IncomingPacket packet(data, datasize);
1143                 m_incoming_queue.push_back(packet);
1144         }
1145 }
1146
1147 /*
1148         Returns true if there was something in queue
1149 */
1150 bool Client::AsyncProcessPacket()
1151 {
1152         DSTACK(__FUNCTION_NAME);
1153         
1154         try //for catching con::PeerNotFoundException
1155         {
1156
1157         con::Peer *peer;
1158         {
1159                 JMutexAutoLock lock(m_con_mutex);
1160                 // All data is coming from the server
1161                 peer = m_con.GetPeer(PEER_ID_SERVER);
1162         }
1163         
1164         u8 ser_version = m_server_ser_ver;
1165
1166         IncomingPacket packet = getPacket();
1167         u8 *data = packet.m_data;
1168         u32 datasize = packet.m_datalen;
1169         
1170         // An empty packet means queue is empty
1171         if(data == NULL){
1172                 return false;
1173         }
1174         
1175         if(datasize < 2)
1176                 return true;
1177         
1178         ToClientCommand command = (ToClientCommand)readU16(&data[0]);
1179
1180         if(command == TOCLIENT_BLOCKDATA)
1181         {
1182                 // Ignore too small packet
1183                 if(datasize < 8)
1184                         return true;
1185                 /*if(datasize < 8 + MapBlock::serializedLength(ser_version))
1186                         goto getdata;*/
1187                         
1188                 v3s16 p;
1189                 p.X = readS16(&data[2]);
1190                 p.Y = readS16(&data[4]);
1191                 p.Z = readS16(&data[6]);
1192                 
1193                 /*dout_client<<DTIME<<"Client: Thread: BLOCKDATA for ("
1194                                 <<p.X<<","<<p.Y<<","<<p.Z<<")"<<std::endl;*/
1195
1196                 /*dstream<<DTIME<<"Client: Thread: BLOCKDATA for ("
1197                                 <<p.X<<","<<p.Y<<","<<p.Z<<")"<<std::endl;*/
1198                 
1199                 std::string datastring((char*)&data[8], datasize-8);
1200                 std::istringstream istr(datastring, std::ios_base::binary);
1201                 
1202                 MapSector *sector;
1203                 MapBlock *block;
1204                 
1205                 { //envlock
1206                         JMutexAutoLock envlock(m_env_mutex);
1207                         
1208                         v2s16 p2d(p.X, p.Z);
1209                         sector = m_env.getMap().emergeSector(p2d);
1210                         
1211                         v2s16 sp = sector->getPos();
1212                         if(sp != p2d)
1213                         {
1214                                 dstream<<"ERROR: Got sector with getPos()="
1215                                                 <<"("<<sp.X<<","<<sp.Y<<"), tried to get"
1216                                                 <<"("<<p2d.X<<","<<p2d.Y<<")"<<std::endl;
1217                         }
1218
1219                         assert(sp == p2d);
1220                         //assert(sector->getPos() == p2d);
1221                         
1222                         try{
1223                                 block = sector->getBlockNoCreate(p.Y);
1224                                 /*
1225                                         Update an existing block
1226                                 */
1227                                 //dstream<<"Updating"<<std::endl;
1228                                 block->deSerialize(istr, ser_version);
1229                                 //block->setChangedFlag();
1230                         }
1231                         catch(InvalidPositionException &e)
1232                         {
1233                                 /*
1234                                         Create a new block
1235                                 */
1236                                 //dstream<<"Creating new"<<std::endl;
1237                                 block = new MapBlock(&m_env.getMap(), p);
1238                                 block->deSerialize(istr, ser_version);
1239                                 sector->insertBlock(block);
1240                                 //block->setChangedFlag();
1241
1242                                 //DEBUG
1243                                 /*NodeMod mod;
1244                                 mod.type = NODEMOD_CHANGECONTENT;
1245                                 mod.param = CONTENT_MESE;
1246                                 block->setTempMod(v3s16(8,10,8), mod);
1247                                 block->setTempMod(v3s16(8,9,8), mod);
1248                                 block->setTempMod(v3s16(8,8,8), mod);
1249                                 block->setTempMod(v3s16(8,7,8), mod);
1250                                 block->setTempMod(v3s16(8,6,8), mod);*/
1251                                 
1252                                 /*
1253                                         Add some coulds
1254                                         Well, this is a dumb way to do it, they should just
1255                                         be drawn as separate objects.
1256                                 */
1257                                 /*if(p.Y == 3)
1258                                 {
1259                                         NodeMod mod;
1260                                         mod.type = NODEMOD_CHANGECONTENT;
1261                                         mod.param = CONTENT_CLOUD;
1262                                         v3s16 p2;
1263                                         p2.Y = 8;
1264                                         for(p2.X=3; p2.X<=13; p2.X++)
1265                                         for(p2.Z=3; p2.Z<=13; p2.Z++)
1266                                         {
1267                                                 block->setTempMod(p2, mod);
1268                                         }
1269                                 }*/
1270                         }
1271                 } //envlock
1272                 
1273                 /*
1274                         Acknowledge block.
1275                 */
1276                 /*
1277                         [0] u16 command
1278                         [2] u8 count
1279                         [3] v3s16 pos_0
1280                         [3+6] v3s16 pos_1
1281                         ...
1282                 */
1283                 u32 replysize = 2+1+6;
1284                 SharedBuffer<u8> reply(replysize);
1285                 writeU16(&reply[0], TOSERVER_GOTBLOCKS);
1286                 reply[2] = 1;
1287                 writeV3S16(&reply[3], p);
1288                 // Send as reliable
1289                 m_con.Send(PEER_ID_SERVER, 1, reply, true);
1290
1291                 /*
1292                         Update Mesh of this block and blocks at x-, y- and z-.
1293                         Environment should not be locked as it interlocks with the
1294                         main thread, from which is will want to retrieve textures.
1295                 */
1296
1297                 m_env.getClientMap().updateMeshes(block->getPos(), getDayNightRatio());
1298         }
1299         else
1300         {
1301                 dout_client<<DTIME<<"WARNING: Client: Ignoring unknown command "
1302                                 <<command<<std::endl;
1303         }
1304
1305         return true;
1306
1307         } //try
1308         catch(con::PeerNotFoundException &e)
1309         {
1310                 /*dout_client<<DTIME<<"Client::AsyncProcessData(): Cancelling: The server"
1311                                 " connection doesn't exist (a timeout or not yet connected?)"<<std::endl;*/
1312                 return false;
1313         }
1314 }
1315
1316 bool Client::AsyncProcessData()
1317 {
1318         for(;;)
1319         {
1320                 bool r = AsyncProcessPacket();
1321                 if(r == false)
1322                         break;
1323         }
1324         return false;
1325 }
1326
1327 void Client::Send(u16 channelnum, SharedBuffer<u8> data, bool reliable)
1328 {
1329         JMutexAutoLock lock(m_con_mutex);
1330         m_con.Send(PEER_ID_SERVER, channelnum, data, reliable);
1331 }
1332
1333 IncomingPacket Client::getPacket()
1334 {
1335         JMutexAutoLock lock(m_incoming_queue_mutex);
1336         
1337         core::list<IncomingPacket>::Iterator i;
1338         // Refer to first one
1339         i = m_incoming_queue.begin();
1340
1341         // If queue is empty, return empty packet
1342         if(i == m_incoming_queue.end()){
1343                 IncomingPacket packet;
1344                 return packet;
1345         }
1346         
1347         // Pop out first packet and return it
1348         IncomingPacket packet = *i;
1349         m_incoming_queue.erase(i);
1350         return packet;
1351 }
1352
1353 void Client::groundAction(u8 action, v3s16 nodepos_undersurface,
1354                 v3s16 nodepos_oversurface, u16 item)
1355 {
1356         if(connectedAndInitialized() == false){
1357                 dout_client<<DTIME<<"Client::groundAction() "
1358                                 "cancelled (not connected)"
1359                                 <<std::endl;
1360                 return;
1361         }
1362         
1363         /*
1364                 length: 17
1365                 [0] u16 command
1366                 [2] u8 action
1367                 [3] v3s16 nodepos_undersurface
1368                 [9] v3s16 nodepos_abovesurface
1369                 [15] u16 item
1370                 actions:
1371                 0: start digging
1372                 1: place block
1373                 2: stop digging (all parameters ignored)
1374                 3: digging completed
1375         */
1376         u8 datasize = 2 + 1 + 6 + 6 + 2;
1377         SharedBuffer<u8> data(datasize);
1378         writeU16(&data[0], TOSERVER_GROUND_ACTION);
1379         writeU8(&data[2], action);
1380         writeV3S16(&data[3], nodepos_undersurface);
1381         writeV3S16(&data[9], nodepos_oversurface);
1382         writeU16(&data[15], item);
1383         Send(0, data, true);
1384 }
1385
1386 void Client::clickObject(u8 button, v3s16 blockpos, s16 id, u16 item)
1387 {
1388         if(connectedAndInitialized() == false){
1389                 dout_client<<DTIME<<"Client::clickObject() "
1390                                 "cancelled (not connected)"
1391                                 <<std::endl;
1392                 return;
1393         }
1394         
1395         /*
1396                 [0] u16 command=TOSERVER_CLICK_OBJECT
1397                 [2] u8 button (0=left, 1=right)
1398                 [3] v3s16 block
1399                 [9] s16 id
1400                 [11] u16 item
1401         */
1402         u8 datasize = 2 + 1 + 6 + 2 + 2;
1403         SharedBuffer<u8> data(datasize);
1404         writeU16(&data[0], TOSERVER_CLICK_OBJECT);
1405         writeU8(&data[2], button);
1406         writeV3S16(&data[3], blockpos);
1407         writeS16(&data[9], id);
1408         writeU16(&data[11], item);
1409         Send(0, data, true);
1410 }
1411
1412 void Client::sendSignText(v3s16 blockpos, s16 id, std::string text)
1413 {
1414         /*
1415                 u16 command
1416                 v3s16 blockpos
1417                 s16 id
1418                 u16 textlen
1419                 textdata
1420         */
1421         std::ostringstream os(std::ios_base::binary);
1422         u8 buf[12];
1423         
1424         // Write command
1425         writeU16(buf, TOSERVER_SIGNTEXT);
1426         os.write((char*)buf, 2);
1427         
1428         // Write blockpos
1429         writeV3S16(buf, blockpos);
1430         os.write((char*)buf, 6);
1431
1432         // Write id
1433         writeS16(buf, id);
1434         os.write((char*)buf, 2);
1435
1436         u16 textlen = text.size();
1437         // Write text length
1438         writeS16(buf, textlen);
1439         os.write((char*)buf, 2);
1440
1441         // Write text
1442         os.write((char*)text.c_str(), textlen);
1443         
1444         // Make data buffer
1445         std::string s = os.str();
1446         SharedBuffer<u8> data((u8*)s.c_str(), s.size());
1447         // Send as reliable
1448         Send(0, data, true);
1449 }
1450         
1451 void Client::sendInventoryAction(InventoryAction *a)
1452 {
1453         std::ostringstream os(std::ios_base::binary);
1454         u8 buf[12];
1455         
1456         // Write command
1457         writeU16(buf, TOSERVER_INVENTORY_ACTION);
1458         os.write((char*)buf, 2);
1459
1460         a->serialize(os);
1461         
1462         // Make data buffer
1463         std::string s = os.str();
1464         SharedBuffer<u8> data((u8*)s.c_str(), s.size());
1465         // Send as reliable
1466         Send(0, data, true);
1467 }
1468
1469 void Client::sendChatMessage(const std::wstring &message)
1470 {
1471         std::ostringstream os(std::ios_base::binary);
1472         u8 buf[12];
1473         
1474         // Write command
1475         writeU16(buf, TOSERVER_CHAT_MESSAGE);
1476         os.write((char*)buf, 2);
1477         
1478         // Write length
1479         writeU16(buf, message.size());
1480         os.write((char*)buf, 2);
1481         
1482         // Write string
1483         for(u32 i=0; i<message.size(); i++)
1484         {
1485                 u16 w = message[i];
1486                 writeU16(buf, w);
1487                 os.write((char*)buf, 2);
1488         }
1489         
1490         // Make data buffer
1491         std::string s = os.str();
1492         SharedBuffer<u8> data((u8*)s.c_str(), s.size());
1493         // Send as reliable
1494         Send(0, data, true);
1495 }
1496
1497 void Client::sendPlayerPos()
1498 {
1499         JMutexAutoLock envlock(m_env_mutex);
1500         
1501         Player *myplayer = m_env.getLocalPlayer();
1502         if(myplayer == NULL)
1503                 return;
1504         
1505         u16 our_peer_id;
1506         {
1507                 JMutexAutoLock lock(m_con_mutex);
1508                 our_peer_id = m_con.GetPeerID();
1509         }
1510         
1511         // Set peer id if not set already
1512         if(myplayer->peer_id == PEER_ID_INEXISTENT)
1513                 myplayer->peer_id = our_peer_id;
1514         // Check that an existing peer_id is the same as the connection's
1515         assert(myplayer->peer_id == our_peer_id);
1516         
1517         v3f pf = myplayer->getPosition();
1518         v3s32 position(pf.X*100, pf.Y*100, pf.Z*100);
1519         v3f sf = myplayer->getSpeed();
1520         v3s32 speed(sf.X*100, sf.Y*100, sf.Z*100);
1521         s32 pitch = myplayer->getPitch() * 100;
1522         s32 yaw = myplayer->getYaw() * 100;
1523
1524         /*
1525                 Format:
1526                 [0] u16 command
1527                 [2] v3s32 position*100
1528                 [2+12] v3s32 speed*100
1529                 [2+12+12] s32 pitch*100
1530                 [2+12+12+4] s32 yaw*100
1531         */
1532
1533         SharedBuffer<u8> data(2+12+12+4+4);
1534         writeU16(&data[0], TOSERVER_PLAYERPOS);
1535         writeV3S32(&data[2], position);
1536         writeV3S32(&data[2+12], speed);
1537         writeS32(&data[2+12+12], pitch);
1538         writeS32(&data[2+12+12+4], yaw);
1539
1540         // Send as unreliable
1541         Send(0, data, false);
1542 }
1543
1544 void Client::removeNode(v3s16 p)
1545 {
1546         JMutexAutoLock envlock(m_env_mutex);
1547         
1548         core::map<v3s16, MapBlock*> modified_blocks;
1549
1550         try
1551         {
1552                 //TimeTaker t("removeNodeAndUpdate", m_device);
1553                 m_env.getMap().removeNodeAndUpdate(p, modified_blocks);
1554         }
1555         catch(InvalidPositionException &e)
1556         {
1557         }
1558         
1559         for(core::map<v3s16, MapBlock * >::Iterator
1560                         i = modified_blocks.getIterator();
1561                         i.atEnd() == false; i++)
1562         {
1563                 v3s16 p = i.getNode()->getKey();
1564                 m_env.getClientMap().updateMeshes(p, m_env.getDayNightRatio());
1565         }
1566 }
1567
1568 void Client::addNode(v3s16 p, MapNode n)
1569 {
1570         JMutexAutoLock envlock(m_env_mutex);
1571
1572         TimeTaker timer1("Client::addNode()");
1573
1574         core::map<v3s16, MapBlock*> modified_blocks;
1575
1576         try
1577         {
1578                 TimeTaker timer3("Client::addNode(): addNodeAndUpdate");
1579                 m_env.getMap().addNodeAndUpdate(p, n, modified_blocks);
1580         }
1581         catch(InvalidPositionException &e)
1582         {}
1583         
1584         TimeTaker timer2("Client::addNode(): updateMeshes");
1585
1586         for(core::map<v3s16, MapBlock * >::Iterator
1587                         i = modified_blocks.getIterator();
1588                         i.atEnd() == false; i++)
1589         {
1590                 v3s16 p = i.getNode()->getKey();
1591                 m_env.getClientMap().updateMeshes(p, m_env.getDayNightRatio());
1592         }
1593 }
1594         
1595 void Client::updateCamera(v3f pos, v3f dir)
1596 {
1597         m_env.getClientMap().updateCamera(pos, dir);
1598         camera_position = pos;
1599         camera_direction = dir;
1600 }
1601
1602 MapNode Client::getNode(v3s16 p)
1603 {
1604         JMutexAutoLock envlock(m_env_mutex);
1605         return m_env.getMap().getNode(p);
1606 }
1607
1608 v3f Client::getPlayerPosition()
1609 {
1610         JMutexAutoLock envlock(m_env_mutex);
1611         LocalPlayer *player = m_env.getLocalPlayer();
1612         assert(player != NULL);
1613         return player->getPosition();
1614 }
1615
1616 void Client::setPlayerControl(PlayerControl &control)
1617 {
1618         JMutexAutoLock envlock(m_env_mutex);
1619         LocalPlayer *player = m_env.getLocalPlayer();
1620         assert(player != NULL);
1621         player->control = control;
1622 }
1623
1624 // Returns true if the inventory of the local player has been
1625 // updated from the server. If it is true, it is set to false.
1626 bool Client::getLocalInventoryUpdated()
1627 {
1628         // m_inventory_updated is behind envlock
1629         JMutexAutoLock envlock(m_env_mutex);
1630         bool updated = m_inventory_updated;
1631         m_inventory_updated = false;
1632         return updated;
1633 }
1634
1635 // Copies the inventory of the local player to parameter
1636 void Client::getLocalInventory(Inventory &dst)
1637 {
1638         JMutexAutoLock envlock(m_env_mutex);
1639         Player *player = m_env.getLocalPlayer();
1640         assert(player != NULL);
1641         dst = player->inventory;
1642 }
1643
1644 MapBlockObject * Client::getSelectedObject(
1645                 f32 max_d,
1646                 v3f from_pos_f_on_map,
1647                 core::line3d<f32> shootline_on_map
1648         )
1649 {
1650         JMutexAutoLock envlock(m_env_mutex);
1651
1652         core::array<DistanceSortedObject> objects;
1653
1654         for(core::map<v3s16, bool>::Iterator
1655                         i = m_active_blocks.getIterator();
1656                         i.atEnd() == false; i++)
1657         {
1658                 v3s16 p = i.getNode()->getKey();
1659
1660                 MapBlock *block = NULL;
1661                 try
1662                 {
1663                         block = m_env.getMap().getBlockNoCreate(p);
1664                 }
1665                 catch(InvalidPositionException &e)
1666                 {
1667                         continue;
1668                 }
1669
1670                 // Calculate from_pos relative to block
1671                 v3s16 block_pos_i_on_map = block->getPosRelative();
1672                 v3f block_pos_f_on_map = intToFloat(block_pos_i_on_map, BS);
1673                 v3f from_pos_f_on_block = from_pos_f_on_map - block_pos_f_on_map;
1674
1675                 block->getObjects(from_pos_f_on_block, max_d, objects);
1676                 //block->getPseudoObjects(from_pos_f_on_block, max_d, objects);
1677         }
1678
1679         //dstream<<"Collected "<<objects.size()<<" nearby objects"<<std::endl;
1680         
1681         // Sort them.
1682         // After this, the closest object is the first in the array.
1683         objects.sort();
1684
1685         for(u32 i=0; i<objects.size(); i++)
1686         {
1687                 MapBlockObject *obj = objects[i].obj;
1688                 MapBlock *block = obj->getBlock();
1689
1690                 // Calculate shootline relative to block
1691                 v3s16 block_pos_i_on_map = block->getPosRelative();
1692                 v3f block_pos_f_on_map = intToFloat(block_pos_i_on_map, BS);
1693                 core::line3d<f32> shootline_on_block(
1694                                 shootline_on_map.start - block_pos_f_on_map,
1695                                 shootline_on_map.end - block_pos_f_on_map
1696                 );
1697
1698                 if(obj->isSelected(shootline_on_block))
1699                 {
1700                         //dstream<<"Returning selected object"<<std::endl;
1701                         return obj;
1702                 }
1703         }
1704
1705         //dstream<<"No object selected; returning NULL."<<std::endl;
1706         return NULL;
1707 }
1708
1709 void Client::printDebugInfo(std::ostream &os)
1710 {
1711         //JMutexAutoLock lock1(m_fetchblock_mutex);
1712         JMutexAutoLock lock2(m_incoming_queue_mutex);
1713
1714         os<<"m_incoming_queue.getSize()="<<m_incoming_queue.getSize()
1715                 //<<", m_fetchblock_history.size()="<<m_fetchblock_history.size()
1716                 //<<", m_opt_not_found_history.size()="<<m_opt_not_found_history.size()
1717                 <<std::endl;
1718 }
1719         
1720 /*s32 Client::getDayNightIndex()
1721 {
1722         assert(m_daynight_i >= 0 && m_daynight_i < DAYNIGHT_CACHE_COUNT);
1723         return m_daynight_i;
1724 }*/
1725
1726 u32 Client::getDayNightRatio()
1727 {
1728         JMutexAutoLock envlock(m_env_mutex);
1729         return m_env.getDayNightRatio();
1730 }
1731
1732 /*void Client::updateSomeExpiredMeshes()
1733 {
1734         TimeTaker timer("updateSomeExpiredMeshes()", g_device);
1735         
1736         Player *player;
1737         {
1738                 JMutexAutoLock envlock(m_env_mutex);
1739                 player = m_env.getLocalPlayer();
1740         }
1741
1742         u32 daynight_ratio = getDayNightRatio();
1743
1744         v3f playerpos = player->getPosition();
1745         v3f playerspeed = player->getSpeed();
1746
1747         v3s16 center_nodepos = floatToInt(playerpos, BS);
1748         v3s16 center = getNodeBlockPos(center_nodepos);
1749
1750         u32 counter = 0;
1751
1752         s16 d_max = 5;
1753         
1754         for(s16 d = 0; d <= d_max; d++)
1755         {
1756                 core::list<v3s16> list;
1757                 getFacePositions(list, d);
1758                 
1759                 core::list<v3s16>::Iterator li;
1760                 for(li=list.begin(); li!=list.end(); li++)
1761                 {
1762                         v3s16 p = *li + center;
1763                         MapBlock *block = NULL;
1764                         try
1765                         {
1766                                 //JMutexAutoLock envlock(m_env_mutex);
1767                                 block = m_env.getMap().getBlockNoCreate(p);
1768                         }
1769                         catch(InvalidPositionException &e)
1770                         {
1771                         }
1772
1773                         if(block == NULL)
1774                                 continue;
1775
1776                         if(block->getMeshExpired() == false)
1777                                 continue;
1778
1779                         block->updateMesh(daynight_ratio);
1780
1781                         counter++;
1782                         if(counter >= 5)
1783                                 return;
1784                 }
1785         }
1786 }*/
1787