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