]> git.lizzy.rs Git - dragonfireclient.git/blob - src/client/client.cpp
Remove unused ITextSceneNode header (#11476)
[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                 RenderingEngine *rendering_engine,
101                 bool ipv6,
102                 GameUI *game_ui
103 ):
104         m_tsrc(tsrc),
105         m_shsrc(shsrc),
106         m_itemdef(itemdef),
107         m_nodedef(nodedef),
108         m_sound(sound),
109         m_event(event),
110         m_rendering_engine(rendering_engine),
111         m_mesh_update_thread(this),
112         m_env(
113                 new ClientMap(this, rendering_engine, control, 666),
114                 tsrc, this
115         ),
116         m_particle_manager(&m_env),
117         m_con(new con::Connection(PROTOCOL_ID, 512, CONNECTION_TIMEOUT, ipv6, this)),
118         m_address_name(address_name),
119         m_server_ser_ver(SER_FMT_VER_INVALID),
120         m_last_chat_message_sent(time(NULL)),
121         m_password(password),
122         m_chosen_auth_mech(AUTH_MECHANISM_NONE),
123         m_media_downloader(new ClientMediaDownloader()),
124         m_state(LC_Created),
125         m_game_ui(game_ui),
126         m_modchannel_mgr(new ModChannelMgr())
127 {
128         // Add local player
129         m_env.setLocalPlayer(new LocalPlayer(this, playername));
130
131         if (g_settings->getBool("enable_minimap")) {
132                 m_minimap = new Minimap(this);
133         }
134
135         m_cache_save_interval = g_settings->getU16("server_map_save_interval");
136 }
137
138 void Client::loadMods()
139 {
140         // Don't load mods twice.
141         // If client scripting is disabled by the client, don't load builtin or
142         // client-provided mods.
143         if (m_mods_loaded || !g_settings->getBool("enable_client_modding"))
144                 return;
145
146         // If client scripting is disabled by the server, don't load builtin or
147         // client-provided mods.
148         // TODO Delete this code block when server-sent CSM and verifying of builtin are
149         // complete.
150         if (checkCSMRestrictionFlag(CSMRestrictionFlags::CSM_RF_LOAD_CLIENT_MODS)) {
151                 warningstream << "Client-provided mod loading is disabled by server." <<
152                         std::endl;
153                 return;
154         }
155
156         m_script = new ClientScripting(this);
157         m_env.setScript(m_script);
158         m_script->setEnv(&m_env);
159
160         // Load builtin
161         scanModIntoMemory(BUILTIN_MOD_NAME, getBuiltinLuaPath());
162         m_script->loadModFromMemory(BUILTIN_MOD_NAME);
163
164         ClientModConfiguration modconf(getClientModsLuaPath());
165         m_mods = modconf.getMods();
166         // complain about mods with unsatisfied dependencies
167         if (!modconf.isConsistent()) {
168                 modconf.printUnsatisfiedModsError();
169                 return;
170         }
171
172         // Print mods
173         infostream << "Client loading mods: ";
174         for (const ModSpec &mod : m_mods)
175                 infostream << mod.name << " ";
176         infostream << std::endl;
177
178         // Load "mod" scripts
179         for (const ModSpec &mod : m_mods) {
180                 if (!string_allowed(mod.name, MODNAME_ALLOWED_CHARS)) {
181                         throw ModError("Error loading mod \"" + mod.name +
182                                 "\": Mod name does not follow naming conventions: "
183                                         "Only characters [a-z0-9_] are allowed.");
184                 }
185                 scanModIntoMemory(mod.name, mod.path);
186         }
187
188         // Run them
189         for (const ModSpec &mod : m_mods)
190                 m_script->loadModFromMemory(mod.name);
191
192         // Mods are done loading. Unlock callbacks
193         m_mods_loaded = true;
194
195         // Run a callback when mods are loaded
196         m_script->on_mods_loaded();
197
198         // Create objects if they're ready
199         if (m_state == LC_Ready)
200                 m_script->on_client_ready(m_env.getLocalPlayer());
201         if (m_camera)
202                 m_script->on_camera_ready(m_camera);
203         if (m_minimap)
204                 m_script->on_minimap_ready(m_minimap);
205 }
206
207 void Client::scanModSubfolder(const std::string &mod_name, const std::string &mod_path,
208                         std::string mod_subpath)
209 {
210         std::string full_path = mod_path + DIR_DELIM + mod_subpath;
211         std::vector<fs::DirListNode> mod = fs::GetDirListing(full_path);
212         for (const fs::DirListNode &j : mod) {
213                 if (j.name[0] == '.')
214                         continue;
215
216                 if (j.dir) {
217                         scanModSubfolder(mod_name, mod_path, mod_subpath + j.name + DIR_DELIM);
218                         continue;
219                 }
220                 std::replace(mod_subpath.begin(), mod_subpath.end(), DIR_DELIM_CHAR, '/');
221
222                 std::string real_path = full_path + j.name;
223                 std::string vfs_path = mod_name + ":" + mod_subpath + j.name;
224                 infostream << "Client::scanModSubfolder(): Loading \"" << real_path
225                                 << "\" as \"" << vfs_path << "\"." << std::endl;
226
227                 std::string contents;
228                 if (!fs::ReadFile(real_path, contents)) {
229                         errorstream << "Client::scanModSubfolder(): Can't read file \""
230                                         << real_path << "\"." << std::endl;
231                         continue;
232                 }
233
234                 m_mod_vfs.emplace(vfs_path, contents);
235         }
236 }
237
238 const std::string &Client::getBuiltinLuaPath()
239 {
240         static const std::string builtin_dir = porting::path_share + DIR_DELIM + "builtin";
241         return builtin_dir;
242 }
243
244 const std::string &Client::getClientModsLuaPath()
245 {
246         static const std::string clientmods_dir = porting::path_share + DIR_DELIM + "clientmods";
247         return clientmods_dir;
248 }
249
250 const std::vector<ModSpec>& Client::getMods() const
251 {
252         static std::vector<ModSpec> client_modspec_temp;
253         return client_modspec_temp;
254 }
255
256 const ModSpec* Client::getModSpec(const std::string &modname) const
257 {
258         return NULL;
259 }
260
261 void Client::Stop()
262 {
263         m_shutdown = true;
264         if (m_mods_loaded)
265                 m_script->on_shutdown();
266         //request all client managed threads to stop
267         m_mesh_update_thread.stop();
268         // Save local server map
269         if (m_localdb) {
270                 infostream << "Local map saving ended." << std::endl;
271                 m_localdb->endSave();
272         }
273
274         if (m_mods_loaded)
275                 delete m_script;
276 }
277
278 bool Client::isShutdown()
279 {
280         return m_shutdown || !m_mesh_update_thread.isRunning();
281 }
282
283 Client::~Client()
284 {
285         m_shutdown = true;
286         m_con->Disconnect();
287
288         deleteAuthData();
289
290         m_mesh_update_thread.stop();
291         m_mesh_update_thread.wait();
292         while (!m_mesh_update_thread.m_queue_out.empty()) {
293                 MeshUpdateResult r = m_mesh_update_thread.m_queue_out.pop_frontNoEx();
294                 delete r.mesh;
295         }
296
297
298         delete m_inventory_from_server;
299
300         // Delete detached inventories
301         for (auto &m_detached_inventorie : m_detached_inventories) {
302                 delete m_detached_inventorie.second;
303         }
304
305         // cleanup 3d model meshes on client shutdown
306         m_rendering_engine->cleanupMeshCache();
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 = m_rendering_engine->get_filesystem();
664                 video::IVideoDriver *vdrv = m_rendering_engine->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 scene::ISceneManager* Client::getSceneManager()
1416 {
1417         return m_rendering_engine->get_scene_manager();
1418 }
1419
1420 Inventory* Client::getInventory(const InventoryLocation &loc)
1421 {
1422         switch(loc.type){
1423         case InventoryLocation::UNDEFINED:
1424         {}
1425         break;
1426         case InventoryLocation::CURRENT_PLAYER:
1427         {
1428                 LocalPlayer *player = m_env.getLocalPlayer();
1429                 assert(player);
1430                 return &player->inventory;
1431         }
1432         break;
1433         case InventoryLocation::PLAYER:
1434         {
1435                 // Check if we are working with local player inventory
1436                 LocalPlayer *player = m_env.getLocalPlayer();
1437                 if (!player || strcmp(player->getName(), loc.name.c_str()) != 0)
1438                         return NULL;
1439                 return &player->inventory;
1440         }
1441         break;
1442         case InventoryLocation::NODEMETA:
1443         {
1444                 NodeMetadata *meta = m_env.getMap().getNodeMetadata(loc.p);
1445                 if(!meta)
1446                         return NULL;
1447                 return meta->getInventory();
1448         }
1449         break;
1450         case InventoryLocation::DETACHED:
1451         {
1452                 if (m_detached_inventories.count(loc.name) == 0)
1453                         return NULL;
1454                 return m_detached_inventories[loc.name];
1455         }
1456         break;
1457         default:
1458                 FATAL_ERROR("Invalid inventory location type.");
1459                 break;
1460         }
1461         return NULL;
1462 }
1463
1464 void Client::inventoryAction(InventoryAction *a)
1465 {
1466         /*
1467                 Send it to the server
1468         */
1469         sendInventoryAction(a);
1470
1471         /*
1472                 Predict some local inventory changes
1473         */
1474         a->clientApply(this, this);
1475
1476         // Remove it
1477         delete a;
1478 }
1479
1480 float Client::getAnimationTime()
1481 {
1482         return m_animation_time;
1483 }
1484
1485 int Client::getCrackLevel()
1486 {
1487         return m_crack_level;
1488 }
1489
1490 v3s16 Client::getCrackPos()
1491 {
1492         return m_crack_pos;
1493 }
1494
1495 void Client::setCrack(int level, v3s16 pos)
1496 {
1497         int old_crack_level = m_crack_level;
1498         v3s16 old_crack_pos = m_crack_pos;
1499
1500         m_crack_level = level;
1501         m_crack_pos = pos;
1502
1503         if(old_crack_level >= 0 && (level < 0 || pos != old_crack_pos))
1504         {
1505                 // remove old crack
1506                 addUpdateMeshTaskForNode(old_crack_pos, false, true);
1507         }
1508         if(level >= 0 && (old_crack_level < 0 || pos != old_crack_pos))
1509         {
1510                 // add new crack
1511                 addUpdateMeshTaskForNode(pos, false, true);
1512         }
1513 }
1514
1515 u16 Client::getHP()
1516 {
1517         LocalPlayer *player = m_env.getLocalPlayer();
1518         assert(player);
1519         return player->hp;
1520 }
1521
1522 bool Client::getChatMessage(std::wstring &res)
1523 {
1524         if (m_chat_queue.empty())
1525                 return false;
1526
1527         ChatMessage *chatMessage = m_chat_queue.front();
1528         m_chat_queue.pop();
1529
1530         res = L"";
1531
1532         switch (chatMessage->type) {
1533                 case CHATMESSAGE_TYPE_RAW:
1534                 case CHATMESSAGE_TYPE_ANNOUNCE:
1535                 case CHATMESSAGE_TYPE_SYSTEM:
1536                         res = chatMessage->message;
1537                         break;
1538                 case CHATMESSAGE_TYPE_NORMAL: {
1539                         if (!chatMessage->sender.empty())
1540                                 res = L"<" + chatMessage->sender + L"> " + chatMessage->message;
1541                         else
1542                                 res = chatMessage->message;
1543                         break;
1544                 }
1545                 default:
1546                         break;
1547         }
1548
1549         delete chatMessage;
1550         return true;
1551 }
1552
1553 void Client::typeChatMessage(const std::wstring &message)
1554 {
1555         // Discard empty line
1556         if (message.empty())
1557                 return;
1558
1559         // If message was consumed by script API, don't send it to server
1560         if (m_mods_loaded && m_script->on_sending_message(wide_to_utf8(message)))
1561                 return;
1562
1563         // Send to others
1564         sendChatMessage(message);
1565 }
1566
1567 void Client::addUpdateMeshTask(v3s16 p, bool ack_to_server, bool urgent)
1568 {
1569         // Check if the block exists to begin with. In the case when a non-existing
1570         // neighbor is automatically added, it may not. In that case we don't want
1571         // to tell the mesh update thread about it.
1572         MapBlock *b = m_env.getMap().getBlockNoCreateNoEx(p);
1573         if (b == NULL)
1574                 return;
1575
1576         m_mesh_update_thread.updateBlock(&m_env.getMap(), p, ack_to_server, urgent);
1577 }
1578
1579 void Client::addUpdateMeshTaskWithEdge(v3s16 blockpos, bool ack_to_server, bool urgent)
1580 {
1581         try{
1582                 addUpdateMeshTask(blockpos, ack_to_server, urgent);
1583         }
1584         catch(InvalidPositionException &e){}
1585
1586         // Leading edge
1587         for (int i=0;i<6;i++)
1588         {
1589                 try{
1590                         v3s16 p = blockpos + g_6dirs[i];
1591                         addUpdateMeshTask(p, false, urgent);
1592                 }
1593                 catch(InvalidPositionException &e){}
1594         }
1595 }
1596
1597 void Client::addUpdateMeshTaskForNode(v3s16 nodepos, bool ack_to_server, bool urgent)
1598 {
1599         {
1600                 v3s16 p = nodepos;
1601                 infostream<<"Client::addUpdateMeshTaskForNode(): "
1602                                 <<"("<<p.X<<","<<p.Y<<","<<p.Z<<")"
1603                                 <<std::endl;
1604         }
1605
1606         v3s16 blockpos          = getNodeBlockPos(nodepos);
1607         v3s16 blockpos_relative = blockpos * MAP_BLOCKSIZE;
1608
1609         try{
1610                 addUpdateMeshTask(blockpos, ack_to_server, urgent);
1611         }
1612         catch(InvalidPositionException &e) {}
1613
1614         // Leading edge
1615         if(nodepos.X == blockpos_relative.X){
1616                 try{
1617                         v3s16 p = blockpos + v3s16(-1,0,0);
1618                         addUpdateMeshTask(p, false, urgent);
1619                 }
1620                 catch(InvalidPositionException &e){}
1621         }
1622
1623         if(nodepos.Y == blockpos_relative.Y){
1624                 try{
1625                         v3s16 p = blockpos + v3s16(0,-1,0);
1626                         addUpdateMeshTask(p, false, urgent);
1627                 }
1628                 catch(InvalidPositionException &e){}
1629         }
1630
1631         if(nodepos.Z == blockpos_relative.Z){
1632                 try{
1633                         v3s16 p = blockpos + v3s16(0,0,-1);
1634                         addUpdateMeshTask(p, false, urgent);
1635                 }
1636                 catch(InvalidPositionException &e){}
1637         }
1638 }
1639
1640 ClientEvent *Client::getClientEvent()
1641 {
1642         FATAL_ERROR_IF(m_client_event_queue.empty(),
1643                         "Cannot getClientEvent, queue is empty.");
1644
1645         ClientEvent *event = m_client_event_queue.front();
1646         m_client_event_queue.pop();
1647         return event;
1648 }
1649
1650 const Address Client::getServerAddress()
1651 {
1652         return m_con->GetPeerAddress(PEER_ID_SERVER);
1653 }
1654
1655 float Client::mediaReceiveProgress()
1656 {
1657         if (m_media_downloader)
1658                 return m_media_downloader->getProgress();
1659
1660         return 1.0; // downloader only exists when not yet done
1661 }
1662
1663 typedef struct TextureUpdateArgs {
1664         gui::IGUIEnvironment *guienv;
1665         u64 last_time_ms;
1666         u16 last_percent;
1667         const wchar_t* text_base;
1668         ITextureSource *tsrc;
1669 } TextureUpdateArgs;
1670
1671 void Client::showUpdateProgressTexture(void *args, u32 progress, u32 max_progress)
1672 {
1673                 TextureUpdateArgs* targs = (TextureUpdateArgs*) args;
1674                 u16 cur_percent = ceil(progress / (double) max_progress * 100.);
1675
1676                 // update the loading menu -- if neccessary
1677                 bool do_draw = false;
1678                 u64 time_ms = targs->last_time_ms;
1679                 if (cur_percent != targs->last_percent) {
1680                         targs->last_percent = cur_percent;
1681                         time_ms = porting::getTimeMs();
1682                         // only draw when the user will notice something:
1683                         do_draw = (time_ms - targs->last_time_ms > 100);
1684                 }
1685
1686                 if (do_draw) {
1687                         targs->last_time_ms = time_ms;
1688                         std::basic_stringstream<wchar_t> strm;
1689                         strm << targs->text_base << " " << targs->last_percent << "%...";
1690                         m_rendering_engine->draw_load_screen(strm.str(), targs->guienv, targs->tsrc, 0,
1691                                 72 + (u16) ((18. / 100.) * (double) targs->last_percent), true);
1692                 }
1693 }
1694
1695 void Client::afterContentReceived()
1696 {
1697         infostream<<"Client::afterContentReceived() started"<<std::endl;
1698         assert(m_itemdef_received); // pre-condition
1699         assert(m_nodedef_received); // pre-condition
1700         assert(mediaReceived()); // pre-condition
1701
1702         const wchar_t* text = wgettext("Loading textures...");
1703
1704         // Clear cached pre-scaled 2D GUI images, as this cache
1705         // might have images with the same name but different
1706         // content from previous sessions.
1707         guiScalingCacheClear();
1708
1709         // Rebuild inherited images and recreate textures
1710         infostream<<"- Rebuilding images and textures"<<std::endl;
1711         m_rendering_engine->draw_load_screen(text, guienv, m_tsrc, 0, 70);
1712         m_tsrc->rebuildImagesAndTextures();
1713         delete[] text;
1714
1715         // Rebuild shaders
1716         infostream<<"- Rebuilding shaders"<<std::endl;
1717         text = wgettext("Rebuilding shaders...");
1718         m_rendering_engine->draw_load_screen(text, guienv, m_tsrc, 0, 71);
1719         m_shsrc->rebuildShaders();
1720         delete[] text;
1721
1722         // Update node aliases
1723         infostream<<"- Updating node aliases"<<std::endl;
1724         text = wgettext("Initializing nodes...");
1725         m_rendering_engine->draw_load_screen(text, guienv, m_tsrc, 0, 72);
1726         m_nodedef->updateAliases(m_itemdef);
1727         for (const auto &path : getTextureDirs()) {
1728                 TextureOverrideSource override_source(path + DIR_DELIM + "override.txt");
1729                 m_nodedef->applyTextureOverrides(override_source.getNodeTileOverrides());
1730                 m_itemdef->applyTextureOverrides(override_source.getItemTextureOverrides());
1731         }
1732         m_nodedef->setNodeRegistrationStatus(true);
1733         m_nodedef->runNodeResolveCallbacks();
1734         delete[] text;
1735
1736         // Update node textures and assign shaders to each tile
1737         infostream<<"- Updating node textures"<<std::endl;
1738         TextureUpdateArgs tu_args;
1739         tu_args.guienv = guienv;
1740         tu_args.last_time_ms = porting::getTimeMs();
1741         tu_args.last_percent = 0;
1742         tu_args.text_base =  wgettext("Initializing nodes");
1743         tu_args.tsrc = m_tsrc;
1744         m_nodedef->updateTextures(this, &tu_args);
1745         delete[] tu_args.text_base;
1746
1747         // Start mesh update thread after setting up content definitions
1748         infostream<<"- Starting mesh update thread"<<std::endl;
1749         m_mesh_update_thread.start();
1750
1751         m_state = LC_Ready;
1752         sendReady();
1753
1754         if (m_mods_loaded)
1755                 m_script->on_client_ready(m_env.getLocalPlayer());
1756
1757         text = wgettext("Done!");
1758         m_rendering_engine->draw_load_screen(text, guienv, m_tsrc, 0, 100);
1759         infostream<<"Client::afterContentReceived() done"<<std::endl;
1760         delete[] text;
1761 }
1762
1763 float Client::getRTT()
1764 {
1765         return m_con->getPeerStat(PEER_ID_SERVER,con::AVG_RTT);
1766 }
1767
1768 float Client::getCurRate()
1769 {
1770         return (m_con->getLocalStat(con::CUR_INC_RATE) +
1771                         m_con->getLocalStat(con::CUR_DL_RATE));
1772 }
1773
1774 void Client::makeScreenshot()
1775 {
1776         irr::video::IVideoDriver *driver = m_rendering_engine->get_video_driver();
1777         irr::video::IImage* const raw_image = driver->createScreenShot();
1778
1779         if (!raw_image)
1780                 return;
1781
1782         time_t t = time(NULL);
1783         struct tm *tm = localtime(&t);
1784
1785         char timetstamp_c[64];
1786         strftime(timetstamp_c, sizeof(timetstamp_c), "%Y%m%d_%H%M%S", tm);
1787
1788         std::string screenshot_dir;
1789
1790         if (fs::IsPathAbsolute(g_settings->get("screenshot_path")))
1791                 screenshot_dir = g_settings->get("screenshot_path");
1792         else
1793                 screenshot_dir = porting::path_user + DIR_DELIM + g_settings->get("screenshot_path");
1794
1795         std::string filename_base = screenshot_dir
1796                         + DIR_DELIM
1797                         + std::string("screenshot_")
1798                         + std::string(timetstamp_c);
1799         std::string filename_ext = "." + g_settings->get("screenshot_format");
1800         std::string filename;
1801
1802         // Create the directory if it doesn't already exist.
1803         // Otherwise, saving the screenshot would fail.
1804         fs::CreateDir(screenshot_dir);
1805
1806         u32 quality = (u32)g_settings->getS32("screenshot_quality");
1807         quality = MYMIN(MYMAX(quality, 0), 100) / 100.0 * 255;
1808
1809         // Try to find a unique filename
1810         unsigned serial = 0;
1811
1812         while (serial < SCREENSHOT_MAX_SERIAL_TRIES) {
1813                 filename = filename_base + (serial > 0 ? ("_" + itos(serial)) : "") + filename_ext;
1814                 std::ifstream tmp(filename.c_str());
1815                 if (!tmp.good())
1816                         break;  // File did not apparently exist, we'll go with it
1817                 serial++;
1818         }
1819
1820         if (serial == SCREENSHOT_MAX_SERIAL_TRIES) {
1821                 infostream << "Could not find suitable filename for screenshot" << std::endl;
1822         } else {
1823                 irr::video::IImage* const image =
1824                                 driver->createImage(video::ECF_R8G8B8, raw_image->getDimension());
1825
1826                 if (image) {
1827                         raw_image->copyTo(image);
1828
1829                         std::ostringstream sstr;
1830                         if (driver->writeImageToFile(image, filename.c_str(), quality)) {
1831                                 sstr << "Saved screenshot to '" << filename << "'";
1832                         } else {
1833                                 sstr << "Failed to save screenshot '" << filename << "'";
1834                         }
1835                         pushToChatQueue(new ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
1836                                         utf8_to_wide(sstr.str())));
1837                         infostream << sstr.str() << std::endl;
1838                         image->drop();
1839                 }
1840         }
1841
1842         raw_image->drop();
1843 }
1844
1845 bool Client::shouldShowMinimap() const
1846 {
1847         return !m_minimap_disabled_by_server;
1848 }
1849
1850 void Client::pushToEventQueue(ClientEvent *event)
1851 {
1852         m_client_event_queue.push(event);
1853 }
1854
1855 void Client::showMinimap(const bool show)
1856 {
1857         m_game_ui->showMinimap(show);
1858 }
1859
1860 // IGameDef interface
1861 // Under envlock
1862 IItemDefManager* Client::getItemDefManager()
1863 {
1864         return m_itemdef;
1865 }
1866 const NodeDefManager* Client::getNodeDefManager()
1867 {
1868         return m_nodedef;
1869 }
1870 ICraftDefManager* Client::getCraftDefManager()
1871 {
1872         return NULL;
1873         //return m_craftdef;
1874 }
1875 ITextureSource* Client::getTextureSource()
1876 {
1877         return m_tsrc;
1878 }
1879 IWritableShaderSource* Client::getShaderSource()
1880 {
1881         return m_shsrc;
1882 }
1883
1884 u16 Client::allocateUnknownNodeId(const std::string &name)
1885 {
1886         errorstream << "Client::allocateUnknownNodeId(): "
1887                         << "Client cannot allocate node IDs" << std::endl;
1888         FATAL_ERROR("Client allocated unknown node");
1889
1890         return CONTENT_IGNORE;
1891 }
1892 ISoundManager* Client::getSoundManager()
1893 {
1894         return m_sound;
1895 }
1896 MtEventManager* Client::getEventManager()
1897 {
1898         return m_event;
1899 }
1900
1901 ParticleManager* Client::getParticleManager()
1902 {
1903         return &m_particle_manager;
1904 }
1905
1906 scene::IAnimatedMesh* Client::getMesh(const std::string &filename, bool cache)
1907 {
1908         StringMap::const_iterator it = m_mesh_data.find(filename);
1909         if (it == m_mesh_data.end()) {
1910                 errorstream << "Client::getMesh(): Mesh not found: \"" << filename
1911                         << "\"" << std::endl;
1912                 return NULL;
1913         }
1914         const std::string &data    = it->second;
1915
1916         // Create the mesh, remove it from cache and return it
1917         // This allows unique vertex colors and other properties for each instance
1918         io::IReadFile *rfile = m_rendering_engine->get_filesystem()->createMemoryReadFile(
1919                         data.c_str(), data.size(), filename.c_str());
1920         FATAL_ERROR_IF(!rfile, "Could not create/open RAM file");
1921
1922         scene::IAnimatedMesh *mesh = m_rendering_engine->get_scene_manager()->getMesh(rfile);
1923         rfile->drop();
1924         if (!mesh)
1925                 return nullptr;
1926         mesh->grab();
1927         if (!cache)
1928                 m_rendering_engine->removeMesh(mesh);
1929         return mesh;
1930 }
1931
1932 const std::string* Client::getModFile(std::string filename)
1933 {
1934         // strip dir delimiter from beginning of path
1935         auto pos = filename.find_first_of(':');
1936         if (pos == std::string::npos)
1937                 return nullptr;
1938         pos++;
1939         auto pos2 = filename.find_first_not_of('/', pos);
1940         if (pos2 > pos)
1941                 filename.erase(pos, pos2 - pos);
1942
1943         StringMap::const_iterator it = m_mod_vfs.find(filename);
1944         if (it == m_mod_vfs.end())
1945                 return nullptr;
1946         return &it->second;
1947 }
1948
1949 bool Client::registerModStorage(ModMetadata *storage)
1950 {
1951         if (m_mod_storages.find(storage->getModName()) != m_mod_storages.end()) {
1952                 errorstream << "Unable to register same mod storage twice. Storage name: "
1953                                 << storage->getModName() << std::endl;
1954                 return false;
1955         }
1956
1957         m_mod_storages[storage->getModName()] = storage;
1958         return true;
1959 }
1960
1961 void Client::unregisterModStorage(const std::string &name)
1962 {
1963         std::unordered_map<std::string, ModMetadata *>::const_iterator it =
1964                 m_mod_storages.find(name);
1965         if (it != m_mod_storages.end()) {
1966                 // Save unconditionaly on unregistration
1967                 it->second->save(getModStoragePath());
1968                 m_mod_storages.erase(name);
1969         }
1970 }
1971
1972 std::string Client::getModStoragePath() const
1973 {
1974         return porting::path_user + DIR_DELIM + "client" + DIR_DELIM + "mod_storage";
1975 }
1976
1977 /*
1978  * Mod channels
1979  */
1980
1981 bool Client::joinModChannel(const std::string &channel)
1982 {
1983         if (m_modchannel_mgr->channelRegistered(channel))
1984                 return false;
1985
1986         NetworkPacket pkt(TOSERVER_MODCHANNEL_JOIN, 2 + channel.size());
1987         pkt << channel;
1988         Send(&pkt);
1989
1990         m_modchannel_mgr->joinChannel(channel, 0);
1991         return true;
1992 }
1993
1994 bool Client::leaveModChannel(const std::string &channel)
1995 {
1996         if (!m_modchannel_mgr->channelRegistered(channel))
1997                 return false;
1998
1999         NetworkPacket pkt(TOSERVER_MODCHANNEL_LEAVE, 2 + channel.size());
2000         pkt << channel;
2001         Send(&pkt);
2002
2003         m_modchannel_mgr->leaveChannel(channel, 0);
2004         return true;
2005 }
2006
2007 bool Client::sendModChannelMessage(const std::string &channel, const std::string &message)
2008 {
2009         if (!m_modchannel_mgr->canWriteOnChannel(channel))
2010                 return false;
2011
2012         if (message.size() > STRING_MAX_LEN) {
2013                 warningstream << "ModChannel message too long, dropping before sending "
2014                                 << " (" << message.size() << " > " << STRING_MAX_LEN << ", channel: "
2015                                 << channel << ")" << std::endl;
2016                 return false;
2017         }
2018
2019         // @TODO: do some client rate limiting
2020         NetworkPacket pkt(TOSERVER_MODCHANNEL_MSG, 2 + channel.size() + 2 + message.size());
2021         pkt << channel << message;
2022         Send(&pkt);
2023         return true;
2024 }
2025
2026 ModChannel* Client::getModChannel(const std::string &channel)
2027 {
2028         return m_modchannel_mgr->getModChannel(channel);
2029 }