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