Return to ignore
[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                 return;
884         }
885
886         /*
887          * Those packets are handled before m_server_ser_ver is set, it's normal
888          * But we must use the new ToClientConnectionState in the future,
889          * as a byte mask
890          */
891         if(toClientCommandTable[command].state == TOCLIENT_STATE_NOT_CONNECTED) {
892                 handleCommand(pkt);
893                 return;
894         }
895
896         if(m_server_ser_ver == SER_FMT_VER_INVALID) {
897                 infostream << "Client: Server serialization"
898                                 " format invalid or not initialized."
899                                 " Skipping incoming command=" << command << std::endl;
900                 return;
901         }
902
903         /*
904           Handle runtime commands
905         */
906
907         handleCommand(pkt);
908 }
909
910 void Client::Send(NetworkPacket* pkt)
911 {
912         m_con.Send(PEER_ID_SERVER,
913                 serverCommandFactoryTable[pkt->getCommand()].channel,
914                 pkt,
915                 serverCommandFactoryTable[pkt->getCommand()].reliable);
916 }
917
918 void Client::interact(u8 action, const PointedThing& pointed)
919 {
920         if(m_state != LC_Ready) {
921                 errorstream << "Client::interact() "
922                                 "Canceled (not connected)"
923                                 << std::endl;
924                 return;
925         }
926
927         /*
928                 [0] u16 command
929                 [2] u8 action
930                 [3] u16 item
931                 [5] u32 length of the next item
932                 [9] serialized PointedThing
933                 actions:
934                 0: start digging (from undersurface) or use
935                 1: stop digging (all parameters ignored)
936                 2: digging completed
937                 3: place block or item (to abovesurface)
938                 4: use item
939         */
940
941         NetworkPacket pkt(TOSERVER_INTERACT, 1 + 2 + 0);
942
943         pkt << action;
944         pkt << (u16)getPlayerItem();
945
946         std::ostringstream tmp_os(std::ios::binary);
947         pointed.serialize(tmp_os);
948
949         pkt.putLongString(tmp_os.str());
950
951         Send(&pkt);
952 }
953
954 void Client::deleteAuthData()
955 {
956         if (!m_auth_data)
957                 return;
958
959         switch (m_chosen_auth_mech) {
960                 case AUTH_MECHANISM_FIRST_SRP:
961                         break;
962                 case AUTH_MECHANISM_SRP:
963                 case AUTH_MECHANISM_LEGACY_PASSWORD:
964                         srp_user_delete((SRPUser *) m_auth_data);
965                         m_auth_data = NULL;
966                         break;
967                 case AUTH_MECHANISM_NONE:
968                         break;
969         }
970 }
971
972
973 AuthMechanism Client::choseAuthMech(const u32 mechs)
974 {
975         if (mechs & AUTH_MECHANISM_SRP)
976                 return AUTH_MECHANISM_SRP;
977
978         if (mechs & AUTH_MECHANISM_FIRST_SRP)
979                 return AUTH_MECHANISM_FIRST_SRP;
980
981         if (mechs & AUTH_MECHANISM_LEGACY_PASSWORD)
982                 return AUTH_MECHANISM_LEGACY_PASSWORD;
983
984         return AUTH_MECHANISM_NONE;
985 }
986
987 void Client::sendLegacyInit(const char* playerName, const char* playerPassword)
988 {
989         NetworkPacket pkt(TOSERVER_INIT_LEGACY,
990                         1 + PLAYERNAME_SIZE + PASSWORD_SIZE + 2 + 2);
991
992         pkt << (u8) SER_FMT_VER_HIGHEST_READ;
993         pkt.putRawString(playerName,PLAYERNAME_SIZE);
994         pkt.putRawString(playerPassword, PASSWORD_SIZE);
995         pkt << (u16) CLIENT_PROTOCOL_VERSION_MIN << (u16) CLIENT_PROTOCOL_VERSION_MAX;
996
997         Send(&pkt);
998 }
999
1000 void Client::sendInit(const std::string &playerName)
1001 {
1002         NetworkPacket pkt(TOSERVER_INIT, 1 + 2 + 2 + (1 + playerName.size()));
1003
1004         // we don't support network compression yet
1005         u16 supp_comp_modes = NETPROTO_COMPRESSION_NONE;
1006         pkt << (u8) SER_FMT_VER_HIGHEST_READ << (u16) supp_comp_modes;
1007         pkt << (u16) CLIENT_PROTOCOL_VERSION_MIN << (u16) CLIENT_PROTOCOL_VERSION_MAX;
1008         pkt << playerName;
1009
1010         Send(&pkt);
1011 }
1012
1013 void Client::startAuth(AuthMechanism chosen_auth_mechanism)
1014 {
1015         m_chosen_auth_mech = chosen_auth_mechanism;
1016
1017         switch (chosen_auth_mechanism) {
1018                 case AUTH_MECHANISM_FIRST_SRP: {
1019                         // send srp verifier to server
1020                         NetworkPacket resp_pkt(TOSERVER_FIRST_SRP, 0);
1021                         char *salt, *bytes_v;
1022                         std::size_t len_salt, len_v;
1023                         salt = NULL;
1024                         getSRPVerifier(getPlayerName(), m_password,
1025                                 &salt, &len_salt, &bytes_v, &len_v);
1026                         resp_pkt
1027                                 << std::string((char*)salt, len_salt)
1028                                 << std::string((char*)bytes_v, len_v)
1029                                 << (u8)((m_password == "") ? 1 : 0);
1030                         free(salt);
1031                         free(bytes_v);
1032                         Send(&resp_pkt);
1033                         break;
1034                 }
1035                 case AUTH_MECHANISM_SRP:
1036                 case AUTH_MECHANISM_LEGACY_PASSWORD: {
1037                         u8 based_on = 1;
1038
1039                         if (chosen_auth_mechanism == AUTH_MECHANISM_LEGACY_PASSWORD) {
1040                                 m_password = translatePassword(getPlayerName(), m_password);
1041                                 based_on = 0;
1042                         }
1043
1044                         std::string playername_u = lowercase(getPlayerName());
1045                         m_auth_data = srp_user_new(SRP_SHA256, SRP_NG_2048,
1046                                 getPlayerName().c_str(), playername_u.c_str(),
1047                                 (const unsigned char *) m_password.c_str(),
1048                                 m_password.length(), NULL, NULL);
1049                         char *bytes_A = 0;
1050                         size_t len_A = 0;
1051                         srp_user_start_authentication((struct SRPUser *) m_auth_data,
1052                                 NULL, NULL, 0, (unsigned char **) &bytes_A, &len_A);
1053
1054                         NetworkPacket resp_pkt(TOSERVER_SRP_BYTES_A, 0);
1055                         resp_pkt << std::string(bytes_A, len_A) << based_on;
1056                         free(bytes_A);
1057                         Send(&resp_pkt);
1058                         break;
1059                 }
1060                 case AUTH_MECHANISM_NONE:
1061                         break; // not handled in this method
1062         }
1063 }
1064
1065 void Client::sendDeletedBlocks(std::vector<v3s16> &blocks)
1066 {
1067         NetworkPacket pkt(TOSERVER_DELETEDBLOCKS, 1 + sizeof(v3s16) * blocks.size());
1068
1069         pkt << (u8) blocks.size();
1070
1071         u32 k = 0;
1072         for(std::vector<v3s16>::iterator
1073                         j = blocks.begin();
1074                         j != blocks.end(); ++j) {
1075                 pkt << *j;
1076                 k++;
1077         }
1078
1079         Send(&pkt);
1080 }
1081
1082 void Client::sendGotBlocks(v3s16 block)
1083 {
1084         NetworkPacket pkt(TOSERVER_GOTBLOCKS, 1 + 6);
1085         pkt << (u8) 1 << block;
1086         Send(&pkt);
1087 }
1088
1089 void Client::sendRemovedSounds(std::vector<s32> &soundList)
1090 {
1091         size_t server_ids = soundList.size();
1092         assert(server_ids <= 0xFFFF);
1093
1094         NetworkPacket pkt(TOSERVER_REMOVED_SOUNDS, 2 + server_ids * 4);
1095
1096         pkt << (u16) (server_ids & 0xFFFF);
1097
1098         for(std::vector<s32>::iterator i = soundList.begin();
1099                         i != soundList.end(); i++)
1100                 pkt << *i;
1101
1102         Send(&pkt);
1103 }
1104
1105 void Client::sendNodemetaFields(v3s16 p, const std::string &formname,
1106                 const StringMap &fields)
1107 {
1108         size_t fields_size = fields.size();
1109
1110         FATAL_ERROR_IF(fields_size > 0xFFFF, "Unsupported number of nodemeta fields");
1111
1112         NetworkPacket pkt(TOSERVER_NODEMETA_FIELDS, 0);
1113
1114         pkt << p << formname << (u16) (fields_size & 0xFFFF);
1115
1116         StringMap::const_iterator it;
1117         for (it = fields.begin(); it != fields.end(); ++it) {
1118                 const std::string &name = it->first;
1119                 const std::string &value = it->second;
1120                 pkt << name;
1121                 pkt.putLongString(value);
1122         }
1123
1124         Send(&pkt);
1125 }
1126
1127 void Client::sendInventoryFields(const std::string &formname,
1128                 const StringMap &fields)
1129 {
1130         size_t fields_size = fields.size();
1131         FATAL_ERROR_IF(fields_size > 0xFFFF, "Unsupported number of inventory fields");
1132
1133         NetworkPacket pkt(TOSERVER_INVENTORY_FIELDS, 0);
1134         pkt << formname << (u16) (fields_size & 0xFFFF);
1135
1136         StringMap::const_iterator it;
1137         for (it = fields.begin(); it != fields.end(); ++it) {
1138                 const std::string &name  = it->first;
1139                 const std::string &value = it->second;
1140                 pkt << name;
1141                 pkt.putLongString(value);
1142         }
1143
1144         Send(&pkt);
1145 }
1146
1147 void Client::sendInventoryAction(InventoryAction *a)
1148 {
1149         std::ostringstream os(std::ios_base::binary);
1150
1151         a->serialize(os);
1152
1153         // Make data buffer
1154         std::string s = os.str();
1155
1156         NetworkPacket pkt(TOSERVER_INVENTORY_ACTION, s.size());
1157         pkt.putRawString(s.c_str(),s.size());
1158
1159         Send(&pkt);
1160 }
1161
1162 void Client::sendChatMessage(const std::wstring &message)
1163 {
1164         NetworkPacket pkt(TOSERVER_CHAT_MESSAGE, 2 + message.size() * sizeof(u16));
1165
1166         pkt << message;
1167
1168         Send(&pkt);
1169 }
1170
1171 void Client::sendChangePassword(const std::string &oldpassword,
1172         const std::string &newpassword)
1173 {
1174         Player *player = m_env.getLocalPlayer();
1175         if (player == NULL)
1176                 return;
1177
1178         std::string playername = player->getName();
1179         if (m_proto_ver >= 25) {
1180                 // get into sudo mode and then send new password to server
1181                 m_password = oldpassword;
1182                 m_new_password = newpassword;
1183                 startAuth(choseAuthMech(m_sudo_auth_methods));
1184         } else {
1185                 std::string oldpwd = translatePassword(playername, oldpassword);
1186                 std::string newpwd = translatePassword(playername, newpassword);
1187
1188                 NetworkPacket pkt(TOSERVER_PASSWORD_LEGACY, 2 * PASSWORD_SIZE);
1189
1190                 for (u8 i = 0; i < PASSWORD_SIZE; i++) {
1191                         pkt << (u8) (i < oldpwd.length() ? oldpwd[i] : 0);
1192                 }
1193
1194                 for (u8 i = 0; i < PASSWORD_SIZE; i++) {
1195                         pkt << (u8) (i < newpwd.length() ? newpwd[i] : 0);
1196                 }
1197                 Send(&pkt);
1198         }
1199 }
1200
1201
1202 void Client::sendDamage(u8 damage)
1203 {
1204         DSTACK(__FUNCTION_NAME);
1205
1206         NetworkPacket pkt(TOSERVER_DAMAGE, sizeof(u8));
1207         pkt << damage;
1208         Send(&pkt);
1209 }
1210
1211 void Client::sendBreath(u16 breath)
1212 {
1213         DSTACK(__FUNCTION_NAME);
1214
1215         NetworkPacket pkt(TOSERVER_BREATH, sizeof(u16));
1216         pkt << breath;
1217         Send(&pkt);
1218 }
1219
1220 void Client::sendRespawn()
1221 {
1222         DSTACK(__FUNCTION_NAME);
1223
1224         NetworkPacket pkt(TOSERVER_RESPAWN, 0);
1225         Send(&pkt);
1226 }
1227
1228 void Client::sendReady()
1229 {
1230         DSTACK(__FUNCTION_NAME);
1231
1232         NetworkPacket pkt(TOSERVER_CLIENT_READY,
1233                         1 + 1 + 1 + 1 + 2 + sizeof(char) * strlen(g_version_hash));
1234
1235         pkt << (u8) VERSION_MAJOR << (u8) VERSION_MINOR << (u8) VERSION_PATCH
1236                 << (u8) 0 << (u16) strlen(g_version_hash);
1237
1238         pkt.putRawString(g_version_hash, (u16) strlen(g_version_hash));
1239         Send(&pkt);
1240 }
1241
1242 void Client::sendPlayerPos()
1243 {
1244         LocalPlayer *myplayer = m_env.getLocalPlayer();
1245         if(myplayer == NULL)
1246                 return;
1247
1248         // Save bandwidth by only updating position when something changed
1249         if(myplayer->last_position        == myplayer->getPosition() &&
1250                         myplayer->last_speed      == myplayer->getSpeed()    &&
1251                         myplayer->last_pitch      == myplayer->getPitch()    &&
1252                         myplayer->last_yaw        == myplayer->getYaw()      &&
1253                         myplayer->last_keyPressed == myplayer->keyPressed)
1254                 return;
1255
1256         myplayer->last_position   = myplayer->getPosition();
1257         myplayer->last_speed      = myplayer->getSpeed();
1258         myplayer->last_pitch      = myplayer->getPitch();
1259         myplayer->last_yaw        = myplayer->getYaw();
1260         myplayer->last_keyPressed = myplayer->keyPressed;
1261
1262         u16 our_peer_id;
1263         {
1264                 //JMutexAutoLock lock(m_con_mutex); //bulk comment-out
1265                 our_peer_id = m_con.GetPeerID();
1266         }
1267
1268         // Set peer id if not set already
1269         if(myplayer->peer_id == PEER_ID_INEXISTENT)
1270                 myplayer->peer_id = our_peer_id;
1271
1272         assert(myplayer->peer_id == our_peer_id);
1273
1274         v3f pf         = myplayer->getPosition();
1275         v3f sf         = myplayer->getSpeed();
1276         s32 pitch      = myplayer->getPitch() * 100;
1277         s32 yaw        = myplayer->getYaw() * 100;
1278         u32 keyPressed = myplayer->keyPressed;
1279
1280         v3s32 position(pf.X*100, pf.Y*100, pf.Z*100);
1281         v3s32 speed(sf.X*100, sf.Y*100, sf.Z*100);
1282         /*
1283                 Format:
1284                 [0] v3s32 position*100
1285                 [12] v3s32 speed*100
1286                 [12+12] s32 pitch*100
1287                 [12+12+4] s32 yaw*100
1288                 [12+12+4+4] u32 keyPressed
1289         */
1290
1291         NetworkPacket pkt(TOSERVER_PLAYERPOS, 12 + 12 + 4 + 4 + 4);
1292
1293         pkt << position << speed << pitch << yaw << keyPressed;
1294
1295         Send(&pkt);
1296 }
1297
1298 void Client::sendPlayerItem(u16 item)
1299 {
1300         Player *myplayer = m_env.getLocalPlayer();
1301         if(myplayer == NULL)
1302                 return;
1303
1304         u16 our_peer_id = m_con.GetPeerID();
1305
1306         // Set peer id if not set already
1307         if(myplayer->peer_id == PEER_ID_INEXISTENT)
1308                 myplayer->peer_id = our_peer_id;
1309         assert(myplayer->peer_id == our_peer_id);
1310
1311         NetworkPacket pkt(TOSERVER_PLAYERITEM, 2);
1312
1313         pkt << item;
1314
1315         Send(&pkt);
1316 }
1317
1318 void Client::removeNode(v3s16 p)
1319 {
1320         std::map<v3s16, MapBlock*> modified_blocks;
1321
1322         try {
1323                 m_env.getMap().removeNodeAndUpdate(p, modified_blocks);
1324         }
1325         catch(InvalidPositionException &e) {
1326         }
1327
1328         for(std::map<v3s16, MapBlock *>::iterator
1329                         i = modified_blocks.begin();
1330                         i != modified_blocks.end(); ++i) {
1331                 addUpdateMeshTaskWithEdge(i->first, false, true);
1332         }
1333 }
1334
1335 void Client::addNode(v3s16 p, MapNode n, bool remove_metadata)
1336 {
1337         //TimeTaker timer1("Client::addNode()");
1338
1339         std::map<v3s16, MapBlock*> modified_blocks;
1340
1341         try {
1342                 //TimeTaker timer3("Client::addNode(): addNodeAndUpdate");
1343                 m_env.getMap().addNodeAndUpdate(p, n, modified_blocks, remove_metadata);
1344         }
1345         catch(InvalidPositionException &e) {
1346         }
1347
1348         for(std::map<v3s16, MapBlock *>::iterator
1349                         i = modified_blocks.begin();
1350                         i != modified_blocks.end(); ++i) {
1351                 addUpdateMeshTaskWithEdge(i->first, false, true);
1352         }
1353 }
1354
1355 void Client::setPlayerControl(PlayerControl &control)
1356 {
1357         LocalPlayer *player = m_env.getLocalPlayer();
1358         assert(player != NULL);
1359         player->control = control;
1360 }
1361
1362 void Client::selectPlayerItem(u16 item)
1363 {
1364         m_playeritem = item;
1365         m_inventory_updated = true;
1366         sendPlayerItem(item);
1367 }
1368
1369 // Returns true if the inventory of the local player has been
1370 // updated from the server. If it is true, it is set to false.
1371 bool Client::getLocalInventoryUpdated()
1372 {
1373         bool updated = m_inventory_updated;
1374         m_inventory_updated = false;
1375         return updated;
1376 }
1377
1378 // Copies the inventory of the local player to parameter
1379 void Client::getLocalInventory(Inventory &dst)
1380 {
1381         Player *player = m_env.getLocalPlayer();
1382         assert(player != NULL);
1383         dst = player->inventory;
1384 }
1385
1386 Inventory* Client::getInventory(const InventoryLocation &loc)
1387 {
1388         switch(loc.type){
1389         case InventoryLocation::UNDEFINED:
1390         {}
1391         break;
1392         case InventoryLocation::CURRENT_PLAYER:
1393         {
1394                 Player *player = m_env.getLocalPlayer();
1395                 assert(player != NULL);
1396                 return &player->inventory;
1397         }
1398         break;
1399         case InventoryLocation::PLAYER:
1400         {
1401                 Player *player = m_env.getPlayer(loc.name.c_str());
1402                 if(!player)
1403                         return NULL;
1404                 return &player->inventory;
1405         }
1406         break;
1407         case InventoryLocation::NODEMETA:
1408         {
1409                 NodeMetadata *meta = m_env.getMap().getNodeMetadata(loc.p);
1410                 if(!meta)
1411                         return NULL;
1412                 return meta->getInventory();
1413         }
1414         break;
1415         case InventoryLocation::DETACHED:
1416         {
1417                 if(m_detached_inventories.count(loc.name) == 0)
1418                         return NULL;
1419                 return m_detached_inventories[loc.name];
1420         }
1421         break;
1422         default:
1423                 FATAL_ERROR("Invalid inventory location type.");
1424                 break;
1425         }
1426         return NULL;
1427 }
1428
1429 void Client::inventoryAction(InventoryAction *a)
1430 {
1431         /*
1432                 Send it to the server
1433         */
1434         sendInventoryAction(a);
1435
1436         /*
1437                 Predict some local inventory changes
1438         */
1439         a->clientApply(this, this);
1440
1441         // Remove it
1442         delete a;
1443 }
1444
1445 ClientActiveObject * Client::getSelectedActiveObject(
1446                 f32 max_d,
1447                 v3f from_pos_f_on_map,
1448                 core::line3d<f32> shootline_on_map
1449         )
1450 {
1451         std::vector<DistanceSortedActiveObject> objects;
1452
1453         m_env.getActiveObjects(from_pos_f_on_map, max_d, objects);
1454
1455         // Sort them.
1456         // After this, the closest object is the first in the array.
1457         std::sort(objects.begin(), objects.end());
1458
1459         for(unsigned int i=0; i<objects.size(); i++)
1460         {
1461                 ClientActiveObject *obj = objects[i].obj;
1462
1463                 core::aabbox3d<f32> *selection_box = obj->getSelectionBox();
1464                 if(selection_box == NULL)
1465                         continue;
1466
1467                 v3f pos = obj->getPosition();
1468
1469                 core::aabbox3d<f32> offsetted_box(
1470                                 selection_box->MinEdge + pos,
1471                                 selection_box->MaxEdge + pos
1472                 );
1473
1474                 if(offsetted_box.intersectsWithLine(shootline_on_map))
1475                 {
1476                         return obj;
1477                 }
1478         }
1479
1480         return NULL;
1481 }
1482
1483 std::list<std::string> Client::getConnectedPlayerNames()
1484 {
1485         return m_env.getPlayerNames();
1486 }
1487
1488 float Client::getAnimationTime()
1489 {
1490         return m_animation_time;
1491 }
1492
1493 int Client::getCrackLevel()
1494 {
1495         return m_crack_level;
1496 }
1497
1498 void Client::setHighlighted(v3s16 pos, bool show_highlighted)
1499 {
1500         m_show_highlighted = show_highlighted;
1501         v3s16 old_highlighted_pos = m_highlighted_pos;
1502         m_highlighted_pos = pos;
1503         addUpdateMeshTaskForNode(old_highlighted_pos, false, true);
1504         addUpdateMeshTaskForNode(m_highlighted_pos, false, true);
1505 }
1506
1507 void Client::setCrack(int level, v3s16 pos)
1508 {
1509         int old_crack_level = m_crack_level;
1510         v3s16 old_crack_pos = m_crack_pos;
1511
1512         m_crack_level = level;
1513         m_crack_pos = pos;
1514
1515         if(old_crack_level >= 0 && (level < 0 || pos != old_crack_pos))
1516         {
1517                 // remove old crack
1518                 addUpdateMeshTaskForNode(old_crack_pos, false, true);
1519         }
1520         if(level >= 0 && (old_crack_level < 0 || pos != old_crack_pos))
1521         {
1522                 // add new crack
1523                 addUpdateMeshTaskForNode(pos, false, true);
1524         }
1525 }
1526
1527 u16 Client::getHP()
1528 {
1529         Player *player = m_env.getLocalPlayer();
1530         assert(player != NULL);
1531         return player->hp;
1532 }
1533
1534 u16 Client::getBreath()
1535 {
1536         Player *player = m_env.getLocalPlayer();
1537         assert(player != NULL);
1538         return player->getBreath();
1539 }
1540
1541 bool Client::getChatMessage(std::wstring &message)
1542 {
1543         if(m_chat_queue.size() == 0)
1544                 return false;
1545         message = m_chat_queue.front();
1546         m_chat_queue.pop();
1547         return true;
1548 }
1549
1550 void Client::typeChatMessage(const std::wstring &message)
1551 {
1552         // Discard empty line
1553         if(message == L"")
1554                 return;
1555
1556         // Send to others
1557         sendChatMessage(message);
1558
1559         // Show locally
1560         if (message[0] == L'/')
1561         {
1562                 m_chat_queue.push((std::wstring)L"issued command: " + message);
1563         }
1564         else
1565         {
1566                 LocalPlayer *player = m_env.getLocalPlayer();
1567                 assert(player != NULL);
1568                 std::wstring name = narrow_to_wide(player->getName());
1569                 m_chat_queue.push((std::wstring)L"<" + name + L"> " + message);
1570         }
1571 }
1572
1573 void Client::addUpdateMeshTask(v3s16 p, bool ack_to_server, bool urgent)
1574 {
1575         MapBlock *b = m_env.getMap().getBlockNoCreateNoEx(p);
1576         if(b == NULL)
1577                 return;
1578
1579         /*
1580                 Create a task to update the mesh of the block
1581         */
1582
1583         MeshMakeData *data = new MeshMakeData(this, m_cache_enable_shaders);
1584
1585         {
1586                 //TimeTaker timer("data fill");
1587                 // Release: ~0ms
1588                 // Debug: 1-6ms, avg=2ms
1589                 data->fill(b);
1590                 data->setCrack(m_crack_level, m_crack_pos);
1591                 data->setHighlighted(m_highlighted_pos, m_show_highlighted);
1592                 data->setSmoothLighting(m_cache_smooth_lighting);
1593         }
1594
1595         // Add task to queue
1596         m_mesh_update_thread.m_queue_in.addBlock(p, data, ack_to_server, urgent);
1597 }
1598
1599 void Client::addUpdateMeshTaskWithEdge(v3s16 blockpos, bool ack_to_server, bool urgent)
1600 {
1601         try{
1602                 addUpdateMeshTask(blockpos, ack_to_server, urgent);
1603         }
1604         catch(InvalidPositionException &e){}
1605
1606         // Leading edge
1607         for (int i=0;i<6;i++)
1608         {
1609                 try{
1610                         v3s16 p = blockpos + g_6dirs[i];
1611                         addUpdateMeshTask(p, false, urgent);
1612                 }
1613                 catch(InvalidPositionException &e){}
1614         }
1615 }
1616
1617 void Client::addUpdateMeshTaskForNode(v3s16 nodepos, bool ack_to_server, bool urgent)
1618 {
1619         {
1620                 v3s16 p = nodepos;
1621                 infostream<<"Client::addUpdateMeshTaskForNode(): "
1622                                 <<"("<<p.X<<","<<p.Y<<","<<p.Z<<")"
1623                                 <<std::endl;
1624         }
1625
1626         v3s16 blockpos          = getNodeBlockPos(nodepos);
1627         v3s16 blockpos_relative = blockpos * MAP_BLOCKSIZE;
1628
1629         try{
1630                 addUpdateMeshTask(blockpos, ack_to_server, urgent);
1631         }
1632         catch(InvalidPositionException &e) {}
1633
1634         // Leading edge
1635         if(nodepos.X == blockpos_relative.X){
1636                 try{
1637                         v3s16 p = blockpos + v3s16(-1,0,0);
1638                         addUpdateMeshTask(p, false, urgent);
1639                 }
1640                 catch(InvalidPositionException &e){}
1641         }
1642
1643         if(nodepos.Y == blockpos_relative.Y){
1644                 try{
1645                         v3s16 p = blockpos + v3s16(0,-1,0);
1646                         addUpdateMeshTask(p, false, urgent);
1647                 }
1648                 catch(InvalidPositionException &e){}
1649         }
1650
1651         if(nodepos.Z == blockpos_relative.Z){
1652                 try{
1653                         v3s16 p = blockpos + v3s16(0,0,-1);
1654                         addUpdateMeshTask(p, false, urgent);
1655                 }
1656                 catch(InvalidPositionException &e){}
1657         }
1658 }
1659
1660 ClientEvent Client::getClientEvent()
1661 {
1662         ClientEvent event;
1663         if(m_client_event_queue.size() == 0) {
1664                 event.type = CE_NONE;
1665         }
1666         else {
1667                 event = m_client_event_queue.front();
1668                 m_client_event_queue.pop();
1669         }
1670         return event;
1671 }
1672
1673 float Client::mediaReceiveProgress()
1674 {
1675         if (m_media_downloader)
1676                 return m_media_downloader->getProgress();
1677         else
1678                 return 1.0; // downloader only exists when not yet done
1679 }
1680
1681 typedef struct TextureUpdateArgs {
1682         IrrlichtDevice *device;
1683         gui::IGUIEnvironment *guienv;
1684         u32 last_time_ms;
1685         u16 last_percent;
1686         const wchar_t* text_base;
1687 } TextureUpdateArgs;
1688
1689 void texture_update_progress(void *args, u32 progress, u32 max_progress)
1690 {
1691                 TextureUpdateArgs* targs = (TextureUpdateArgs*) args;
1692                 u16 cur_percent = ceil(progress / (double) max_progress * 100.);
1693
1694                 // update the loading menu -- if neccessary
1695                 bool do_draw = false;
1696                 u32 time_ms = targs->last_time_ms;
1697                 if (cur_percent != targs->last_percent) {
1698                         targs->last_percent = cur_percent;
1699                         time_ms = getTimeMs();
1700                         // only draw when the user will notice something:
1701                         do_draw = (time_ms - targs->last_time_ms > 100);
1702                 }
1703
1704                 if (do_draw) {
1705                         targs->last_time_ms = time_ms;
1706                         std::basic_stringstream<wchar_t> strm;
1707                         strm << targs->text_base << " " << targs->last_percent << "%...";
1708                         draw_load_screen(strm.str(), targs->device, targs->guienv, 0,
1709                                 72 + (u16) ((18. / 100.) * (double) targs->last_percent));
1710                 }
1711 }
1712
1713 void Client::afterContentReceived(IrrlichtDevice *device)
1714 {
1715         infostream<<"Client::afterContentReceived() started"<<std::endl;
1716         assert(m_itemdef_received); // pre-condition
1717         assert(m_nodedef_received); // pre-condition
1718         assert(mediaReceived()); // pre-condition
1719
1720         const wchar_t* text = wgettext("Loading textures...");
1721
1722         // Clear cached pre-scaled 2D GUI images, as this cache
1723         // might have images with the same name but different
1724         // content from previous sessions.
1725         guiScalingCacheClear(device->getVideoDriver());
1726
1727         // Rebuild inherited images and recreate textures
1728         infostream<<"- Rebuilding images and textures"<<std::endl;
1729         draw_load_screen(text,device, guienv, 0, 70);
1730         m_tsrc->rebuildImagesAndTextures();
1731         delete[] text;
1732
1733         // Rebuild shaders
1734         infostream<<"- Rebuilding shaders"<<std::endl;
1735         text = wgettext("Rebuilding shaders...");
1736         draw_load_screen(text, device, guienv, 0, 71);
1737         m_shsrc->rebuildShaders();
1738         delete[] text;
1739
1740         // Update node aliases
1741         infostream<<"- Updating node aliases"<<std::endl;
1742         text = wgettext("Initializing nodes...");
1743         draw_load_screen(text, device, guienv, 0, 72);
1744         m_nodedef->updateAliases(m_itemdef);
1745         std::string texture_path = g_settings->get("texture_path");
1746         if (texture_path != "" && fs::IsDir(texture_path))
1747                 m_nodedef->applyTextureOverrides(texture_path + DIR_DELIM + "override.txt");
1748         m_nodedef->setNodeRegistrationStatus(true);
1749         m_nodedef->runNodeResolveCallbacks();
1750         delete[] text;
1751
1752         // Update node textures and assign shaders to each tile
1753         infostream<<"- Updating node textures"<<std::endl;
1754         TextureUpdateArgs tu_args;
1755         tu_args.device = device;
1756         tu_args.guienv = guienv;
1757         tu_args.last_time_ms = getTimeMs();
1758         tu_args.last_percent = 0;
1759         tu_args.text_base =  wgettext("Initializing nodes");
1760         m_nodedef->updateTextures(this, texture_update_progress, &tu_args);
1761         delete[] tu_args.text_base;
1762
1763         // Preload item textures and meshes if configured to
1764         if(g_settings->getBool("preload_item_visuals"))
1765         {
1766                 verbosestream<<"Updating item textures and meshes"<<std::endl;
1767                 text = wgettext("Item textures...");
1768                 draw_load_screen(text, device, guienv, 0, 0);
1769                 std::set<std::string> names = m_itemdef->getAll();
1770                 size_t size = names.size();
1771                 size_t count = 0;
1772                 int percent = 0;
1773                 for(std::set<std::string>::const_iterator
1774                                 i = names.begin(); i != names.end(); ++i)
1775                 {
1776                         // Asking for these caches the result
1777                         m_itemdef->getInventoryTexture(*i, this);
1778                         m_itemdef->getWieldMesh(*i, this);
1779                         count++;
1780                         percent = (count * 100 / size * 0.2) + 80;
1781                         draw_load_screen(text, device, guienv, 0, percent);
1782                 }
1783                 delete[] text;
1784         }
1785
1786         // Start mesh update thread after setting up content definitions
1787         infostream<<"- Starting mesh update thread"<<std::endl;
1788         m_mesh_update_thread.Start();
1789
1790         m_state = LC_Ready;
1791         sendReady();
1792         text = wgettext("Done!");
1793         draw_load_screen(text, device, guienv, 0, 100);
1794         infostream<<"Client::afterContentReceived() done"<<std::endl;
1795         delete[] text;
1796 }
1797
1798 float Client::getRTT(void)
1799 {
1800         return m_con.getPeerStat(PEER_ID_SERVER,con::AVG_RTT);
1801 }
1802
1803 float Client::getCurRate(void)
1804 {
1805         return ( m_con.getLocalStat(con::CUR_INC_RATE) +
1806                         m_con.getLocalStat(con::CUR_DL_RATE));
1807 }
1808
1809 float Client::getAvgRate(void)
1810 {
1811         return ( m_con.getLocalStat(con::AVG_INC_RATE) +
1812                         m_con.getLocalStat(con::AVG_DL_RATE));
1813 }
1814
1815 void Client::makeScreenshot(IrrlichtDevice *device)
1816 {
1817         irr::video::IVideoDriver *driver = device->getVideoDriver();
1818         irr::video::IImage* const raw_image = driver->createScreenShot();
1819
1820         if (!raw_image)
1821                 return;
1822
1823         time_t t = time(NULL);
1824         struct tm *tm = localtime(&t);
1825
1826         char timetstamp_c[64];
1827         strftime(timetstamp_c, sizeof(timetstamp_c), "%Y%m%d_%H%M%S", tm);
1828
1829         std::string filename_base = g_settings->get("screenshot_path")
1830                         + DIR_DELIM
1831                         + std::string("screenshot_")
1832                         + std::string(timetstamp_c);
1833         std::string filename_ext = ".png";
1834         std::string filename;
1835
1836         // Try to find a unique filename
1837         unsigned serial = 0;
1838
1839         while (serial < SCREENSHOT_MAX_SERIAL_TRIES) {
1840                 filename = filename_base + (serial > 0 ? ("_" + itos(serial)) : "") + filename_ext;
1841                 std::ifstream tmp(filename.c_str());
1842                 if (!tmp.good())
1843                         break;  // File did not apparently exist, we'll go with it
1844                 serial++;
1845         }
1846
1847         if (serial == SCREENSHOT_MAX_SERIAL_TRIES) {
1848                 infostream << "Could not find suitable filename for screenshot" << std::endl;
1849         } else {
1850                 irr::video::IImage* const image =
1851                                 driver->createImage(video::ECF_R8G8B8, raw_image->getDimension());
1852
1853                 if (image) {
1854                         raw_image->copyTo(image);
1855
1856                         std::ostringstream sstr;
1857                         if (driver->writeImageToFile(image, filename.c_str())) {
1858                                 sstr << "Saved screenshot to '" << filename << "'";
1859                         } else {
1860                                 sstr << "Failed to save screenshot '" << filename << "'";
1861                         }
1862                         m_chat_queue.push(narrow_to_wide(sstr.str()));
1863                         infostream << sstr.str() << std::endl;
1864                         image->drop();
1865                 }
1866         }
1867
1868         raw_image->drop();
1869 }
1870
1871 // IGameDef interface
1872 // Under envlock
1873 IItemDefManager* Client::getItemDefManager()
1874 {
1875         return m_itemdef;
1876 }
1877 INodeDefManager* Client::getNodeDefManager()
1878 {
1879         return m_nodedef;
1880 }
1881 ICraftDefManager* Client::getCraftDefManager()
1882 {
1883         return NULL;
1884         //return m_craftdef;
1885 }
1886 ITextureSource* Client::getTextureSource()
1887 {
1888         return m_tsrc;
1889 }
1890 IShaderSource* Client::getShaderSource()
1891 {
1892         return m_shsrc;
1893 }
1894 scene::ISceneManager* Client::getSceneManager()
1895 {
1896         return m_device->getSceneManager();
1897 }
1898 u16 Client::allocateUnknownNodeId(const std::string &name)
1899 {
1900         errorstream << "Client::allocateUnknownNodeId(): "
1901                         << "Client cannot allocate node IDs" << std::endl;
1902         FATAL_ERROR("Client allocated unknown node");
1903
1904         return CONTENT_IGNORE;
1905 }
1906 ISoundManager* Client::getSoundManager()
1907 {
1908         return m_sound;
1909 }
1910 MtEventManager* Client::getEventManager()
1911 {
1912         return m_event;
1913 }
1914
1915 ParticleManager* Client::getParticleManager()
1916 {
1917         return &m_particle_manager;
1918 }
1919
1920 scene::IAnimatedMesh* Client::getMesh(const std::string &filename)
1921 {
1922         StringMap::const_iterator it = m_mesh_data.find(filename);
1923         if (it == m_mesh_data.end()) {
1924                 errorstream << "Client::getMesh(): Mesh not found: \"" << filename
1925                         << "\"" << std::endl;
1926                 return NULL;
1927         }
1928         const std::string &data    = it->second;
1929         scene::ISceneManager *smgr = m_device->getSceneManager();
1930
1931         // Create the mesh, remove it from cache and return it
1932         // This allows unique vertex colors and other properties for each instance
1933         Buffer<char> data_rw(data.c_str(), data.size()); // Const-incorrect Irrlicht
1934         io::IFileSystem *irrfs = m_device->getFileSystem();
1935         io::IReadFile *rfile   = irrfs->createMemoryReadFile(
1936                         *data_rw, data_rw.getSize(), filename.c_str());
1937         FATAL_ERROR_IF(!rfile, "Could not create/open RAM file");
1938
1939         scene::IAnimatedMesh *mesh = smgr->getMesh(rfile);
1940         rfile->drop();
1941         // NOTE: By playing with Irrlicht refcounts, maybe we could cache a bunch
1942         // of uniquely named instances and re-use them
1943         mesh->grab();
1944         smgr->getMeshCache()->removeMesh(mesh);
1945         return mesh;
1946 }