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