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