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