]> git.lizzy.rs Git - minetest.git/blob - src/client/client.cpp
Avoid unnecessary copies during media/mesh loading
[minetest.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 #if IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR > 8
667                 io::IReadFile *rfile = irrfs->createMemoryReadFile(
668                                 data.c_str(), data.size(), "_tempreadfile");
669 #else
670                 // Silly irrlicht's const-incorrectness
671                 Buffer<char> data_rw(data.c_str(), data.size());
672                 io::IReadFile *rfile = irrfs->createMemoryReadFile(
673                                 *data_rw, data_rw.getSize(), "_tempreadfile");
674 #endif
675
676                 FATAL_ERROR_IF(!rfile, "Could not create irrlicht memory file.");
677
678                 // Read image
679                 video::IImage *img = vdrv->createImageFromFile(rfile);
680                 if (!img) {
681                         errorstream<<"Client: Cannot create image from data of "
682                                         <<"file \""<<filename<<"\""<<std::endl;
683                         rfile->drop();
684                         return false;
685                 }
686
687                 m_tsrc->insertSourceImage(filename, img);
688                 img->drop();
689                 rfile->drop();
690                 return true;
691         }
692
693         const char *sound_ext[] = {
694                 ".0.ogg", ".1.ogg", ".2.ogg", ".3.ogg", ".4.ogg",
695                 ".5.ogg", ".6.ogg", ".7.ogg", ".8.ogg", ".9.ogg",
696                 ".ogg", NULL
697         };
698         name = removeStringEnd(filename, sound_ext);
699         if (!name.empty()) {
700                 TRACESTREAM(<< "Client: Attempting to load sound "
701                         << "file \"" << filename << "\"" << std::endl);
702                 return m_sound->loadSoundData(name, data);
703         }
704
705         const char *model_ext[] = {
706                 ".x", ".b3d", ".md2", ".obj",
707                 NULL
708         };
709         name = removeStringEnd(filename, model_ext);
710         if (!name.empty()) {
711                 verbosestream<<"Client: Storing model into memory: "
712                                 <<"\""<<filename<<"\""<<std::endl;
713                 if(m_mesh_data.count(filename))
714                         errorstream<<"Multiple models with name \""<<filename.c_str()
715                                         <<"\" found; replacing previous model"<<std::endl;
716                 m_mesh_data[filename] = data;
717                 return true;
718         }
719
720         const char *translate_ext[] = {
721                 ".tr", NULL
722         };
723         name = removeStringEnd(filename, translate_ext);
724         if (!name.empty()) {
725                 if (from_media_push)
726                         return false;
727                 TRACESTREAM(<< "Client: Loading translation: "
728                                 << "\"" << filename << "\"" << std::endl);
729                 g_client_translations->loadTranslation(data);
730                 return true;
731         }
732
733         errorstream << "Client: Don't know how to load file \""
734                 << filename << "\"" << std::endl;
735         return false;
736 }
737
738 // Virtual methods from con::PeerHandler
739 void Client::peerAdded(con::Peer *peer)
740 {
741         infostream << "Client::peerAdded(): peer->id="
742                         << peer->id << std::endl;
743 }
744 void Client::deletingPeer(con::Peer *peer, bool timeout)
745 {
746         infostream << "Client::deletingPeer(): "
747                         "Server Peer is getting deleted "
748                         << "(timeout=" << timeout << ")" << std::endl;
749
750         if (timeout) {
751                 m_access_denied = true;
752                 m_access_denied_reason = gettext("Connection timed out.");
753         }
754 }
755
756 /*
757         u16 command
758         u16 number of files requested
759         for each file {
760                 u16 length of name
761                 string name
762         }
763 */
764 void Client::request_media(const std::vector<std::string> &file_requests)
765 {
766         std::ostringstream os(std::ios_base::binary);
767         writeU16(os, TOSERVER_REQUEST_MEDIA);
768         size_t file_requests_size = file_requests.size();
769
770         FATAL_ERROR_IF(file_requests_size > 0xFFFF, "Unsupported number of file requests");
771
772         // Packet dynamicly resized
773         NetworkPacket pkt(TOSERVER_REQUEST_MEDIA, 2 + 0);
774
775         pkt << (u16) (file_requests_size & 0xFFFF);
776
777         for (const std::string &file_request : file_requests) {
778                 pkt << file_request;
779         }
780
781         Send(&pkt);
782
783         infostream << "Client: Sending media request list to server ("
784                         << file_requests.size() << " files. packet size)" << std::endl;
785 }
786
787 void Client::initLocalMapSaving(const Address &address,
788                 const std::string &hostname,
789                 bool is_local_server)
790 {
791         if (!g_settings->getBool("enable_local_map_saving") || is_local_server) {
792                 return;
793         }
794
795         std::string world_path;
796 #define set_world_path(hostname) \
797         world_path = porting::path_user \
798                 + DIR_DELIM + "worlds" \
799                 + DIR_DELIM + "server_" \
800                 + hostname + "_" + std::to_string(address.getPort());
801
802         set_world_path(hostname);
803         if (!fs::IsDir(world_path)) {
804                 std::string hostname_escaped = hostname;
805                 str_replace(hostname_escaped, ':', '_');
806                 set_world_path(hostname_escaped);
807         }
808 #undef set_world_path
809         fs::CreateAllDirs(world_path);
810
811         m_localdb = new MapDatabaseSQLite3(world_path);
812         m_localdb->beginSave();
813         actionstream << "Local map saving started, map will be saved at '" << world_path << "'" << std::endl;
814 }
815
816 void Client::ReceiveAll()
817 {
818         NetworkPacket pkt;
819         u64 start_ms = porting::getTimeMs();
820         const u64 budget = 100;
821         for(;;) {
822                 // Limit time even if there would be huge amounts of data to
823                 // process
824                 if (porting::getTimeMs() > start_ms + budget) {
825                         infostream << "Client::ReceiveAll(): "
826                                         "Packet processing budget exceeded." << std::endl;
827                         break;
828                 }
829
830                 pkt.clear();
831                 try {
832                         if (!m_con->TryReceive(&pkt))
833                                 break;
834                         ProcessData(&pkt);
835                 } catch (const con::InvalidIncomingDataException &e) {
836                         infostream << "Client::ReceiveAll(): "
837                                         "InvalidIncomingDataException: what()="
838                                          << e.what() << std::endl;
839                 }
840         }
841 }
842
843 inline void Client::handleCommand(NetworkPacket* pkt)
844 {
845         const ToClientCommandHandler& opHandle = toClientCommandTable[pkt->getCommand()];
846         (this->*opHandle.handler)(pkt);
847 }
848
849 /*
850         sender_peer_id given to this shall be quaranteed to be a valid peer
851 */
852 void Client::ProcessData(NetworkPacket *pkt)
853 {
854         ToClientCommand command = (ToClientCommand) pkt->getCommand();
855         u32 sender_peer_id = pkt->getPeerId();
856
857         //infostream<<"Client: received command="<<command<<std::endl;
858         m_packetcounter.add((u16)command);
859         g_profiler->graphAdd("client_received_packets", 1);
860
861         /*
862                 If this check is removed, be sure to change the queue
863                 system to know the ids
864         */
865         if(sender_peer_id != PEER_ID_SERVER) {
866                 infostream << "Client::ProcessData(): Discarding data not "
867                         "coming from server: peer_id=" << sender_peer_id
868                         << std::endl;
869                 return;
870         }
871
872         // Command must be handled into ToClientCommandHandler
873         if (command >= TOCLIENT_NUM_MSG_TYPES) {
874                 infostream << "Client: Ignoring unknown command "
875                         << command << std::endl;
876                 return;
877         }
878
879         /*
880          * Those packets are handled before m_server_ser_ver is set, it's normal
881          * But we must use the new ToClientConnectionState in the future,
882          * as a byte mask
883          */
884         if(toClientCommandTable[command].state == TOCLIENT_STATE_NOT_CONNECTED) {
885                 handleCommand(pkt);
886                 return;
887         }
888
889         if(m_server_ser_ver == SER_FMT_VER_INVALID) {
890                 infostream << "Client: Server serialization"
891                                 " format invalid or not initialized."
892                                 " Skipping incoming command=" << command << std::endl;
893                 return;
894         }
895
896         /*
897           Handle runtime commands
898         */
899
900         handleCommand(pkt);
901 }
902
903 void Client::Send(NetworkPacket* pkt)
904 {
905         m_con->Send(PEER_ID_SERVER,
906                 serverCommandFactoryTable[pkt->getCommand()].channel,
907                 pkt,
908                 serverCommandFactoryTable[pkt->getCommand()].reliable);
909 }
910
911 // Will fill up 12 + 12 + 4 + 4 + 4 bytes
912 void writePlayerPos(LocalPlayer *myplayer, ClientMap *clientMap, NetworkPacket *pkt)
913 {
914         v3f pf           = myplayer->getPosition() * 100;
915         v3f sf           = myplayer->getSpeed() * 100;
916         s32 pitch        = myplayer->getPitch() * 100;
917         s32 yaw          = myplayer->getYaw() * 100;
918         u32 keyPressed   = myplayer->keyPressed;
919         // scaled by 80, so that pi can fit into a u8
920         u8 fov           = clientMap->getCameraFov() * 80;
921         u8 wanted_range  = MYMIN(255,
922                         std::ceil(clientMap->getControl().wanted_range / MAP_BLOCKSIZE));
923
924         v3s32 position(pf.X, pf.Y, pf.Z);
925         v3s32 speed(sf.X, sf.Y, sf.Z);
926
927         /*
928                 Format:
929                 [0] v3s32 position*100
930                 [12] v3s32 speed*100
931                 [12+12] s32 pitch*100
932                 [12+12+4] s32 yaw*100
933                 [12+12+4+4] u32 keyPressed
934                 [12+12+4+4+4] u8 fov*80
935                 [12+12+4+4+4+1] u8 ceil(wanted_range / MAP_BLOCKSIZE)
936         */
937         *pkt << position << speed << pitch << yaw << keyPressed;
938         *pkt << fov << wanted_range;
939 }
940
941 void Client::interact(InteractAction action, const PointedThing& pointed)
942 {
943         if(m_state != LC_Ready) {
944                 errorstream << "Client::interact() "
945                                 "Canceled (not connected)"
946                                 << std::endl;
947                 return;
948         }
949
950         LocalPlayer *myplayer = m_env.getLocalPlayer();
951         if (myplayer == NULL)
952                 return;
953
954         /*
955                 [0] u16 command
956                 [2] u8 action
957                 [3] u16 item
958                 [5] u32 length of the next item (plen)
959                 [9] serialized PointedThing
960                 [9 + plen] player position information
961         */
962
963         NetworkPacket pkt(TOSERVER_INTERACT, 1 + 2 + 0);
964
965         pkt << (u8)action;
966         pkt << myplayer->getWieldIndex();
967
968         std::ostringstream tmp_os(std::ios::binary);
969         pointed.serialize(tmp_os);
970
971         pkt.putLongString(tmp_os.str());
972
973         writePlayerPos(myplayer, &m_env.getClientMap(), &pkt);
974
975         Send(&pkt);
976 }
977
978 void Client::deleteAuthData()
979 {
980         if (!m_auth_data)
981                 return;
982
983         switch (m_chosen_auth_mech) {
984                 case AUTH_MECHANISM_FIRST_SRP:
985                         break;
986                 case AUTH_MECHANISM_SRP:
987                 case AUTH_MECHANISM_LEGACY_PASSWORD:
988                         srp_user_delete((SRPUser *) m_auth_data);
989                         m_auth_data = NULL;
990                         break;
991                 case AUTH_MECHANISM_NONE:
992                         break;
993         }
994         m_chosen_auth_mech = AUTH_MECHANISM_NONE;
995 }
996
997
998 AuthMechanism Client::choseAuthMech(const u32 mechs)
999 {
1000         if (mechs & AUTH_MECHANISM_SRP)
1001                 return AUTH_MECHANISM_SRP;
1002
1003         if (mechs & AUTH_MECHANISM_FIRST_SRP)
1004                 return AUTH_MECHANISM_FIRST_SRP;
1005
1006         if (mechs & AUTH_MECHANISM_LEGACY_PASSWORD)
1007                 return AUTH_MECHANISM_LEGACY_PASSWORD;
1008
1009         return AUTH_MECHANISM_NONE;
1010 }
1011
1012 void Client::sendInit(const std::string &playerName)
1013 {
1014         NetworkPacket pkt(TOSERVER_INIT, 1 + 2 + 2 + (1 + playerName.size()));
1015
1016         // we don't support network compression yet
1017         u16 supp_comp_modes = NETPROTO_COMPRESSION_NONE;
1018
1019         pkt << (u8) SER_FMT_VER_HIGHEST_READ << (u16) supp_comp_modes;
1020         pkt << (u16) CLIENT_PROTOCOL_VERSION_MIN << (u16) CLIENT_PROTOCOL_VERSION_MAX;
1021         pkt << playerName;
1022
1023         Send(&pkt);
1024 }
1025
1026 void Client::promptConfirmRegistration(AuthMechanism chosen_auth_mechanism)
1027 {
1028         m_chosen_auth_mech = chosen_auth_mechanism;
1029         m_is_registration_confirmation_state = true;
1030 }
1031
1032 void Client::confirmRegistration()
1033 {
1034         m_is_registration_confirmation_state = false;
1035         startAuth(m_chosen_auth_mech);
1036 }
1037
1038 void Client::startAuth(AuthMechanism chosen_auth_mechanism)
1039 {
1040         m_chosen_auth_mech = chosen_auth_mechanism;
1041
1042         switch (chosen_auth_mechanism) {
1043                 case AUTH_MECHANISM_FIRST_SRP: {
1044                         // send srp verifier to server
1045                         std::string verifier;
1046                         std::string salt;
1047                         generate_srp_verifier_and_salt(getPlayerName(), m_password,
1048                                 &verifier, &salt);
1049
1050                         NetworkPacket resp_pkt(TOSERVER_FIRST_SRP, 0);
1051                         resp_pkt << salt << verifier << (u8)((m_password.empty()) ? 1 : 0);
1052
1053                         Send(&resp_pkt);
1054                         break;
1055                 }
1056                 case AUTH_MECHANISM_SRP:
1057                 case AUTH_MECHANISM_LEGACY_PASSWORD: {
1058                         u8 based_on = 1;
1059
1060                         if (chosen_auth_mechanism == AUTH_MECHANISM_LEGACY_PASSWORD) {
1061                                 m_password = translate_password(getPlayerName(), m_password);
1062                                 based_on = 0;
1063                         }
1064
1065                         std::string playername_u = lowercase(getPlayerName());
1066                         m_auth_data = srp_user_new(SRP_SHA256, SRP_NG_2048,
1067                                 getPlayerName().c_str(), playername_u.c_str(),
1068                                 (const unsigned char *) m_password.c_str(),
1069                                 m_password.length(), NULL, NULL);
1070                         char *bytes_A = 0;
1071                         size_t len_A = 0;
1072                         SRP_Result res = srp_user_start_authentication(
1073                                 (struct SRPUser *) m_auth_data, NULL, NULL, 0,
1074                                 (unsigned char **) &bytes_A, &len_A);
1075                         FATAL_ERROR_IF(res != SRP_OK, "Creating local SRP user failed.");
1076
1077                         NetworkPacket resp_pkt(TOSERVER_SRP_BYTES_A, 0);
1078                         resp_pkt << std::string(bytes_A, len_A) << based_on;
1079                         Send(&resp_pkt);
1080                         break;
1081                 }
1082                 case AUTH_MECHANISM_NONE:
1083                         break; // not handled in this method
1084         }
1085 }
1086
1087 void Client::sendDeletedBlocks(std::vector<v3s16> &blocks)
1088 {
1089         NetworkPacket pkt(TOSERVER_DELETEDBLOCKS, 1 + sizeof(v3s16) * blocks.size());
1090
1091         pkt << (u8) blocks.size();
1092
1093         for (const v3s16 &block : blocks) {
1094                 pkt << block;
1095         }
1096
1097         Send(&pkt);
1098 }
1099
1100 void Client::sendGotBlocks(const std::vector<v3s16> &blocks)
1101 {
1102         NetworkPacket pkt(TOSERVER_GOTBLOCKS, 1 + 6 * blocks.size());
1103         pkt << (u8) blocks.size();
1104         for (const v3s16 &block : blocks)
1105                 pkt << block;
1106
1107         Send(&pkt);
1108 }
1109
1110 void Client::sendRemovedSounds(std::vector<s32> &soundList)
1111 {
1112         size_t server_ids = soundList.size();
1113         assert(server_ids <= 0xFFFF);
1114
1115         NetworkPacket pkt(TOSERVER_REMOVED_SOUNDS, 2 + server_ids * 4);
1116
1117         pkt << (u16) (server_ids & 0xFFFF);
1118
1119         for (s32 sound_id : soundList)
1120                 pkt << sound_id;
1121
1122         Send(&pkt);
1123 }
1124
1125 void Client::sendNodemetaFields(v3s16 p, const std::string &formname,
1126                 const StringMap &fields)
1127 {
1128         size_t fields_size = fields.size();
1129
1130         FATAL_ERROR_IF(fields_size > 0xFFFF, "Unsupported number of nodemeta fields");
1131
1132         NetworkPacket pkt(TOSERVER_NODEMETA_FIELDS, 0);
1133
1134         pkt << p << formname << (u16) (fields_size & 0xFFFF);
1135
1136         StringMap::const_iterator it;
1137         for (it = fields.begin(); it != fields.end(); ++it) {
1138                 const std::string &name = it->first;
1139                 const std::string &value = it->second;
1140                 pkt << name;
1141                 pkt.putLongString(value);
1142         }
1143
1144         Send(&pkt);
1145 }
1146
1147 void Client::sendInventoryFields(const std::string &formname,
1148                 const StringMap &fields)
1149 {
1150         size_t fields_size = fields.size();
1151         FATAL_ERROR_IF(fields_size > 0xFFFF, "Unsupported number of inventory fields");
1152
1153         NetworkPacket pkt(TOSERVER_INVENTORY_FIELDS, 0);
1154         pkt << formname << (u16) (fields_size & 0xFFFF);
1155
1156         StringMap::const_iterator it;
1157         for (it = fields.begin(); it != fields.end(); ++it) {
1158                 const std::string &name  = it->first;
1159                 const std::string &value = it->second;
1160                 pkt << name;
1161                 pkt.putLongString(value);
1162         }
1163
1164         Send(&pkt);
1165 }
1166
1167 void Client::sendInventoryAction(InventoryAction *a)
1168 {
1169         std::ostringstream os(std::ios_base::binary);
1170
1171         a->serialize(os);
1172
1173         // Make data buffer
1174         std::string s = os.str();
1175
1176         NetworkPacket pkt(TOSERVER_INVENTORY_ACTION, s.size());
1177         pkt.putRawString(s.c_str(),s.size());
1178
1179         Send(&pkt);
1180 }
1181
1182 bool Client::canSendChatMessage() const
1183 {
1184         u32 now = time(NULL);
1185         float time_passed = now - m_last_chat_message_sent;
1186
1187         float virt_chat_message_allowance = m_chat_message_allowance + time_passed *
1188                         (CLIENT_CHAT_MESSAGE_LIMIT_PER_10S / 8.0f);
1189
1190         if (virt_chat_message_allowance < 1.0f)
1191                 return false;
1192
1193         return true;
1194 }
1195
1196 void Client::sendChatMessage(const std::wstring &message)
1197 {
1198         const s16 max_queue_size = g_settings->getS16("max_out_chat_queue_size");
1199         if (canSendChatMessage()) {
1200                 u32 now = time(NULL);
1201                 float time_passed = now - m_last_chat_message_sent;
1202                 m_last_chat_message_sent = now;
1203
1204                 m_chat_message_allowance += time_passed * (CLIENT_CHAT_MESSAGE_LIMIT_PER_10S / 8.0f);
1205                 if (m_chat_message_allowance > CLIENT_CHAT_MESSAGE_LIMIT_PER_10S)
1206                         m_chat_message_allowance = CLIENT_CHAT_MESSAGE_LIMIT_PER_10S;
1207
1208                 m_chat_message_allowance -= 1.0f;
1209
1210                 NetworkPacket pkt(TOSERVER_CHAT_MESSAGE, 2 + message.size() * sizeof(u16));
1211
1212                 pkt << message;
1213
1214                 Send(&pkt);
1215         } else if (m_out_chat_queue.size() < (u16) max_queue_size || max_queue_size == -1) {
1216                 m_out_chat_queue.push(message);
1217         } else {
1218                 infostream << "Could not queue chat message because maximum out chat queue size ("
1219                                 << max_queue_size << ") is reached." << std::endl;
1220         }
1221 }
1222
1223 void Client::clearOutChatQueue()
1224 {
1225         m_out_chat_queue = std::queue<std::wstring>();
1226 }
1227
1228 void Client::sendChangePassword(const std::string &oldpassword,
1229         const std::string &newpassword)
1230 {
1231         LocalPlayer *player = m_env.getLocalPlayer();
1232         if (player == NULL)
1233                 return;
1234
1235         // get into sudo mode and then send new password to server
1236         m_password = oldpassword;
1237         m_new_password = newpassword;
1238         startAuth(choseAuthMech(m_sudo_auth_methods));
1239 }
1240
1241
1242 void Client::sendDamage(u16 damage)
1243 {
1244         NetworkPacket pkt(TOSERVER_DAMAGE, sizeof(u16));
1245         pkt << damage;
1246         Send(&pkt);
1247 }
1248
1249 void Client::sendRespawn()
1250 {
1251         NetworkPacket pkt(TOSERVER_RESPAWN, 0);
1252         Send(&pkt);
1253 }
1254
1255 void Client::sendReady()
1256 {
1257         NetworkPacket pkt(TOSERVER_CLIENT_READY,
1258                         1 + 1 + 1 + 1 + 2 + sizeof(char) * strlen(g_version_hash) + 2);
1259
1260         pkt << (u8) VERSION_MAJOR << (u8) VERSION_MINOR << (u8) VERSION_PATCH
1261                 << (u8) 0 << (u16) strlen(g_version_hash);
1262
1263         pkt.putRawString(g_version_hash, (u16) strlen(g_version_hash));
1264         pkt << (u16)FORMSPEC_API_VERSION;
1265         Send(&pkt);
1266 }
1267
1268 void Client::sendPlayerPos()
1269 {
1270         LocalPlayer *player = m_env.getLocalPlayer();
1271         if (!player)
1272                 return;
1273
1274         ClientMap &map = m_env.getClientMap();
1275         u8 camera_fov   = map.getCameraFov();
1276         u8 wanted_range = map.getControl().wanted_range;
1277
1278         // Save bandwidth by only updating position when
1279         // player is not dead and something changed
1280
1281         if (m_activeobjects_received && player->isDead())
1282                 return;
1283
1284         if (
1285                         player->last_position     == player->getPosition() &&
1286                         player->last_speed        == player->getSpeed()    &&
1287                         player->last_pitch        == player->getPitch()    &&
1288                         player->last_yaw          == player->getYaw()      &&
1289                         player->last_keyPressed   == player->keyPressed    &&
1290                         player->last_camera_fov   == camera_fov            &&
1291                         player->last_wanted_range == wanted_range)
1292                 return;
1293
1294         player->last_position     = player->getPosition();
1295         player->last_speed        = player->getSpeed();
1296         player->last_pitch        = player->getPitch();
1297         player->last_yaw          = player->getYaw();
1298         player->last_keyPressed   = player->keyPressed;
1299         player->last_camera_fov   = camera_fov;
1300         player->last_wanted_range = wanted_range;
1301
1302         NetworkPacket pkt(TOSERVER_PLAYERPOS, 12 + 12 + 4 + 4 + 4 + 1 + 1);
1303
1304         writePlayerPos(player, &map, &pkt);
1305
1306         Send(&pkt);
1307 }
1308
1309 void Client::removeNode(v3s16 p)
1310 {
1311         std::map<v3s16, MapBlock*> modified_blocks;
1312
1313         try {
1314                 m_env.getMap().removeNodeAndUpdate(p, modified_blocks);
1315         }
1316         catch(InvalidPositionException &e) {
1317         }
1318
1319         for (const auto &modified_block : modified_blocks) {
1320                 addUpdateMeshTaskWithEdge(modified_block.first, false, true);
1321         }
1322 }
1323
1324 /**
1325  * Helper function for Client Side Modding
1326  * CSM restrictions are applied there, this should not be used for core engine
1327  * @param p
1328  * @param is_valid_position
1329  * @return
1330  */
1331 MapNode Client::CSMGetNode(v3s16 p, bool *is_valid_position)
1332 {
1333         if (checkCSMRestrictionFlag(CSMRestrictionFlags::CSM_RF_LOOKUP_NODES)) {
1334                 v3s16 ppos = floatToInt(m_env.getLocalPlayer()->getPosition(), BS);
1335                 if ((u32) ppos.getDistanceFrom(p) > m_csm_restriction_noderange) {
1336                         *is_valid_position = false;
1337                         return {};
1338                 }
1339         }
1340         return m_env.getMap().getNode(p, is_valid_position);
1341 }
1342
1343 int Client::CSMClampRadius(v3s16 pos, int radius)
1344 {
1345         if (!checkCSMRestrictionFlag(CSMRestrictionFlags::CSM_RF_LOOKUP_NODES))
1346                 return radius;
1347         // This is approximate and will cause some allowed nodes to be excluded
1348         v3s16 ppos = floatToInt(m_env.getLocalPlayer()->getPosition(), BS);
1349         u32 distance = ppos.getDistanceFrom(pos);
1350         if (distance >= m_csm_restriction_noderange)
1351                 return 0;
1352         return std::min<int>(radius, m_csm_restriction_noderange - distance);
1353 }
1354
1355 v3s16 Client::CSMClampPos(v3s16 pos)
1356 {
1357         if (!checkCSMRestrictionFlag(CSMRestrictionFlags::CSM_RF_LOOKUP_NODES))
1358                 return pos;
1359         v3s16 ppos = floatToInt(m_env.getLocalPlayer()->getPosition(), BS);
1360         const int range = m_csm_restriction_noderange;
1361         return v3s16(
1362                 core::clamp<int>(pos.X, (int)ppos.X - range, (int)ppos.X + range),
1363                 core::clamp<int>(pos.Y, (int)ppos.Y - range, (int)ppos.Y + range),
1364                 core::clamp<int>(pos.Z, (int)ppos.Z - range, (int)ppos.Z + range)
1365         );
1366 }
1367
1368 void Client::addNode(v3s16 p, MapNode n, bool remove_metadata)
1369 {
1370         //TimeTaker timer1("Client::addNode()");
1371
1372         std::map<v3s16, MapBlock*> modified_blocks;
1373
1374         try {
1375                 //TimeTaker timer3("Client::addNode(): addNodeAndUpdate");
1376                 m_env.getMap().addNodeAndUpdate(p, n, modified_blocks, remove_metadata);
1377         }
1378         catch(InvalidPositionException &e) {
1379         }
1380
1381         for (const auto &modified_block : modified_blocks) {
1382                 addUpdateMeshTaskWithEdge(modified_block.first, false, true);
1383         }
1384 }
1385
1386 void Client::setPlayerControl(PlayerControl &control)
1387 {
1388         LocalPlayer *player = m_env.getLocalPlayer();
1389         assert(player);
1390         player->control = control;
1391 }
1392
1393 void Client::setPlayerItem(u16 item)
1394 {
1395         m_env.getLocalPlayer()->setWieldIndex(item);
1396         m_update_wielded_item = true;
1397
1398         NetworkPacket pkt(TOSERVER_PLAYERITEM, 2);
1399         pkt << item;
1400         Send(&pkt);
1401 }
1402
1403 // Returns true once after the inventory of the local player
1404 // has been updated from the server.
1405 bool Client::updateWieldedItem()
1406 {
1407         if (!m_update_wielded_item)
1408                 return false;
1409
1410         m_update_wielded_item = false;
1411
1412         LocalPlayer *player = m_env.getLocalPlayer();
1413         assert(player);
1414         if (auto *list = player->inventory.getList("main"))
1415                 list->setModified(false);
1416         if (auto *list = player->inventory.getList("hand"))
1417                 list->setModified(false);
1418
1419         return true;
1420 }
1421
1422 Inventory* Client::getInventory(const InventoryLocation &loc)
1423 {
1424         switch(loc.type){
1425         case InventoryLocation::UNDEFINED:
1426         {}
1427         break;
1428         case InventoryLocation::CURRENT_PLAYER:
1429         {
1430                 LocalPlayer *player = m_env.getLocalPlayer();
1431                 assert(player);
1432                 return &player->inventory;
1433         }
1434         break;
1435         case InventoryLocation::PLAYER:
1436         {
1437                 // Check if we are working with local player inventory
1438                 LocalPlayer *player = m_env.getLocalPlayer();
1439                 if (!player || strcmp(player->getName(), loc.name.c_str()) != 0)
1440                         return NULL;
1441                 return &player->inventory;
1442         }
1443         break;
1444         case InventoryLocation::NODEMETA:
1445         {
1446                 NodeMetadata *meta = m_env.getMap().getNodeMetadata(loc.p);
1447                 if(!meta)
1448                         return NULL;
1449                 return meta->getInventory();
1450         }
1451         break;
1452         case InventoryLocation::DETACHED:
1453         {
1454                 if (m_detached_inventories.count(loc.name) == 0)
1455                         return NULL;
1456                 return m_detached_inventories[loc.name];
1457         }
1458         break;
1459         default:
1460                 FATAL_ERROR("Invalid inventory location type.");
1461                 break;
1462         }
1463         return NULL;
1464 }
1465
1466 void Client::inventoryAction(InventoryAction *a)
1467 {
1468         /*
1469                 Send it to the server
1470         */
1471         sendInventoryAction(a);
1472
1473         /*
1474                 Predict some local inventory changes
1475         */
1476         a->clientApply(this, this);
1477
1478         // Remove it
1479         delete a;
1480 }
1481
1482 float Client::getAnimationTime()
1483 {
1484         return m_animation_time;
1485 }
1486
1487 int Client::getCrackLevel()
1488 {
1489         return m_crack_level;
1490 }
1491
1492 v3s16 Client::getCrackPos()
1493 {
1494         return m_crack_pos;
1495 }
1496
1497 void Client::setCrack(int level, v3s16 pos)
1498 {
1499         int old_crack_level = m_crack_level;
1500         v3s16 old_crack_pos = m_crack_pos;
1501
1502         m_crack_level = level;
1503         m_crack_pos = pos;
1504
1505         if(old_crack_level >= 0 && (level < 0 || pos != old_crack_pos))
1506         {
1507                 // remove old crack
1508                 addUpdateMeshTaskForNode(old_crack_pos, false, true);
1509         }
1510         if(level >= 0 && (old_crack_level < 0 || pos != old_crack_pos))
1511         {
1512                 // add new crack
1513                 addUpdateMeshTaskForNode(pos, false, true);
1514         }
1515 }
1516
1517 u16 Client::getHP()
1518 {
1519         LocalPlayer *player = m_env.getLocalPlayer();
1520         assert(player);
1521         return player->hp;
1522 }
1523
1524 bool Client::getChatMessage(std::wstring &res)
1525 {
1526         if (m_chat_queue.empty())
1527                 return false;
1528
1529         ChatMessage *chatMessage = m_chat_queue.front();
1530         m_chat_queue.pop();
1531
1532         res = L"";
1533
1534         switch (chatMessage->type) {
1535                 case CHATMESSAGE_TYPE_RAW:
1536                 case CHATMESSAGE_TYPE_ANNOUNCE:
1537                 case CHATMESSAGE_TYPE_SYSTEM:
1538                         res = chatMessage->message;
1539                         break;
1540                 case CHATMESSAGE_TYPE_NORMAL: {
1541                         if (!chatMessage->sender.empty())
1542                                 res = L"<" + chatMessage->sender + L"> " + chatMessage->message;
1543                         else
1544                                 res = chatMessage->message;
1545                         break;
1546                 }
1547                 default:
1548                         break;
1549         }
1550
1551         delete chatMessage;
1552         return true;
1553 }
1554
1555 void Client::typeChatMessage(const std::wstring &message)
1556 {
1557         // Discard empty line
1558         if (message.empty())
1559                 return;
1560
1561         // If message was consumed by script API, don't send it to server
1562         if (m_mods_loaded && m_script->on_sending_message(wide_to_utf8(message)))
1563                 return;
1564
1565         // Send to others
1566         sendChatMessage(message);
1567 }
1568
1569 void Client::addUpdateMeshTask(v3s16 p, bool ack_to_server, bool urgent)
1570 {
1571         // Check if the block exists to begin with. In the case when a non-existing
1572         // neighbor is automatically added, it may not. In that case we don't want
1573         // to tell the mesh update thread about it.
1574         MapBlock *b = m_env.getMap().getBlockNoCreateNoEx(p);
1575         if (b == NULL)
1576                 return;
1577
1578         m_mesh_update_thread.updateBlock(&m_env.getMap(), p, ack_to_server, urgent);
1579 }
1580
1581 void Client::addUpdateMeshTaskWithEdge(v3s16 blockpos, bool ack_to_server, bool urgent)
1582 {
1583         try{
1584                 addUpdateMeshTask(blockpos, ack_to_server, urgent);
1585         }
1586         catch(InvalidPositionException &e){}
1587
1588         // Leading edge
1589         for (int i=0;i<6;i++)
1590         {
1591                 try{
1592                         v3s16 p = blockpos + g_6dirs[i];
1593                         addUpdateMeshTask(p, false, urgent);
1594                 }
1595                 catch(InvalidPositionException &e){}
1596         }
1597 }
1598
1599 void Client::addUpdateMeshTaskForNode(v3s16 nodepos, bool ack_to_server, bool urgent)
1600 {
1601         {
1602                 v3s16 p = nodepos;
1603                 infostream<<"Client::addUpdateMeshTaskForNode(): "
1604                                 <<"("<<p.X<<","<<p.Y<<","<<p.Z<<")"
1605                                 <<std::endl;
1606         }
1607
1608         v3s16 blockpos          = getNodeBlockPos(nodepos);
1609         v3s16 blockpos_relative = blockpos * MAP_BLOCKSIZE;
1610
1611         try{
1612                 addUpdateMeshTask(blockpos, ack_to_server, urgent);
1613         }
1614         catch(InvalidPositionException &e) {}
1615
1616         // Leading edge
1617         if(nodepos.X == blockpos_relative.X){
1618                 try{
1619                         v3s16 p = blockpos + v3s16(-1,0,0);
1620                         addUpdateMeshTask(p, false, urgent);
1621                 }
1622                 catch(InvalidPositionException &e){}
1623         }
1624
1625         if(nodepos.Y == blockpos_relative.Y){
1626                 try{
1627                         v3s16 p = blockpos + v3s16(0,-1,0);
1628                         addUpdateMeshTask(p, false, urgent);
1629                 }
1630                 catch(InvalidPositionException &e){}
1631         }
1632
1633         if(nodepos.Z == blockpos_relative.Z){
1634                 try{
1635                         v3s16 p = blockpos + v3s16(0,0,-1);
1636                         addUpdateMeshTask(p, false, urgent);
1637                 }
1638                 catch(InvalidPositionException &e){}
1639         }
1640 }
1641
1642 ClientEvent *Client::getClientEvent()
1643 {
1644         FATAL_ERROR_IF(m_client_event_queue.empty(),
1645                         "Cannot getClientEvent, queue is empty.");
1646
1647         ClientEvent *event = m_client_event_queue.front();
1648         m_client_event_queue.pop();
1649         return event;
1650 }
1651
1652 const Address Client::getServerAddress()
1653 {
1654         return m_con->GetPeerAddress(PEER_ID_SERVER);
1655 }
1656
1657 float Client::mediaReceiveProgress()
1658 {
1659         if (m_media_downloader)
1660                 return m_media_downloader->getProgress();
1661
1662         return 1.0; // downloader only exists when not yet done
1663 }
1664
1665 typedef struct TextureUpdateArgs {
1666         gui::IGUIEnvironment *guienv;
1667         u64 last_time_ms;
1668         u16 last_percent;
1669         const wchar_t* text_base;
1670         ITextureSource *tsrc;
1671 } TextureUpdateArgs;
1672
1673 void texture_update_progress(void *args, u32 progress, u32 max_progress)
1674 {
1675                 TextureUpdateArgs* targs = (TextureUpdateArgs*) args;
1676                 u16 cur_percent = ceil(progress / (double) max_progress * 100.);
1677
1678                 // update the loading menu -- if neccessary
1679                 bool do_draw = false;
1680                 u64 time_ms = targs->last_time_ms;
1681                 if (cur_percent != targs->last_percent) {
1682                         targs->last_percent = cur_percent;
1683                         time_ms = porting::getTimeMs();
1684                         // only draw when the user will notice something:
1685                         do_draw = (time_ms - targs->last_time_ms > 100);
1686                 }
1687
1688                 if (do_draw) {
1689                         targs->last_time_ms = time_ms;
1690                         std::basic_stringstream<wchar_t> strm;
1691                         strm << targs->text_base << " " << targs->last_percent << "%...";
1692                         RenderingEngine::draw_load_screen(strm.str(), targs->guienv, targs->tsrc, 0,
1693                                 72 + (u16) ((18. / 100.) * (double) targs->last_percent), true);
1694                 }
1695 }
1696
1697 void Client::afterContentReceived()
1698 {
1699         infostream<<"Client::afterContentReceived() started"<<std::endl;
1700         assert(m_itemdef_received); // pre-condition
1701         assert(m_nodedef_received); // pre-condition
1702         assert(mediaReceived()); // pre-condition
1703
1704         const wchar_t* text = wgettext("Loading textures...");
1705
1706         // Clear cached pre-scaled 2D GUI images, as this cache
1707         // might have images with the same name but different
1708         // content from previous sessions.
1709         guiScalingCacheClear();
1710
1711         // Rebuild inherited images and recreate textures
1712         infostream<<"- Rebuilding images and textures"<<std::endl;
1713         RenderingEngine::draw_load_screen(text, guienv, m_tsrc, 0, 70);
1714         m_tsrc->rebuildImagesAndTextures();
1715         delete[] text;
1716
1717         // Rebuild shaders
1718         infostream<<"- Rebuilding shaders"<<std::endl;
1719         text = wgettext("Rebuilding shaders...");
1720         RenderingEngine::draw_load_screen(text, guienv, m_tsrc, 0, 71);
1721         m_shsrc->rebuildShaders();
1722         delete[] text;
1723
1724         // Update node aliases
1725         infostream<<"- Updating node aliases"<<std::endl;
1726         text = wgettext("Initializing nodes...");
1727         RenderingEngine::draw_load_screen(text, guienv, m_tsrc, 0, 72);
1728         m_nodedef->updateAliases(m_itemdef);
1729         for (const auto &path : getTextureDirs()) {
1730                 TextureOverrideSource override_source(path + DIR_DELIM + "override.txt");
1731                 m_nodedef->applyTextureOverrides(override_source.getNodeTileOverrides());
1732                 m_itemdef->applyTextureOverrides(override_source.getItemTextureOverrides());
1733         }
1734         m_nodedef->setNodeRegistrationStatus(true);
1735         m_nodedef->runNodeResolveCallbacks();
1736         delete[] text;
1737
1738         // Update node textures and assign shaders to each tile
1739         infostream<<"- Updating node textures"<<std::endl;
1740         TextureUpdateArgs tu_args;
1741         tu_args.guienv = guienv;
1742         tu_args.last_time_ms = porting::getTimeMs();
1743         tu_args.last_percent = 0;
1744         tu_args.text_base =  wgettext("Initializing nodes");
1745         tu_args.tsrc = m_tsrc;
1746         m_nodedef->updateTextures(this, texture_update_progress, &tu_args);
1747         delete[] tu_args.text_base;
1748
1749         // Start mesh update thread after setting up content definitions
1750         infostream<<"- Starting mesh update thread"<<std::endl;
1751         m_mesh_update_thread.start();
1752
1753         m_state = LC_Ready;
1754         sendReady();
1755
1756         if (m_mods_loaded)
1757                 m_script->on_client_ready(m_env.getLocalPlayer());
1758
1759         text = wgettext("Done!");
1760         RenderingEngine::draw_load_screen(text, guienv, m_tsrc, 0, 100);
1761         infostream<<"Client::afterContentReceived() done"<<std::endl;
1762         delete[] text;
1763 }
1764
1765 float Client::getRTT()
1766 {
1767         return m_con->getPeerStat(PEER_ID_SERVER,con::AVG_RTT);
1768 }
1769
1770 float Client::getCurRate()
1771 {
1772         return (m_con->getLocalStat(con::CUR_INC_RATE) +
1773                         m_con->getLocalStat(con::CUR_DL_RATE));
1774 }
1775
1776 void Client::makeScreenshot()
1777 {
1778         irr::video::IVideoDriver *driver = RenderingEngine::get_video_driver();
1779         irr::video::IImage* const raw_image = driver->createScreenShot();
1780
1781         if (!raw_image)
1782                 return;
1783
1784         time_t t = time(NULL);
1785         struct tm *tm = localtime(&t);
1786
1787         char timetstamp_c[64];
1788         strftime(timetstamp_c, sizeof(timetstamp_c), "%Y%m%d_%H%M%S", tm);
1789
1790         std::string screenshot_dir;
1791
1792         if (fs::IsPathAbsolute(g_settings->get("screenshot_path")))
1793                 screenshot_dir = g_settings->get("screenshot_path");
1794         else
1795                 screenshot_dir = porting::path_user + DIR_DELIM + g_settings->get("screenshot_path");
1796
1797         std::string filename_base = screenshot_dir
1798                         + DIR_DELIM
1799                         + std::string("screenshot_")
1800                         + std::string(timetstamp_c);
1801         std::string filename_ext = "." + g_settings->get("screenshot_format");
1802         std::string filename;
1803
1804         // Create the directory if it doesn't already exist.
1805         // Otherwise, saving the screenshot would fail.
1806         fs::CreateDir(screenshot_dir);
1807
1808         u32 quality = (u32)g_settings->getS32("screenshot_quality");
1809         quality = MYMIN(MYMAX(quality, 0), 100) / 100.0 * 255;
1810
1811         // Try to find a unique filename
1812         unsigned serial = 0;
1813
1814         while (serial < SCREENSHOT_MAX_SERIAL_TRIES) {
1815                 filename = filename_base + (serial > 0 ? ("_" + itos(serial)) : "") + filename_ext;
1816                 std::ifstream tmp(filename.c_str());
1817                 if (!tmp.good())
1818                         break;  // File did not apparently exist, we'll go with it
1819                 serial++;
1820         }
1821
1822         if (serial == SCREENSHOT_MAX_SERIAL_TRIES) {
1823                 infostream << "Could not find suitable filename for screenshot" << std::endl;
1824         } else {
1825                 irr::video::IImage* const image =
1826                                 driver->createImage(video::ECF_R8G8B8, raw_image->getDimension());
1827
1828                 if (image) {
1829                         raw_image->copyTo(image);
1830
1831                         std::ostringstream sstr;
1832                         if (driver->writeImageToFile(image, filename.c_str(), quality)) {
1833                                 sstr << "Saved screenshot to '" << filename << "'";
1834                         } else {
1835                                 sstr << "Failed to save screenshot '" << filename << "'";
1836                         }
1837                         pushToChatQueue(new ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
1838                                         utf8_to_wide(sstr.str())));
1839                         infostream << sstr.str() << std::endl;
1840                         image->drop();
1841                 }
1842         }
1843
1844         raw_image->drop();
1845 }
1846
1847 bool Client::shouldShowMinimap() const
1848 {
1849         return !m_minimap_disabled_by_server;
1850 }
1851
1852 void Client::pushToEventQueue(ClientEvent *event)
1853 {
1854         m_client_event_queue.push(event);
1855 }
1856
1857 void Client::showMinimap(const bool show)
1858 {
1859         m_game_ui->showMinimap(show);
1860 }
1861
1862 // IGameDef interface
1863 // Under envlock
1864 IItemDefManager* Client::getItemDefManager()
1865 {
1866         return m_itemdef;
1867 }
1868 const NodeDefManager* Client::getNodeDefManager()
1869 {
1870         return m_nodedef;
1871 }
1872 ICraftDefManager* Client::getCraftDefManager()
1873 {
1874         return NULL;
1875         //return m_craftdef;
1876 }
1877 ITextureSource* Client::getTextureSource()
1878 {
1879         return m_tsrc;
1880 }
1881 IWritableShaderSource* Client::getShaderSource()
1882 {
1883         return m_shsrc;
1884 }
1885
1886 u16 Client::allocateUnknownNodeId(const std::string &name)
1887 {
1888         errorstream << "Client::allocateUnknownNodeId(): "
1889                         << "Client cannot allocate node IDs" << std::endl;
1890         FATAL_ERROR("Client allocated unknown node");
1891
1892         return CONTENT_IGNORE;
1893 }
1894 ISoundManager* Client::getSoundManager()
1895 {
1896         return m_sound;
1897 }
1898 MtEventManager* Client::getEventManager()
1899 {
1900         return m_event;
1901 }
1902
1903 ParticleManager* Client::getParticleManager()
1904 {
1905         return &m_particle_manager;
1906 }
1907
1908 scene::IAnimatedMesh* Client::getMesh(const std::string &filename, bool cache)
1909 {
1910         StringMap::const_iterator it = m_mesh_data.find(filename);
1911         if (it == m_mesh_data.end()) {
1912                 errorstream << "Client::getMesh(): Mesh not found: \"" << filename
1913                         << "\"" << std::endl;
1914                 return NULL;
1915         }
1916         const std::string &data    = it->second;
1917
1918         // Create the mesh, remove it from cache and return it
1919         // This allows unique vertex colors and other properties for each instance
1920 #if IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR > 8
1921         io::IReadFile *rfile = RenderingEngine::get_filesystem()->createMemoryReadFile(
1922                         data.c_str(), data.size(), filename.c_str());
1923 #else
1924         Buffer<char> data_rw(data.c_str(), data.size()); // Const-incorrect Irrlicht
1925         io::IReadFile *rfile = RenderingEngine::get_filesystem()->createMemoryReadFile(
1926                         *data_rw, data_rw.getSize(), filename.c_str());
1927 #endif
1928         FATAL_ERROR_IF(!rfile, "Could not create/open RAM file");
1929
1930         scene::IAnimatedMesh *mesh = RenderingEngine::get_scene_manager()->getMesh(rfile);
1931         rfile->drop();
1932         if (!mesh)
1933                 return nullptr;
1934         mesh->grab();
1935         if (!cache)
1936                 RenderingEngine::get_mesh_cache()->removeMesh(mesh);
1937         return mesh;
1938 }
1939
1940 const std::string* Client::getModFile(std::string filename)
1941 {
1942         // strip dir delimiter from beginning of path
1943         auto pos = filename.find_first_of(':');
1944         if (pos == std::string::npos)
1945                 return nullptr;
1946         pos++;
1947         auto pos2 = filename.find_first_not_of('/', pos);
1948         if (pos2 > pos)
1949                 filename.erase(pos, pos2 - pos);
1950
1951         StringMap::const_iterator it = m_mod_vfs.find(filename);
1952         if (it == m_mod_vfs.end())
1953                 return nullptr;
1954         return &it->second;
1955 }
1956
1957 bool Client::registerModStorage(ModMetadata *storage)
1958 {
1959         if (m_mod_storages.find(storage->getModName()) != m_mod_storages.end()) {
1960                 errorstream << "Unable to register same mod storage twice. Storage name: "
1961                                 << storage->getModName() << std::endl;
1962                 return false;
1963         }
1964
1965         m_mod_storages[storage->getModName()] = storage;
1966         return true;
1967 }
1968
1969 void Client::unregisterModStorage(const std::string &name)
1970 {
1971         std::unordered_map<std::string, ModMetadata *>::const_iterator it =
1972                 m_mod_storages.find(name);
1973         if (it != m_mod_storages.end()) {
1974                 // Save unconditionaly on unregistration
1975                 it->second->save(getModStoragePath());
1976                 m_mod_storages.erase(name);
1977         }
1978 }
1979
1980 std::string Client::getModStoragePath() const
1981 {
1982         return porting::path_user + DIR_DELIM + "client" + DIR_DELIM + "mod_storage";
1983 }
1984
1985 /*
1986  * Mod channels
1987  */
1988
1989 bool Client::joinModChannel(const std::string &channel)
1990 {
1991         if (m_modchannel_mgr->channelRegistered(channel))
1992                 return false;
1993
1994         NetworkPacket pkt(TOSERVER_MODCHANNEL_JOIN, 2 + channel.size());
1995         pkt << channel;
1996         Send(&pkt);
1997
1998         m_modchannel_mgr->joinChannel(channel, 0);
1999         return true;
2000 }
2001
2002 bool Client::leaveModChannel(const std::string &channel)
2003 {
2004         if (!m_modchannel_mgr->channelRegistered(channel))
2005                 return false;
2006
2007         NetworkPacket pkt(TOSERVER_MODCHANNEL_LEAVE, 2 + channel.size());
2008         pkt << channel;
2009         Send(&pkt);
2010
2011         m_modchannel_mgr->leaveChannel(channel, 0);
2012         return true;
2013 }
2014
2015 bool Client::sendModChannelMessage(const std::string &channel, const std::string &message)
2016 {
2017         if (!m_modchannel_mgr->canWriteOnChannel(channel))
2018                 return false;
2019
2020         if (message.size() > STRING_MAX_LEN) {
2021                 warningstream << "ModChannel message too long, dropping before sending "
2022                                 << " (" << message.size() << " > " << STRING_MAX_LEN << ", channel: "
2023                                 << channel << ")" << std::endl;
2024                 return false;
2025         }
2026
2027         // @TODO: do some client rate limiting
2028         NetworkPacket pkt(TOSERVER_MODCHANNEL_MSG, 2 + channel.size() + 2 + message.size());
2029         pkt << channel << message;
2030         Send(&pkt);
2031         return true;
2032 }
2033
2034 ModChannel* Client::getModChannel(const std::string &channel)
2035 {
2036         return m_modchannel_mgr->getModChannel(channel);
2037 }