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