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