Make early protocol auth mechanism generic, and add SRP
[oweals/minetest.git] / src / client.cpp
1 /*
2 Minetest
3 Copyright (C) 2013 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 Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser 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 <iostream>
21 #include <algorithm>
22 #include <sstream>
23 #include <IFileSystem.h>
24 #include "jthread/jmutexautolock.h"
25 #include "util/auth.h"
26 #include "util/directiontables.h"
27 #include "util/pointedthing.h"
28 #include "util/serialize.h"
29 #include "util/string.h"
30 #include "util/srp.h"
31 #include "client.h"
32 #include "network/clientopcodes.h"
33 #include "filesys.h"
34 #include "porting.h"
35 #include "mapblock_mesh.h"
36 #include "mapblock.h"
37 #include "settings.h"
38 #include "profiler.h"
39 #include "gettext.h"
40 #include "log.h"
41 #include "nodemetadata.h"
42 #include "itemdef.h"
43 #include "shader.h"
44 #include "clientmap.h"
45 #include "clientmedia.h"
46 #include "sound.h"
47 #include "IMeshCache.h"
48 #include "config.h"
49 #include "version.h"
50 #include "drawscene.h"
51 #include "database-sqlite3.h"
52 #include "serialization.h"
53 #include "guiscalingfilter.h"
54
55 extern gui::IGUIEnvironment* guienv;
56
57 /*
58         QueuedMeshUpdate
59 */
60
61 QueuedMeshUpdate::QueuedMeshUpdate():
62         p(-1337,-1337,-1337),
63         data(NULL),
64         ack_block_to_server(false)
65 {
66 }
67
68 QueuedMeshUpdate::~QueuedMeshUpdate()
69 {
70         if(data)
71                 delete data;
72 }
73
74 /*
75         MeshUpdateQueue
76 */
77
78 MeshUpdateQueue::MeshUpdateQueue()
79 {
80 }
81
82 MeshUpdateQueue::~MeshUpdateQueue()
83 {
84         JMutexAutoLock lock(m_mutex);
85
86         for(std::vector<QueuedMeshUpdate*>::iterator
87                         i = m_queue.begin();
88                         i != m_queue.end(); i++)
89         {
90                 QueuedMeshUpdate *q = *i;
91                 delete q;
92         }
93 }
94
95 /*
96         peer_id=0 adds with nobody to send to
97 */
98 void MeshUpdateQueue::addBlock(v3s16 p, MeshMakeData *data, bool ack_block_to_server, bool urgent)
99 {
100         DSTACK(__FUNCTION_NAME);
101
102         assert(data);   // pre-condition
103
104         JMutexAutoLock lock(m_mutex);
105
106         if(urgent)
107                 m_urgents.insert(p);
108
109         /*
110                 Find if block is already in queue.
111                 If it is, update the data and quit.
112         */
113         for(std::vector<QueuedMeshUpdate*>::iterator
114                         i = m_queue.begin();
115                         i != m_queue.end(); i++)
116         {
117                 QueuedMeshUpdate *q = *i;
118                 if(q->p == p)
119                 {
120                         if(q->data)
121                                 delete q->data;
122                         q->data = data;
123                         if(ack_block_to_server)
124                                 q->ack_block_to_server = true;
125                         return;
126                 }
127         }
128
129         /*
130                 Add the block
131         */
132         QueuedMeshUpdate *q = new QueuedMeshUpdate;
133         q->p = p;
134         q->data = data;
135         q->ack_block_to_server = ack_block_to_server;
136         m_queue.push_back(q);
137 }
138
139 // Returned pointer must be deleted
140 // Returns NULL if queue is empty
141 QueuedMeshUpdate * MeshUpdateQueue::pop()
142 {
143         JMutexAutoLock lock(m_mutex);
144
145         bool must_be_urgent = !m_urgents.empty();
146         for(std::vector<QueuedMeshUpdate*>::iterator
147                         i = m_queue.begin();
148                         i != m_queue.end(); i++)
149         {
150                 QueuedMeshUpdate *q = *i;
151                 if(must_be_urgent && m_urgents.count(q->p) == 0)
152                         continue;
153                 m_queue.erase(i);
154                 m_urgents.erase(q->p);
155                 return q;
156         }
157         return NULL;
158 }
159
160 /*
161         MeshUpdateThread
162 */
163
164 void * MeshUpdateThread::Thread()
165 {
166         ThreadStarted();
167
168         log_register_thread("MeshUpdateThread");
169
170         DSTACK(__FUNCTION_NAME);
171
172         BEGIN_DEBUG_EXCEPTION_HANDLER
173
174         porting::setThreadName("MeshUpdateThread");
175
176         while(!StopRequested())
177         {
178                 QueuedMeshUpdate *q = m_queue_in.pop();
179                 if(q == NULL)
180                 {
181                         sleep_ms(3);
182                         continue;
183                 }
184
185                 ScopeProfiler sp(g_profiler, "Client: Mesh making");
186
187                 MapBlockMesh *mesh_new = new MapBlockMesh(q->data, m_camera_offset);
188                 if(mesh_new->getMesh()->getMeshBufferCount() == 0)
189                 {
190                         delete mesh_new;
191                         mesh_new = NULL;
192                 }
193
194                 MeshUpdateResult r;
195                 r.p = q->p;
196                 r.mesh = mesh_new;
197                 r.ack_block_to_server = q->ack_block_to_server;
198
199                 m_queue_out.push_back(r);
200
201                 delete q;
202         }
203
204         END_DEBUG_EXCEPTION_HANDLER(errorstream)
205
206         return NULL;
207 }
208
209 /*
210         Client
211 */
212
213 Client::Client(
214                 IrrlichtDevice *device,
215                 const char *playername,
216                 std::string password,
217                 MapDrawControl &control,
218                 IWritableTextureSource *tsrc,
219                 IWritableShaderSource *shsrc,
220                 IWritableItemDefManager *itemdef,
221                 IWritableNodeDefManager *nodedef,
222                 ISoundManager *sound,
223                 MtEventManager *event,
224                 bool ipv6
225 ):
226         m_packetcounter_timer(0.0),
227         m_connection_reinit_timer(0.1),
228         m_avg_rtt_timer(0.0),
229         m_playerpos_send_timer(0.0),
230         m_ignore_damage_timer(0.0),
231         m_tsrc(tsrc),
232         m_shsrc(shsrc),
233         m_itemdef(itemdef),
234         m_nodedef(nodedef),
235         m_sound(sound),
236         m_event(event),
237         m_mesh_update_thread(this),
238         m_env(
239                 new ClientMap(this, this, control,
240                         device->getSceneManager()->getRootSceneNode(),
241                         device->getSceneManager(), 666),
242                 device->getSceneManager(),
243                 tsrc, this, device
244         ),
245         m_particle_manager(&m_env),
246         m_con(PROTOCOL_ID, 512, CONNECTION_TIMEOUT, ipv6, this),
247         m_device(device),
248         m_server_ser_ver(SER_FMT_VER_INVALID),
249         m_playeritem(0),
250         m_inventory_updated(false),
251         m_inventory_from_server(NULL),
252         m_inventory_from_server_age(0.0),
253         m_show_highlighted(false),
254         m_animation_time(0),
255         m_crack_level(-1),
256         m_crack_pos(0,0,0),
257         m_highlighted_pos(0,0,0),
258         m_map_seed(0),
259         m_password(password),
260         m_chosen_auth_mech(AUTH_MECHANISM_NONE),
261         m_auth_data(NULL),
262         m_access_denied(false),
263         m_itemdef_received(false),
264         m_nodedef_received(false),
265         m_media_downloader(new ClientMediaDownloader()),
266         m_time_of_day_set(false),
267         m_last_time_of_day_f(-1),
268         m_time_of_day_update_timer(0),
269         m_recommended_send_interval(0.1),
270         m_removed_sounds_check_timer(0),
271         m_state(LC_Created),
272         m_localdb(NULL)
273 {
274         // Add local player
275         m_env.addPlayer(new LocalPlayer(this, playername));
276
277         m_cache_save_interval = g_settings->getU16("server_map_save_interval");
278
279         m_cache_smooth_lighting = g_settings->getBool("smooth_lighting");
280         m_cache_enable_shaders  = g_settings->getBool("enable_shaders");
281 }
282
283 void Client::Stop()
284 {
285         //request all client managed threads to stop
286         m_mesh_update_thread.Stop();
287         // Save local server map
288         if (m_localdb) {
289                 infostream << "Local map saving ended." << std::endl;
290                 m_localdb->endSave();
291         }
292 }
293
294 bool Client::isShutdown()
295 {
296
297         if (!m_mesh_update_thread.IsRunning()) return true;
298
299         return false;
300 }
301
302 Client::~Client()
303 {
304         m_con.Disconnect();
305
306         m_mesh_update_thread.Stop();
307         m_mesh_update_thread.Wait();
308         while(!m_mesh_update_thread.m_queue_out.empty()) {
309                 MeshUpdateResult r = m_mesh_update_thread.m_queue_out.pop_frontNoEx();
310                 delete r.mesh;
311         }
312
313
314         delete m_inventory_from_server;
315
316         // Delete detached inventories
317         for(std::map<std::string, Inventory*>::iterator
318                         i = m_detached_inventories.begin();
319                         i != m_detached_inventories.end(); i++){
320                 delete i->second;
321         }
322
323         // cleanup 3d model meshes on client shutdown
324         while (m_device->getSceneManager()->getMeshCache()->getMeshCount() != 0) {
325                 scene::IAnimatedMesh * mesh =
326                         m_device->getSceneManager()->getMeshCache()->getMeshByIndex(0);
327
328                 if (mesh != NULL)
329                         m_device->getSceneManager()->getMeshCache()->removeMesh(mesh);
330         }
331 }
332
333 void Client::connect(Address address,
334                 const std::string &address_name,
335                 bool is_local_server)
336 {
337         DSTACK(__FUNCTION_NAME);
338
339         initLocalMapSaving(address, address_name, is_local_server);
340
341         m_con.SetTimeoutMs(0);
342         m_con.Connect(address);
343 }
344
345 void Client::step(float dtime)
346 {
347         DSTACK(__FUNCTION_NAME);
348
349         // Limit a bit
350         if(dtime > 2.0)
351                 dtime = 2.0;
352
353         if(m_ignore_damage_timer > dtime)
354                 m_ignore_damage_timer -= dtime;
355         else
356                 m_ignore_damage_timer = 0.0;
357
358         m_animation_time += dtime;
359         if(m_animation_time > 60.0)
360                 m_animation_time -= 60.0;
361
362         m_time_of_day_update_timer += dtime;
363
364         ReceiveAll();
365
366         /*
367                 Packet counter
368         */
369         {
370                 float &counter = m_packetcounter_timer;
371                 counter -= dtime;
372                 if(counter <= 0.0)
373                 {
374                         counter = 20.0;
375
376                         infostream << "Client packetcounter (" << m_packetcounter_timer
377                                         << "):"<<std::endl;
378                         m_packetcounter.print(infostream);
379                         m_packetcounter.clear();
380                 }
381         }
382
383         // UGLY hack to fix 2 second startup delay caused by non existent
384         // server client startup synchronization in local server or singleplayer mode
385         static bool initial_step = true;
386         if (initial_step) {
387                 initial_step = false;
388         }
389         else if(m_state == LC_Created) {
390                 float &counter = m_connection_reinit_timer;
391                 counter -= dtime;
392                 if(counter <= 0.0) {
393                         counter = 2.0;
394
395                         Player *myplayer = m_env.getLocalPlayer();
396                         FATAL_ERROR_IF(myplayer == NULL, "Local player not found in environment.");
397
398                         // Send TOSERVER_INIT_LEGACY
399                         // [0] u16 TOSERVER_INIT_LEGACY
400                         // [2] u8 SER_FMT_VER_HIGHEST_READ
401                         // [3] u8[20] player_name
402                         // [23] u8[28] password (new in some version)
403                         // [51] u16 minimum supported network protocol version (added sometime)
404                         // [53] u16 maximum supported network protocol version (added later than the previous one)
405
406                         char pName[PLAYERNAME_SIZE];
407                         char pPassword[PASSWORD_SIZE];
408                         memset(pName, 0, PLAYERNAME_SIZE * sizeof(char));
409                         memset(pPassword, 0, PASSWORD_SIZE * sizeof(char));
410
411                         std::string hashed_password = translatePassword(myplayer->getName(), m_password);
412                         snprintf(pName, PLAYERNAME_SIZE, "%s", myplayer->getName());
413                         snprintf(pPassword, PASSWORD_SIZE, "%s", hashed_password.c_str());
414
415                         sendLegacyInit(pName, pPassword);
416                         if (LATEST_PROTOCOL_VERSION >= 25)
417                                 sendInit(myplayer->getName());
418                 }
419
420                 // Not connected, return
421                 return;
422         }
423
424         /*
425                 Do stuff if connected
426         */
427
428         /*
429                 Run Map's timers and unload unused data
430         */
431         const float map_timer_and_unload_dtime = 5.25;
432         if(m_map_timer_and_unload_interval.step(dtime, map_timer_and_unload_dtime)) {
433                 ScopeProfiler sp(g_profiler, "Client: map timer and unload");
434                 std::vector<v3s16> deleted_blocks;
435                 m_env.getMap().timerUpdate(map_timer_and_unload_dtime,
436                                 g_settings->getFloat("client_unload_unused_data_timeout"),
437                                 &deleted_blocks);
438
439                 /*
440                         Send info to server
441                         NOTE: This loop is intentionally iterated the way it is.
442                 */
443
444                 std::vector<v3s16>::iterator i = deleted_blocks.begin();
445                 std::vector<v3s16> sendlist;
446                 for(;;) {
447                         if(sendlist.size() == 255 || i == deleted_blocks.end()) {
448                                 if(sendlist.empty())
449                                         break;
450                                 /*
451                                         [0] u16 command
452                                         [2] u8 count
453                                         [3] v3s16 pos_0
454                                         [3+6] v3s16 pos_1
455                                         ...
456                                 */
457
458                                 sendDeletedBlocks(sendlist);
459
460                                 if(i == deleted_blocks.end())
461                                         break;
462
463                                 sendlist.clear();
464                         }
465
466                         sendlist.push_back(*i);
467                         ++i;
468                 }
469         }
470
471         /*
472                 Handle environment
473         */
474         // Control local player (0ms)
475         LocalPlayer *player = m_env.getLocalPlayer();
476         assert(player != NULL);
477         player->applyControl(dtime);
478
479         // Step environment
480         m_env.step(dtime);
481
482         /*
483                 Get events
484         */
485         for(;;) {
486                 ClientEnvEvent event = m_env.getClientEvent();
487                 if(event.type == CEE_NONE) {
488                         break;
489                 }
490                 else if(event.type == CEE_PLAYER_DAMAGE) {
491                         if(m_ignore_damage_timer <= 0) {
492                                 u8 damage = event.player_damage.amount;
493
494                                 if(event.player_damage.send_to_server)
495                                         sendDamage(damage);
496
497                                 // Add to ClientEvent queue
498                                 ClientEvent event;
499                                 event.type = CE_PLAYER_DAMAGE;
500                                 event.player_damage.amount = damage;
501                                 m_client_event_queue.push(event);
502                         }
503                 }
504                 else if(event.type == CEE_PLAYER_BREATH) {
505                                 u16 breath = event.player_breath.amount;
506                                 sendBreath(breath);
507                 }
508         }
509
510         /*
511                 Print some info
512         */
513         float &counter = m_avg_rtt_timer;
514         counter += dtime;
515         if(counter >= 10) {
516                 counter = 0.0;
517                 // connectedAndInitialized() is true, peer exists.
518                 float avg_rtt = getRTT();
519                 infostream << "Client: avg_rtt=" << avg_rtt << std::endl;
520         }
521
522         /*
523                 Send player position to server
524         */
525         {
526                 float &counter = m_playerpos_send_timer;
527                 counter += dtime;
528                 if((m_state == LC_Ready) && (counter >= m_recommended_send_interval))
529                 {
530                         counter = 0.0;
531                         sendPlayerPos();
532                 }
533         }
534
535         /*
536                 Replace updated meshes
537         */
538         {
539                 int num_processed_meshes = 0;
540                 while(!m_mesh_update_thread.m_queue_out.empty())
541                 {
542                         num_processed_meshes++;
543                         MeshUpdateResult r = m_mesh_update_thread.m_queue_out.pop_frontNoEx();
544                         MapBlock *block = m_env.getMap().getBlockNoCreateNoEx(r.p);
545                         if(block) {
546                                 // Delete the old mesh
547                                 if(block->mesh != NULL)
548                                 {
549                                         // TODO: Remove hardware buffers of meshbuffers of block->mesh
550                                         delete block->mesh;
551                                         block->mesh = NULL;
552                                 }
553
554                                 // Replace with the new mesh
555                                 block->mesh = r.mesh;
556                         } else {
557                                 delete r.mesh;
558                         }
559
560                         if(r.ack_block_to_server) {
561                                 /*
562                                         Acknowledge block
563                                         [0] u8 count
564                                         [1] v3s16 pos_0
565                                 */
566                                 sendGotBlocks(r.p);
567                         }
568                 }
569
570                 if(num_processed_meshes > 0)
571                         g_profiler->graphAdd("num_processed_meshes", num_processed_meshes);
572         }
573
574         /*
575                 Load fetched media
576         */
577         if (m_media_downloader && m_media_downloader->isStarted()) {
578                 m_media_downloader->step(this);
579                 if (m_media_downloader->isDone()) {
580                         received_media();
581                         delete m_media_downloader;
582                         m_media_downloader = NULL;
583                 }
584         }
585
586         /*
587                 If the server didn't update the inventory in a while, revert
588                 the local inventory (so the player notices the lag problem
589                 and knows something is wrong).
590         */
591         if(m_inventory_from_server)
592         {
593                 float interval = 10.0;
594                 float count_before = floor(m_inventory_from_server_age / interval);
595
596                 m_inventory_from_server_age += dtime;
597
598                 float count_after = floor(m_inventory_from_server_age / interval);
599
600                 if(count_after != count_before)
601                 {
602                         // Do this every <interval> seconds after TOCLIENT_INVENTORY
603                         // Reset the locally changed inventory to the authoritative inventory
604                         Player *player = m_env.getLocalPlayer();
605                         player->inventory = *m_inventory_from_server;
606                         m_inventory_updated = true;
607                 }
608         }
609
610         /*
611                 Update positions of sounds attached to objects
612         */
613         {
614                 for(std::map<int, u16>::iterator
615                                 i = m_sounds_to_objects.begin();
616                                 i != m_sounds_to_objects.end(); i++)
617                 {
618                         int client_id = i->first;
619                         u16 object_id = i->second;
620                         ClientActiveObject *cao = m_env.getActiveObject(object_id);
621                         if(!cao)
622                                 continue;
623                         v3f pos = cao->getPosition();
624                         m_sound->updateSoundPosition(client_id, pos);
625                 }
626         }
627
628         /*
629                 Handle removed remotely initiated sounds
630         */
631         m_removed_sounds_check_timer += dtime;
632         if(m_removed_sounds_check_timer >= 2.32) {
633                 m_removed_sounds_check_timer = 0;
634                 // Find removed sounds and clear references to them
635                 std::vector<s32> removed_server_ids;
636                 for(std::map<s32, int>::iterator
637                                 i = m_sounds_server_to_client.begin();
638                                 i != m_sounds_server_to_client.end();) {
639                         s32 server_id = i->first;
640                         int client_id = i->second;
641                         i++;
642                         if(!m_sound->soundExists(client_id)) {
643                                 m_sounds_server_to_client.erase(server_id);
644                                 m_sounds_client_to_server.erase(client_id);
645                                 m_sounds_to_objects.erase(client_id);
646                                 removed_server_ids.push_back(server_id);
647                         }
648                 }
649
650                 // Sync to server
651                 if(!removed_server_ids.empty()) {
652                         sendRemovedSounds(removed_server_ids);
653                 }
654         }
655
656         // Write server map
657         if (m_localdb && m_localdb_save_interval.step(dtime,
658                         m_cache_save_interval)) {
659                 m_localdb->endSave();
660                 m_localdb->beginSave();
661         }
662 }
663
664 bool Client::loadMedia(const std::string &data, const std::string &filename)
665 {
666         // Silly irrlicht's const-incorrectness
667         Buffer<char> data_rw(data.c_str(), data.size());
668
669         std::string name;
670
671         const char *image_ext[] = {
672                 ".png", ".jpg", ".bmp", ".tga",
673                 ".pcx", ".ppm", ".psd", ".wal", ".rgb",
674                 NULL
675         };
676         name = removeStringEnd(filename, image_ext);
677         if(name != "")
678         {
679                 verbosestream<<"Client: Attempting to load image "
680                 <<"file \""<<filename<<"\""<<std::endl;
681
682                 io::IFileSystem *irrfs = m_device->getFileSystem();
683                 video::IVideoDriver *vdrv = m_device->getVideoDriver();
684
685                 // Create an irrlicht memory file
686                 io::IReadFile *rfile = irrfs->createMemoryReadFile(
687                                 *data_rw, data_rw.getSize(), "_tempreadfile");
688
689                 FATAL_ERROR_IF(!rfile, "Could not create irrlicht memory file.");
690
691                 // Read image
692                 video::IImage *img = vdrv->createImageFromFile(rfile);
693                 if(!img){
694                         errorstream<<"Client: Cannot create image from data of "
695                                         <<"file \""<<filename<<"\""<<std::endl;
696                         rfile->drop();
697                         return false;
698                 }
699                 else {
700                         m_tsrc->insertSourceImage(filename, img);
701                         img->drop();
702                         rfile->drop();
703                         return true;
704                 }
705         }
706
707         const char *sound_ext[] = {
708                 ".0.ogg", ".1.ogg", ".2.ogg", ".3.ogg", ".4.ogg",
709                 ".5.ogg", ".6.ogg", ".7.ogg", ".8.ogg", ".9.ogg",
710                 ".ogg", NULL
711         };
712         name = removeStringEnd(filename, sound_ext);
713         if(name != "")
714         {
715                 verbosestream<<"Client: Attempting to load sound "
716                 <<"file \""<<filename<<"\""<<std::endl;
717                 m_sound->loadSoundData(name, data);
718                 return true;
719         }
720
721         const char *model_ext[] = {
722                 ".x", ".b3d", ".md2", ".obj",
723                 NULL
724         };
725         name = removeStringEnd(filename, model_ext);
726         if(name != "")
727         {
728                 verbosestream<<"Client: Storing model into memory: "
729                                 <<"\""<<filename<<"\""<<std::endl;
730                 if(m_mesh_data.count(filename))
731                         errorstream<<"Multiple models with name \""<<filename.c_str()
732                                         <<"\" found; replacing previous model"<<std::endl;
733                 m_mesh_data[filename] = data;
734                 return true;
735         }
736
737         errorstream<<"Client: Don't know how to load file \""
738                         <<filename<<"\""<<std::endl;
739         return false;
740 }
741
742 // Virtual methods from con::PeerHandler
743 void Client::peerAdded(con::Peer *peer)
744 {
745         infostream<<"Client::peerAdded(): peer->id="
746                         <<peer->id<<std::endl;
747 }
748 void Client::deletingPeer(con::Peer *peer, bool timeout)
749 {
750         infostream<<"Client::deletingPeer(): "
751                         "Server Peer is getting deleted "
752                         <<"(timeout="<<timeout<<")"<<std::endl;
753 }
754
755 /*
756         u16 command
757         u16 number of files requested
758         for each file {
759                 u16 length of name
760                 string name
761         }
762 */
763 void Client::request_media(const std::vector<std::string> &file_requests)
764 {
765         std::ostringstream os(std::ios_base::binary);
766         writeU16(os, TOSERVER_REQUEST_MEDIA);
767         size_t file_requests_size = file_requests.size();
768
769         FATAL_ERROR_IF(file_requests_size > 0xFFFF, "Unsupported number of file requests");
770
771         // Packet dynamicly resized
772         NetworkPacket pkt(TOSERVER_REQUEST_MEDIA, 2 + 0);
773
774         pkt << (u16) (file_requests_size & 0xFFFF);
775
776         for(std::vector<std::string>::const_iterator i = file_requests.begin();
777                         i != file_requests.end(); ++i) {
778                 pkt << (*i);
779         }
780
781         Send(&pkt);
782
783         infostream << "Client: Sending media request list to server ("
784                         << file_requests.size() << " files. packet size)" << std::endl;
785 }
786
787 void Client::received_media()
788 {
789         NetworkPacket pkt(TOSERVER_RECEIVED_MEDIA, 0);
790         Send(&pkt);
791         infostream << "Client: Notifying server that we received all media"
792                         << std::endl;
793 }
794
795 void Client::initLocalMapSaving(const Address &address,
796                 const std::string &hostname,
797                 bool is_local_server)
798 {
799         if (!g_settings->getBool("enable_local_map_saving") || is_local_server) {
800                 return;
801         }
802
803         const std::string world_path = porting::path_user
804                 + DIR_DELIM + "worlds"
805                 + DIR_DELIM + "server_"
806                 + hostname + "_" + to_string(address.getPort());
807
808         fs::CreateAllDirs(world_path);
809
810         m_localdb = new Database_SQLite3(world_path);
811         m_localdb->beginSave();
812         actionstream << "Local map saving started, map will be saved at '" << world_path << "'" << std::endl;
813 }
814
815 void Client::ReceiveAll()
816 {
817         DSTACK(__FUNCTION_NAME);
818         u32 start_ms = porting::getTimeMs();
819         for(;;)
820         {
821                 // Limit time even if there would be huge amounts of data to
822                 // process
823                 if(porting::getTimeMs() > start_ms + 100)
824                         break;
825
826                 try {
827                         Receive();
828                         g_profiler->graphAdd("client_received_packets", 1);
829                 }
830                 catch(con::NoIncomingDataException &e) {
831                         break;
832                 }
833                 catch(con::InvalidIncomingDataException &e) {
834                         infostream<<"Client::ReceiveAll(): "
835                                         "InvalidIncomingDataException: what()="
836                                         <<e.what()<<std::endl;
837                 }
838         }
839 }
840
841 void Client::Receive()
842 {
843         DSTACK(__FUNCTION_NAME);
844         NetworkPacket pkt;
845         m_con.Receive(&pkt);
846         ProcessData(&pkt);
847 }
848
849 inline void Client::handleCommand(NetworkPacket* pkt)
850 {
851         const ToClientCommandHandler& opHandle = toClientCommandTable[pkt->getCommand()];
852         (this->*opHandle.handler)(pkt);
853 }
854
855 /*
856         sender_peer_id given to this shall be quaranteed to be a valid peer
857 */
858 void Client::ProcessData(NetworkPacket *pkt)
859 {
860         DSTACK(__FUNCTION_NAME);
861
862         ToClientCommand command = (ToClientCommand) pkt->getCommand();
863         u32 sender_peer_id = pkt->getPeerId();
864
865         //infostream<<"Client: received command="<<command<<std::endl;
866         m_packetcounter.add((u16)command);
867
868         /*
869                 If this check is removed, be sure to change the queue
870                 system to know the ids
871         */
872         if(sender_peer_id != PEER_ID_SERVER) {
873                 infostream << "Client::ProcessData(): Discarding data not "
874                         "coming from server: peer_id=" << sender_peer_id
875                         << std::endl;
876                 return;
877         }
878
879         // Command must be handled into ToClientCommandHandler
880         if (command >= TOCLIENT_NUM_MSG_TYPES) {
881                 infostream << "Client: Ignoring unknown command "
882                         << command << std::endl;
883         }
884
885         /*
886          * Those packets are handled before m_server_ser_ver is set, it's normal
887          * But we must use the new ToClientConnectionState in the future,
888          * as a byte mask
889          */
890         if(toClientCommandTable[command].state == TOCLIENT_STATE_NOT_CONNECTED) {
891                 handleCommand(pkt);
892                 return;
893         }
894
895         if(m_server_ser_ver == SER_FMT_VER_INVALID) {
896                 infostream << "Client: Server serialization"
897                                 " format invalid or not initialized."
898                                 " Skipping incoming command=" << command << std::endl;
899                 return;
900         }
901
902         /*
903           Handle runtime commands
904         */
905
906         handleCommand(pkt);
907 }
908
909 void Client::Send(NetworkPacket* pkt)
910 {
911         m_con.Send(PEER_ID_SERVER,
912                 serverCommandFactoryTable[pkt->getCommand()].channel,
913                 pkt,
914                 serverCommandFactoryTable[pkt->getCommand()].reliable);
915 }
916
917 void Client::interact(u8 action, const PointedThing& pointed)
918 {
919         if(m_state != LC_Ready) {
920                 errorstream << "Client::interact() "
921                                 "Canceled (not connected)"
922                                 << std::endl;
923                 return;
924         }
925
926         /*
927                 [0] u16 command
928                 [2] u8 action
929                 [3] u16 item
930                 [5] u32 length of the next item
931                 [9] serialized PointedThing
932                 actions:
933                 0: start digging (from undersurface) or use
934                 1: stop digging (all parameters ignored)
935                 2: digging completed
936                 3: place block or item (to abovesurface)
937                 4: use item
938         */
939
940         NetworkPacket pkt(TOSERVER_INTERACT, 1 + 2 + 0);
941
942         pkt << action;
943         pkt << (u16)getPlayerItem();
944
945         std::ostringstream tmp_os(std::ios::binary);
946         pointed.serialize(tmp_os);
947
948         pkt.putLongString(tmp_os.str());
949
950         Send(&pkt);
951 }
952
953 void Client::deleteAuthData()
954 {
955         if (!m_auth_data)
956                 return;
957
958         switch (m_chosen_auth_mech) {
959                 case AUTH_MECHANISM_FIRST_SRP:
960                         break;
961                 case AUTH_MECHANISM_SRP:
962                 case AUTH_MECHANISM_LEGACY_PASSWORD:
963                         srp_user_delete((SRPUser *) m_auth_data);
964                         m_auth_data = NULL;
965                         break;
966                 case AUTH_MECHANISM_NONE:
967                         break;
968         }
969 }
970
971
972 AuthMechanism Client::choseAuthMech(const u32 mechs)
973 {
974         if (mechs & AUTH_MECHANISM_SRP)
975                 return AUTH_MECHANISM_SRP;
976
977         if (mechs & AUTH_MECHANISM_FIRST_SRP)
978                 return AUTH_MECHANISM_FIRST_SRP;
979
980         if (mechs & AUTH_MECHANISM_LEGACY_PASSWORD)
981                 return AUTH_MECHANISM_LEGACY_PASSWORD;
982
983         return AUTH_MECHANISM_NONE;
984 }
985
986 void Client::sendLegacyInit(const char* playerName, const char* playerPassword)
987 {
988         NetworkPacket pkt(TOSERVER_INIT_LEGACY,
989                         1 + PLAYERNAME_SIZE + PASSWORD_SIZE + 2 + 2);
990
991         pkt << (u8) SER_FMT_VER_HIGHEST_READ;
992         pkt.putRawString(playerName,PLAYERNAME_SIZE);
993         pkt.putRawString(playerPassword, PASSWORD_SIZE);
994         pkt << (u16) CLIENT_PROTOCOL_VERSION_MIN << (u16) CLIENT_PROTOCOL_VERSION_MAX;
995
996         Send(&pkt);
997 }
998
999 void Client::sendInit(const std::string &playerName)
1000 {
1001         NetworkPacket pkt(TOSERVER_INIT, 1 + 2 + 2 + (1 + playerName.size()));
1002
1003         // TODO (later) actually send supported compression modes
1004         pkt << (u8) SER_FMT_VER_HIGHEST_READ << (u8) 42;
1005         pkt << (u16) CLIENT_PROTOCOL_VERSION_MIN << (u16) CLIENT_PROTOCOL_VERSION_MAX;
1006         pkt << playerName;
1007
1008         Send(&pkt);
1009 }
1010
1011 void Client::startAuth(AuthMechanism chosen_auth_mechanism)
1012 {
1013         m_chosen_auth_mech = chosen_auth_mechanism;
1014
1015         switch (chosen_auth_mechanism) {
1016                 case AUTH_MECHANISM_FIRST_SRP: {
1017                         // send srp verifier to server
1018                         NetworkPacket resp_pkt(TOSERVER_FIRST_SRP, 0);
1019                         char *salt, *bytes_v;
1020                         std::size_t len_salt, len_v;
1021                         salt = NULL;
1022                         getSRPVerifier(getPlayerName(), m_password,
1023                                 &salt, &len_salt, &bytes_v, &len_v);
1024                         resp_pkt
1025                                 << std::string((char*)salt, len_salt)
1026                                 << std::string((char*)bytes_v, len_v)
1027                                 << (u8)((m_password == "") ? 1 : 0);
1028                         free(salt);
1029                         free(bytes_v);
1030                         Send(&resp_pkt);
1031                         break;
1032                 }
1033                 case AUTH_MECHANISM_SRP:
1034                 case AUTH_MECHANISM_LEGACY_PASSWORD: {
1035                         u8 based_on = 1;
1036
1037                         if (chosen_auth_mechanism == AUTH_MECHANISM_LEGACY_PASSWORD) {
1038                                 m_password = translatePassword(getPlayerName(), m_password);
1039                                 based_on = 0;
1040                         }
1041
1042                         std::string playername_u = lowercase(getPlayerName());
1043                         m_auth_data = srp_user_new(SRP_SHA256, SRP_NG_2048,
1044                                 getPlayerName().c_str(), playername_u.c_str(),
1045                                 (const unsigned char *) m_password.c_str(),
1046                                 m_password.length(), NULL, NULL);
1047                         char *bytes_A = 0;
1048                         size_t len_A = 0;
1049                         srp_user_start_authentication((struct SRPUser *) m_auth_data,
1050                                 NULL, NULL, 0, (unsigned char **) &bytes_A, &len_A);
1051
1052                         NetworkPacket resp_pkt(TOSERVER_SRP_BYTES_A, 0);
1053                         resp_pkt << std::string(bytes_A, len_A) << based_on;
1054                         free(bytes_A);
1055                         Send(&resp_pkt);
1056                         break;
1057                 }
1058                 case AUTH_MECHANISM_NONE:
1059                         break; // not handled in this method
1060         }
1061 }
1062
1063 void Client::sendDeletedBlocks(std::vector<v3s16> &blocks)
1064 {
1065         NetworkPacket pkt(TOSERVER_DELETEDBLOCKS, 1 + sizeof(v3s16) * blocks.size());
1066
1067         pkt << (u8) blocks.size();
1068
1069         u32 k = 0;
1070         for(std::vector<v3s16>::iterator
1071                         j = blocks.begin();
1072                         j != blocks.end(); ++j) {
1073                 pkt << *j;
1074                 k++;
1075         }
1076
1077         Send(&pkt);
1078 }
1079
1080 void Client::sendGotBlocks(v3s16 block)
1081 {
1082         NetworkPacket pkt(TOSERVER_GOTBLOCKS, 1 + 6);
1083         pkt << (u8) 1 << block;
1084         Send(&pkt);
1085 }
1086
1087 void Client::sendRemovedSounds(std::vector<s32> &soundList)
1088 {
1089         size_t server_ids = soundList.size();
1090         assert(server_ids <= 0xFFFF);
1091
1092         NetworkPacket pkt(TOSERVER_REMOVED_SOUNDS, 2 + server_ids * 4);
1093
1094         pkt << (u16) (server_ids & 0xFFFF);
1095
1096         for(std::vector<s32>::iterator i = soundList.begin();
1097                         i != soundList.end(); i++)
1098                 pkt << *i;
1099
1100         Send(&pkt);
1101 }
1102
1103 void Client::sendNodemetaFields(v3s16 p, const std::string &formname,
1104                 const std::map<std::string, std::string> &fields)
1105 {
1106         size_t fields_size = fields.size();
1107
1108         FATAL_ERROR_IF(fields_size > 0xFFFF, "Unsupported number of nodemeta fields");
1109
1110         NetworkPacket pkt(TOSERVER_NODEMETA_FIELDS, 0);
1111
1112         pkt << p << formname << (u16) (fields_size & 0xFFFF);
1113
1114         for(std::map<std::string, std::string>::const_iterator
1115                         i = fields.begin(); i != fields.end(); i++) {
1116                 const std::string &name = i->first;
1117                 const std::string &value = i->second;
1118                 pkt << name;
1119                 pkt.putLongString(value);
1120         }
1121
1122         Send(&pkt);
1123 }
1124
1125 void Client::sendInventoryFields(const std::string &formname,
1126                 const std::map<std::string, std::string> &fields)
1127 {
1128         size_t fields_size = fields.size();
1129         FATAL_ERROR_IF(fields_size > 0xFFFF, "Unsupported number of inventory fields");
1130
1131         NetworkPacket pkt(TOSERVER_INVENTORY_FIELDS, 0);
1132         pkt << formname << (u16) (fields_size & 0xFFFF);
1133
1134         for(std::map<std::string, std::string>::const_iterator
1135                         i = fields.begin(); i != fields.end(); i++) {
1136                 const std::string &name  = i->first;
1137                 const std::string &value = i->second;
1138                 pkt << name;
1139                 pkt.putLongString(value);
1140         }
1141
1142         Send(&pkt);
1143 }
1144
1145 void Client::sendInventoryAction(InventoryAction *a)
1146 {
1147         std::ostringstream os(std::ios_base::binary);
1148
1149         a->serialize(os);
1150
1151         // Make data buffer
1152         std::string s = os.str();
1153
1154         NetworkPacket pkt(TOSERVER_INVENTORY_ACTION, s.size());
1155         pkt.putRawString(s.c_str(),s.size());
1156
1157         Send(&pkt);
1158 }
1159
1160 void Client::sendChatMessage(const std::wstring &message)
1161 {
1162         NetworkPacket pkt(TOSERVER_CHAT_MESSAGE, 2 + message.size() * sizeof(u16));
1163
1164         pkt << message;
1165
1166         Send(&pkt);
1167 }
1168
1169 void Client::sendChangePassword(const std::string &oldpassword,
1170         const std::string &newpassword)
1171 {
1172         Player *player = m_env.getLocalPlayer();
1173         if (player == NULL)
1174                 return;
1175
1176         std::string playername = player->getName();
1177         if (m_proto_ver >= 25) {
1178                 // get into sudo mode and then send new password to server
1179                 m_password = oldpassword;
1180                 m_new_password = newpassword;
1181                 startAuth(choseAuthMech(m_sudo_auth_methods));
1182         } else {
1183                 std::string oldpwd = translatePassword(playername, oldpassword);
1184                 std::string newpwd = translatePassword(playername, newpassword);
1185
1186                 NetworkPacket pkt(TOSERVER_PASSWORD_LEGACY, 2 * PASSWORD_SIZE);
1187
1188                 for (u8 i = 0; i < PASSWORD_SIZE; i++) {
1189                         pkt << (u8) (i < oldpwd.length() ? oldpwd[i] : 0);
1190                 }
1191
1192                 for (u8 i = 0; i < PASSWORD_SIZE; i++) {
1193                         pkt << (u8) (i < newpwd.length() ? newpwd[i] : 0);
1194                 }
1195                 Send(&pkt);
1196         }
1197 }
1198
1199
1200 void Client::sendDamage(u8 damage)
1201 {
1202         DSTACK(__FUNCTION_NAME);
1203
1204         NetworkPacket pkt(TOSERVER_DAMAGE, sizeof(u8));
1205         pkt << damage;
1206         Send(&pkt);
1207 }
1208
1209 void Client::sendBreath(u16 breath)
1210 {
1211         DSTACK(__FUNCTION_NAME);
1212
1213         NetworkPacket pkt(TOSERVER_BREATH, sizeof(u16));
1214         pkt << breath;
1215         Send(&pkt);
1216 }
1217
1218 void Client::sendRespawn()
1219 {
1220         DSTACK(__FUNCTION_NAME);
1221
1222         NetworkPacket pkt(TOSERVER_RESPAWN, 0);
1223         Send(&pkt);
1224 }
1225
1226 void Client::sendReady()
1227 {
1228         DSTACK(__FUNCTION_NAME);
1229
1230         NetworkPacket pkt(TOSERVER_CLIENT_READY,
1231                         1 + 1 + 1 + 1 + 2 + sizeof(char) * strlen(g_version_hash));
1232
1233         pkt << (u8) VERSION_MAJOR << (u8) VERSION_MINOR << (u8) VERSION_PATCH
1234                 << (u8) 0 << (u16) strlen(g_version_hash);
1235
1236         pkt.putRawString(g_version_hash, (u16) strlen(g_version_hash));
1237         Send(&pkt);
1238 }
1239
1240 void Client::sendPlayerPos()
1241 {
1242         LocalPlayer *myplayer = m_env.getLocalPlayer();
1243         if(myplayer == NULL)
1244                 return;
1245
1246         // Save bandwidth by only updating position when something changed
1247         if(myplayer->last_position        == myplayer->getPosition() &&
1248                         myplayer->last_speed      == myplayer->getSpeed()    &&
1249                         myplayer->last_pitch      == myplayer->getPitch()    &&
1250                         myplayer->last_yaw        == myplayer->getYaw()      &&
1251                         myplayer->last_keyPressed == myplayer->keyPressed)
1252                 return;
1253
1254         myplayer->last_position   = myplayer->getPosition();
1255         myplayer->last_speed      = myplayer->getSpeed();
1256         myplayer->last_pitch      = myplayer->getPitch();
1257         myplayer->last_yaw        = myplayer->getYaw();
1258         myplayer->last_keyPressed = myplayer->keyPressed;
1259
1260         u16 our_peer_id;
1261         {
1262                 //JMutexAutoLock lock(m_con_mutex); //bulk comment-out
1263                 our_peer_id = m_con.GetPeerID();
1264         }
1265
1266         // Set peer id if not set already
1267         if(myplayer->peer_id == PEER_ID_INEXISTENT)
1268                 myplayer->peer_id = our_peer_id;
1269
1270         assert(myplayer->peer_id == our_peer_id);
1271
1272         v3f pf         = myplayer->getPosition();
1273         v3f sf         = myplayer->getSpeed();
1274         s32 pitch      = myplayer->getPitch() * 100;
1275         s32 yaw        = myplayer->getYaw() * 100;
1276         u32 keyPressed = myplayer->keyPressed;
1277
1278         v3s32 position(pf.X*100, pf.Y*100, pf.Z*100);
1279         v3s32 speed(sf.X*100, sf.Y*100, sf.Z*100);
1280         /*
1281                 Format:
1282                 [0] v3s32 position*100
1283                 [12] v3s32 speed*100
1284                 [12+12] s32 pitch*100
1285                 [12+12+4] s32 yaw*100
1286                 [12+12+4+4] u32 keyPressed
1287         */
1288
1289         NetworkPacket pkt(TOSERVER_PLAYERPOS, 12 + 12 + 4 + 4 + 4);
1290
1291         pkt << position << speed << pitch << yaw << keyPressed;
1292
1293         Send(&pkt);
1294 }
1295
1296 void Client::sendPlayerItem(u16 item)
1297 {
1298         Player *myplayer = m_env.getLocalPlayer();
1299         if(myplayer == NULL)
1300                 return;
1301
1302         u16 our_peer_id = m_con.GetPeerID();
1303
1304         // Set peer id if not set already
1305         if(myplayer->peer_id == PEER_ID_INEXISTENT)
1306                 myplayer->peer_id = our_peer_id;
1307         assert(myplayer->peer_id == our_peer_id);
1308
1309         NetworkPacket pkt(TOSERVER_PLAYERITEM, 2);
1310
1311         pkt << item;
1312
1313         Send(&pkt);
1314 }
1315
1316 void Client::removeNode(v3s16 p)
1317 {
1318         std::map<v3s16, MapBlock*> modified_blocks;
1319
1320         try {
1321                 m_env.getMap().removeNodeAndUpdate(p, modified_blocks);
1322         }
1323         catch(InvalidPositionException &e) {
1324         }
1325
1326         for(std::map<v3s16, MapBlock *>::iterator
1327                         i = modified_blocks.begin();
1328                         i != modified_blocks.end(); ++i) {
1329                 addUpdateMeshTaskWithEdge(i->first, false, true);
1330         }
1331 }
1332
1333 void Client::addNode(v3s16 p, MapNode n, bool remove_metadata)
1334 {
1335         //TimeTaker timer1("Client::addNode()");
1336
1337         std::map<v3s16, MapBlock*> modified_blocks;
1338
1339         try {
1340                 //TimeTaker timer3("Client::addNode(): addNodeAndUpdate");
1341                 m_env.getMap().addNodeAndUpdate(p, n, modified_blocks, remove_metadata);
1342         }
1343         catch(InvalidPositionException &e) {
1344         }
1345
1346         for(std::map<v3s16, MapBlock *>::iterator
1347                         i = modified_blocks.begin();
1348                         i != modified_blocks.end(); ++i) {
1349                 addUpdateMeshTaskWithEdge(i->first, false, true);
1350         }
1351 }
1352
1353 void Client::setPlayerControl(PlayerControl &control)
1354 {
1355         LocalPlayer *player = m_env.getLocalPlayer();
1356         assert(player != NULL);
1357         player->control = control;
1358 }
1359
1360 void Client::selectPlayerItem(u16 item)
1361 {
1362         m_playeritem = item;
1363         m_inventory_updated = true;
1364         sendPlayerItem(item);
1365 }
1366
1367 // Returns true if the inventory of the local player has been
1368 // updated from the server. If it is true, it is set to false.
1369 bool Client::getLocalInventoryUpdated()
1370 {
1371         bool updated = m_inventory_updated;
1372         m_inventory_updated = false;
1373         return updated;
1374 }
1375
1376 // Copies the inventory of the local player to parameter
1377 void Client::getLocalInventory(Inventory &dst)
1378 {
1379         Player *player = m_env.getLocalPlayer();
1380         assert(player != NULL);
1381         dst = player->inventory;
1382 }
1383
1384 Inventory* Client::getInventory(const InventoryLocation &loc)
1385 {
1386         switch(loc.type){
1387         case InventoryLocation::UNDEFINED:
1388         {}
1389         break;
1390         case InventoryLocation::CURRENT_PLAYER:
1391         {
1392                 Player *player = m_env.getLocalPlayer();
1393                 assert(player != NULL);
1394                 return &player->inventory;
1395         }
1396         break;
1397         case InventoryLocation::PLAYER:
1398         {
1399                 Player *player = m_env.getPlayer(loc.name.c_str());
1400                 if(!player)
1401                         return NULL;
1402                 return &player->inventory;
1403         }
1404         break;
1405         case InventoryLocation::NODEMETA:
1406         {
1407                 NodeMetadata *meta = m_env.getMap().getNodeMetadata(loc.p);
1408                 if(!meta)
1409                         return NULL;
1410                 return meta->getInventory();
1411         }
1412         break;
1413         case InventoryLocation::DETACHED:
1414         {
1415                 if(m_detached_inventories.count(loc.name) == 0)
1416                         return NULL;
1417                 return m_detached_inventories[loc.name];
1418         }
1419         break;
1420         default:
1421                 FATAL_ERROR("Invalid inventory location type.");
1422                 break;
1423         }
1424         return NULL;
1425 }
1426
1427 void Client::inventoryAction(InventoryAction *a)
1428 {
1429         /*
1430                 Send it to the server
1431         */
1432         sendInventoryAction(a);
1433
1434         /*
1435                 Predict some local inventory changes
1436         */
1437         a->clientApply(this, this);
1438
1439         // Remove it
1440         delete a;
1441 }
1442
1443 ClientActiveObject * Client::getSelectedActiveObject(
1444                 f32 max_d,
1445                 v3f from_pos_f_on_map,
1446                 core::line3d<f32> shootline_on_map
1447         )
1448 {
1449         std::vector<DistanceSortedActiveObject> objects;
1450
1451         m_env.getActiveObjects(from_pos_f_on_map, max_d, objects);
1452
1453         // Sort them.
1454         // After this, the closest object is the first in the array.
1455         std::sort(objects.begin(), objects.end());
1456
1457         for(unsigned int i=0; i<objects.size(); i++)
1458         {
1459                 ClientActiveObject *obj = objects[i].obj;
1460
1461                 core::aabbox3d<f32> *selection_box = obj->getSelectionBox();
1462                 if(selection_box == NULL)
1463                         continue;
1464
1465                 v3f pos = obj->getPosition();
1466
1467                 core::aabbox3d<f32> offsetted_box(
1468                                 selection_box->MinEdge + pos,
1469                                 selection_box->MaxEdge + pos
1470                 );
1471
1472                 if(offsetted_box.intersectsWithLine(shootline_on_map))
1473                 {
1474                         return obj;
1475                 }
1476         }
1477
1478         return NULL;
1479 }
1480
1481 std::list<std::string> Client::getConnectedPlayerNames()
1482 {
1483         return m_env.getPlayerNames();
1484 }
1485
1486 float Client::getAnimationTime()
1487 {
1488         return m_animation_time;
1489 }
1490
1491 int Client::getCrackLevel()
1492 {
1493         return m_crack_level;
1494 }
1495
1496 void Client::setHighlighted(v3s16 pos, bool show_highlighted)
1497 {
1498         m_show_highlighted = show_highlighted;
1499         v3s16 old_highlighted_pos = m_highlighted_pos;
1500         m_highlighted_pos = pos;
1501         addUpdateMeshTaskForNode(old_highlighted_pos, false, true);
1502         addUpdateMeshTaskForNode(m_highlighted_pos, false, true);
1503 }
1504
1505 void Client::setCrack(int level, v3s16 pos)
1506 {
1507         int old_crack_level = m_crack_level;
1508         v3s16 old_crack_pos = m_crack_pos;
1509
1510         m_crack_level = level;
1511         m_crack_pos = pos;
1512
1513         if(old_crack_level >= 0 && (level < 0 || pos != old_crack_pos))
1514         {
1515                 // remove old crack
1516                 addUpdateMeshTaskForNode(old_crack_pos, false, true);
1517         }
1518         if(level >= 0 && (old_crack_level < 0 || pos != old_crack_pos))
1519         {
1520                 // add new crack
1521                 addUpdateMeshTaskForNode(pos, false, true);
1522         }
1523 }
1524
1525 u16 Client::getHP()
1526 {
1527         Player *player = m_env.getLocalPlayer();
1528         assert(player != NULL);
1529         return player->hp;
1530 }
1531
1532 u16 Client::getBreath()
1533 {
1534         Player *player = m_env.getLocalPlayer();
1535         assert(player != NULL);
1536         return player->getBreath();
1537 }
1538
1539 bool Client::getChatMessage(std::wstring &message)
1540 {
1541         if(m_chat_queue.size() == 0)
1542                 return false;
1543         message = m_chat_queue.front();
1544         m_chat_queue.pop();
1545         return true;
1546 }
1547
1548 void Client::typeChatMessage(const std::wstring &message)
1549 {
1550         // Discard empty line
1551         if(message == L"")
1552                 return;
1553
1554         // Send to others
1555         sendChatMessage(message);
1556
1557         // Show locally
1558         if (message[0] == L'/')
1559         {
1560                 m_chat_queue.push((std::wstring)L"issued command: " + message);
1561         }
1562         else
1563         {
1564                 LocalPlayer *player = m_env.getLocalPlayer();
1565                 assert(player != NULL);
1566                 std::wstring name = narrow_to_wide(player->getName());
1567                 m_chat_queue.push((std::wstring)L"<" + name + L"> " + message);
1568         }
1569 }
1570
1571 void Client::addUpdateMeshTask(v3s16 p, bool ack_to_server, bool urgent)
1572 {
1573         MapBlock *b = m_env.getMap().getBlockNoCreateNoEx(p);
1574         if(b == NULL)
1575                 return;
1576
1577         /*
1578                 Create a task to update the mesh of the block
1579         */
1580
1581         MeshMakeData *data = new MeshMakeData(this, m_cache_enable_shaders);
1582
1583         {
1584                 //TimeTaker timer("data fill");
1585                 // Release: ~0ms
1586                 // Debug: 1-6ms, avg=2ms
1587                 data->fill(b);
1588                 data->setCrack(m_crack_level, m_crack_pos);
1589                 data->setHighlighted(m_highlighted_pos, m_show_highlighted);
1590                 data->setSmoothLighting(m_cache_smooth_lighting);
1591         }
1592
1593         // Add task to queue
1594         m_mesh_update_thread.m_queue_in.addBlock(p, data, ack_to_server, urgent);
1595 }
1596
1597 void Client::addUpdateMeshTaskWithEdge(v3s16 blockpos, bool ack_to_server, bool urgent)
1598 {
1599         try{
1600                 addUpdateMeshTask(blockpos, ack_to_server, urgent);
1601         }
1602         catch(InvalidPositionException &e){}
1603
1604         // Leading edge
1605         for (int i=0;i<6;i++)
1606         {
1607                 try{
1608                         v3s16 p = blockpos + g_6dirs[i];
1609                         addUpdateMeshTask(p, false, urgent);
1610                 }
1611                 catch(InvalidPositionException &e){}
1612         }
1613 }
1614
1615 void Client::addUpdateMeshTaskForNode(v3s16 nodepos, bool ack_to_server, bool urgent)
1616 {
1617         {
1618                 v3s16 p = nodepos;
1619                 infostream<<"Client::addUpdateMeshTaskForNode(): "
1620                                 <<"("<<p.X<<","<<p.Y<<","<<p.Z<<")"
1621                                 <<std::endl;
1622         }
1623
1624         v3s16 blockpos          = getNodeBlockPos(nodepos);
1625         v3s16 blockpos_relative = blockpos * MAP_BLOCKSIZE;
1626
1627         try{
1628                 addUpdateMeshTask(blockpos, ack_to_server, urgent);
1629         }
1630         catch(InvalidPositionException &e) {}
1631
1632         // Leading edge
1633         if(nodepos.X == blockpos_relative.X){
1634                 try{
1635                         v3s16 p = blockpos + v3s16(-1,0,0);
1636                         addUpdateMeshTask(p, false, urgent);
1637                 }
1638                 catch(InvalidPositionException &e){}
1639         }
1640
1641         if(nodepos.Y == blockpos_relative.Y){
1642                 try{
1643                         v3s16 p = blockpos + v3s16(0,-1,0);
1644                         addUpdateMeshTask(p, false, urgent);
1645                 }
1646                 catch(InvalidPositionException &e){}
1647         }
1648
1649         if(nodepos.Z == blockpos_relative.Z){
1650                 try{
1651                         v3s16 p = blockpos + v3s16(0,0,-1);
1652                         addUpdateMeshTask(p, false, urgent);
1653                 }
1654                 catch(InvalidPositionException &e){}
1655         }
1656 }
1657
1658 ClientEvent Client::getClientEvent()
1659 {
1660         ClientEvent event;
1661         if(m_client_event_queue.size() == 0) {
1662                 event.type = CE_NONE;
1663         }
1664         else {
1665                 event = m_client_event_queue.front();
1666                 m_client_event_queue.pop();
1667         }
1668         return event;
1669 }
1670
1671 float Client::mediaReceiveProgress()
1672 {
1673         if (m_media_downloader)
1674                 return m_media_downloader->getProgress();
1675         else
1676                 return 1.0; // downloader only exists when not yet done
1677 }
1678
1679 typedef struct TextureUpdateArgs {
1680         IrrlichtDevice *device;
1681         gui::IGUIEnvironment *guienv;
1682         u32 last_time_ms;
1683         u16 last_percent;
1684         const wchar_t* text_base;
1685 } TextureUpdateArgs;
1686
1687 void texture_update_progress(void *args, u32 progress, u32 max_progress)
1688 {
1689                 TextureUpdateArgs* targs = (TextureUpdateArgs*) args;
1690                 u16 cur_percent = ceil(progress / (double) max_progress * 100.);
1691
1692                 // update the loading menu -- if neccessary
1693                 bool do_draw = false;
1694                 u32 time_ms = targs->last_time_ms;
1695                 if (cur_percent != targs->last_percent) {
1696                         targs->last_percent = cur_percent;
1697                         time_ms = getTimeMs();
1698                         // only draw when the user will notice something:
1699                         do_draw = (time_ms - targs->last_time_ms > 100);
1700                 }
1701
1702                 if (do_draw) {
1703                         targs->last_time_ms = time_ms;
1704                         std::basic_stringstream<wchar_t> strm;
1705                         strm << targs->text_base << " " << targs->last_percent << "%...";
1706                         draw_load_screen(strm.str(), targs->device, targs->guienv, 0,
1707                                 72 + (u16) ((18. / 100.) * (double) targs->last_percent));
1708                 }
1709 }
1710
1711 void Client::afterContentReceived(IrrlichtDevice *device)
1712 {
1713         infostream<<"Client::afterContentReceived() started"<<std::endl;
1714         assert(m_itemdef_received); // pre-condition
1715         assert(m_nodedef_received); // pre-condition
1716         assert(mediaReceived()); // pre-condition
1717
1718         const wchar_t* text = wgettext("Loading textures...");
1719
1720         // Clear cached pre-scaled 2D GUI images, as this cache
1721         // might have images with the same name but different
1722         // content from previous sessions.
1723         guiScalingCacheClear(device->getVideoDriver());
1724
1725         // Rebuild inherited images and recreate textures
1726         infostream<<"- Rebuilding images and textures"<<std::endl;
1727         draw_load_screen(text,device, guienv, 0, 70);
1728         m_tsrc->rebuildImagesAndTextures();
1729         delete[] text;
1730
1731         // Rebuild shaders
1732         infostream<<"- Rebuilding shaders"<<std::endl;
1733         text = wgettext("Rebuilding shaders...");
1734         draw_load_screen(text, device, guienv, 0, 71);
1735         m_shsrc->rebuildShaders();
1736         delete[] text;
1737
1738         // Update node aliases
1739         infostream<<"- Updating node aliases"<<std::endl;
1740         text = wgettext("Initializing nodes...");
1741         draw_load_screen(text, device, guienv, 0, 72);
1742         m_nodedef->updateAliases(m_itemdef);
1743         m_nodedef->setNodeRegistrationStatus(true);
1744         m_nodedef->runNodeResolveCallbacks();
1745         delete[] text;
1746
1747         // Update node textures and assign shaders to each tile
1748         infostream<<"- Updating node textures"<<std::endl;
1749         TextureUpdateArgs tu_args;
1750         tu_args.device = device;
1751         tu_args.guienv = guienv;
1752         tu_args.last_time_ms = getTimeMs();
1753         tu_args.last_percent = 0;
1754         tu_args.text_base =  wgettext("Initializing nodes");
1755         m_nodedef->updateTextures(this, texture_update_progress, &tu_args);
1756         delete[] tu_args.text_base;
1757
1758         // Preload item textures and meshes if configured to
1759         if(g_settings->getBool("preload_item_visuals"))
1760         {
1761                 verbosestream<<"Updating item textures and meshes"<<std::endl;
1762                 text = wgettext("Item textures...");
1763                 draw_load_screen(text, device, guienv, 0, 0);
1764                 std::set<std::string> names = m_itemdef->getAll();
1765                 size_t size = names.size();
1766                 size_t count = 0;
1767                 int percent = 0;
1768                 for(std::set<std::string>::const_iterator
1769                                 i = names.begin(); i != names.end(); ++i)
1770                 {
1771                         // Asking for these caches the result
1772                         m_itemdef->getInventoryTexture(*i, this);
1773                         m_itemdef->getWieldMesh(*i, this);
1774                         count++;
1775                         percent = (count * 100 / size * 0.2) + 80;
1776                         draw_load_screen(text, device, guienv, 0, percent);
1777                 }
1778                 delete[] text;
1779         }
1780
1781         // Start mesh update thread after setting up content definitions
1782         infostream<<"- Starting mesh update thread"<<std::endl;
1783         m_mesh_update_thread.Start();
1784
1785         m_state = LC_Ready;
1786         sendReady();
1787         text = wgettext("Done!");
1788         draw_load_screen(text, device, guienv, 0, 100);
1789         infostream<<"Client::afterContentReceived() done"<<std::endl;
1790         delete[] text;
1791 }
1792
1793 float Client::getRTT(void)
1794 {
1795         return m_con.getPeerStat(PEER_ID_SERVER,con::AVG_RTT);
1796 }
1797
1798 float Client::getCurRate(void)
1799 {
1800         return ( m_con.getLocalStat(con::CUR_INC_RATE) +
1801                         m_con.getLocalStat(con::CUR_DL_RATE));
1802 }
1803
1804 float Client::getAvgRate(void)
1805 {
1806         return ( m_con.getLocalStat(con::AVG_INC_RATE) +
1807                         m_con.getLocalStat(con::AVG_DL_RATE));
1808 }
1809
1810 void Client::makeScreenshot(IrrlichtDevice *device)
1811 {
1812         irr::video::IVideoDriver *driver = device->getVideoDriver();
1813         irr::video::IImage* const raw_image = driver->createScreenShot();
1814
1815         if (!raw_image)
1816                 return;
1817
1818         time_t t = time(NULL);
1819         struct tm *tm = localtime(&t);
1820
1821         char timetstamp_c[64];
1822         strftime(timetstamp_c, sizeof(timetstamp_c), "%Y%m%d_%H%M%S", tm);
1823
1824         std::string filename_base = g_settings->get("screenshot_path")
1825                         + DIR_DELIM
1826                         + std::string("screenshot_")
1827                         + std::string(timetstamp_c);
1828         std::string filename_ext = ".png";
1829         std::string filename;
1830
1831         // Try to find a unique filename
1832         unsigned serial = 0;
1833
1834         while (serial < SCREENSHOT_MAX_SERIAL_TRIES) {
1835                 filename = filename_base + (serial > 0 ? ("_" + itos(serial)) : "") + filename_ext;
1836                 std::ifstream tmp(filename.c_str());
1837                 if (!tmp.good())
1838                         break;  // File did not apparently exist, we'll go with it
1839                 serial++;
1840         }
1841
1842         if (serial == SCREENSHOT_MAX_SERIAL_TRIES) {
1843                 infostream << "Could not find suitable filename for screenshot" << std::endl;
1844         } else {
1845                 irr::video::IImage* const image =
1846                                 driver->createImage(video::ECF_R8G8B8, raw_image->getDimension());
1847
1848                 if (image) {
1849                         raw_image->copyTo(image);
1850
1851                         std::ostringstream sstr;
1852                         if (driver->writeImageToFile(image, filename.c_str())) {
1853                                 sstr << "Saved screenshot to '" << filename << "'";
1854                         } else {
1855                                 sstr << "Failed to save screenshot '" << filename << "'";
1856                         }
1857                         m_chat_queue.push(narrow_to_wide(sstr.str()));
1858                         infostream << sstr.str() << std::endl;
1859                         image->drop();
1860                 }
1861         }
1862
1863         raw_image->drop();
1864 }
1865
1866 // IGameDef interface
1867 // Under envlock
1868 IItemDefManager* Client::getItemDefManager()
1869 {
1870         return m_itemdef;
1871 }
1872 INodeDefManager* Client::getNodeDefManager()
1873 {
1874         return m_nodedef;
1875 }
1876 ICraftDefManager* Client::getCraftDefManager()
1877 {
1878         return NULL;
1879         //return m_craftdef;
1880 }
1881 ITextureSource* Client::getTextureSource()
1882 {
1883         return m_tsrc;
1884 }
1885 IShaderSource* Client::getShaderSource()
1886 {
1887         return m_shsrc;
1888 }
1889 scene::ISceneManager* Client::getSceneManager()
1890 {
1891         return m_device->getSceneManager();
1892 }
1893 u16 Client::allocateUnknownNodeId(const std::string &name)
1894 {
1895         errorstream << "Client::allocateUnknownNodeId(): "
1896                         << "Client cannot allocate node IDs" << std::endl;
1897         FATAL_ERROR("Client allocated unknown node");
1898
1899         return CONTENT_IGNORE;
1900 }
1901 ISoundManager* Client::getSoundManager()
1902 {
1903         return m_sound;
1904 }
1905 MtEventManager* Client::getEventManager()
1906 {
1907         return m_event;
1908 }
1909
1910 ParticleManager* Client::getParticleManager()
1911 {
1912         return &m_particle_manager;
1913 }
1914
1915 scene::IAnimatedMesh* Client::getMesh(const std::string &filename)
1916 {
1917         std::map<std::string, std::string>::const_iterator i =
1918                         m_mesh_data.find(filename);
1919         if(i == m_mesh_data.end()){
1920                 errorstream<<"Client::getMesh(): Mesh not found: \""<<filename<<"\""
1921                                 <<std::endl;
1922                 return NULL;
1923         }
1924         const std::string &data    = i->second;
1925         scene::ISceneManager *smgr = m_device->getSceneManager();
1926
1927         // Create the mesh, remove it from cache and return it
1928         // This allows unique vertex colors and other properties for each instance
1929         Buffer<char> data_rw(data.c_str(), data.size()); // Const-incorrect Irrlicht
1930         io::IFileSystem *irrfs = m_device->getFileSystem();
1931         io::IReadFile *rfile   = irrfs->createMemoryReadFile(
1932                         *data_rw, data_rw.getSize(), filename.c_str());
1933         FATAL_ERROR_IF(!rfile, "Could not create/open RAM file");
1934
1935         scene::IAnimatedMesh *mesh = smgr->getMesh(rfile);
1936         rfile->drop();
1937         // NOTE: By playing with Irrlicht refcounts, maybe we could cache a bunch
1938         // of uniquely named instances and re-use them
1939         mesh->grab();
1940         smgr->getMeshCache()->removeMesh(mesh);
1941         return mesh;
1942 }