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