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