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