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