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