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