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