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